<template>
  <div class="app-container">
    <el-row>
      <el-col :span="22">
        <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true">
          <el-form-item label="日期" prop="startDate">
            <el-date-picker
              v-model="queryParams.startDate"
              type="date"
              value-format="yyyy-MM-dd"
              @change="getList"
              placeholder="开始日期"
              :clearable="false"
              style="width: 135px">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="至" prop="endDate">
            <el-date-picker
              v-model="queryParams.endDate"
              type="date"
              value-format="yyyy-MM-dd"
              @change="getList"
              placeholder="结束日期"
              :clearable="false"
              style="width: 135px">
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="statusGroup">
            <el-checkbox-group v-model="queryParams.statusGroup" size="mini" @change="getList">
              <el-checkbox-button
                v-for="dict in dict.type.task_status"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.value === '0' ? '待查看' : dict.label }}
              </el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item prop="priority">
            <el-select
              v-model="queryParams.priority"
              @change="getList"
              clearable
              placeholder="优先级"
              style="width: 85px">
              <el-option
                v-for="dict in dict.type.task_priority"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value">
                <el-tag :color="priorityColorMap[dict.value]" effect="dark" :hit="false">
                  {{ dict.label }}
                </el-tag>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="2">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >日常任务
        </el-button>
      </el-col>
    </el-row>

    <el-table
      class="view-table"
      :data="tableData"
      size="mini"
      @cell-mouse-enter="cellMouseEnter"
      @cell-mouse-leave="cellMouseLeave"
      :cell-style="cellStyle"
      @cell-click="cellClick"
      @cell-dblclick="cellDbClick"
      @row-click="rowClick"
      height="calc(100vh - 120px)"
      border>
      <el-table-column fixed prop="id" label="编号" align="center" width="50"/>
      <el-table-column fixed prop="taskName" label="任务名称" align="center" class="task-name-cell" width="180"/>
      <el-table-column fixed prop="executorName" label="主负责人" align="center" width="90">
        <template slot-scope="scope">
          <div style="line-height: 15px">{{ scope.row.executorName }}</div>
          <el-tag size="mini" :type="statusMap[scope.row.status].type">
            {{ statusMap[scope.row.status].name + ' ' + scope.row.progressValue + '%' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed prop="" label="优先级" align="center" width="60">
        <template slot-scope="scope">
          <el-tag :color="priorityColorMap[scope.row.priority]" effect="dark" :hit="false">
            {{ getTaskPriority(scope.row.priority) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" v-for="header in tableHeaders" :key="header.day" :prop="header.day" width="42">
        <template slot="header">
          <el-popover placement="top" trigger="hover">
            <div>{{ header.day }}已反馈工时：
              <span style="font-size: 16px;font-weight: bold; margin-right: 5px">{{ header.dayHours }}</span>
              小时
            </div>
            <div slot="reference" style="width:40px;text-align: center;cursor: pointer">
              <div style="font-size: 10px;">{{ header.day }}</div>
              <div v-if="header.week=='周六'" class="view-cell" style="color: #1c84c6">{{ header.week }}</div>
              <div v-else-if="header.week=='周日'" class="view-cell" style="color: #1c84c6">{{ header.week }}</div>
              <div v-else-if="header.week=='今日'" class="view-cell" style="color: #00E704">{{ header.week }}</div>
              <div v-else class="view-cell">{{ header.week }}</div>
            </div>
          </el-popover>
        </template>
        <template slot-scope="scope">
          <span v-if="scope.row[header.day].comment" class="comment-badge"></span>
          <span v-if="scope.row[header.day].audit" class="audit-badge"></span>
          <el-popover
            v-if="scope.row[header.day].value!=''"
            placement="top"
            width="700"
            trigger="click">
            <el-table :data="feedbacks" border size="mini">
              <el-table-column width="75" label="反馈状态" align="center">
                <template slot-scope="temp">
                  <div>{{ getFeedbackTypeName(temp.row.feedbackType) }}</div>
                </template>
              </el-table-column>
              <el-table-column width="60" property="userName" label="反馈人" align="center"/>
              <el-table-column width="55" label="完成度" align="center">
                <template slot-scope="temp">
                  <div>{{ !temp.row.value ? '' : temp.row.value + '%' }}</div>
                </template>
              </el-table-column>
              <el-table-column width="60" prop="hours" label="工时(h)" align="center"/>
              <el-table-column width="110" property="createTime" label="反馈时间" align="center">
                <template slot-scope="temp">
                  <div>{{ parseTime(temp.row.createTime) }}</div>
                </template>
              </el-table-column>
              <el-table-column label="反馈备注" align="center">
                <template slot-scope="temp">
                  <div>
                    <span>{{ temp.row.description }}</span>
                    <span v-for="(file,index) in temp.row.fileList">
                                <a :href="file.url" style="color: darkgreen">
                                  <span style="margin-left: 5px">{{ file.name }}</span>
                                </a>
                    </span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="当前达成进度" width="100px" align="center">
                <template slot-scope="temp">
                  <el-popover
                    v-if="temp.row.descriptionDetail&&temp.row.descriptionDetail.length>0"
                    placement="top"
                    width="600"
                    trigger="hover">
                    <div v-html="temp.row.descriptionDetail"></div>
                    <el-button slot="reference" type="text">详情</el-button>
                  </el-popover>
                  <span
                    v-if="(temp.row.feedbackType === '4'||temp.row.feedbackType === '5')&& scope.row.executor===userId && temp.row.commentConfirm!='1'"
                    style="margin-left: 10px">
                  <el-button type="text" icon="el-icon-thumb" size="mini"
                             @click="confirmComment(temp.row)">确认</el-button>
                  </span>
                </template>
              </el-table-column>
            </el-table>
            <div slot="reference" style="line-height:40px;font-size: 10px;cursor: pointer">
              {{ scope.row[header.day].value }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="反馈任务" :visible.sync="open" width="680px" class="feed-dialog" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" size="mini" label-width="106px">
        <el-form-item label="任务名称">
          <div>{{ form.taskName }}</div>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属项目">
              <div>{{ form.projectName }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="反馈时间">
              <div>{{ form.feedbackDate }}</div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划工时">
              <el-input-number v-model="form.planHours" :min="0.1" :step="0.1"
                               :step-strictly="true"
                               :controls="false"></el-input-number>
              <span style="margin-left: 5px">小时</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已反馈工时">
              <span>{{ form.feedbackHours }}</span>
              <span style="margin-left: 5px">小时</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作时长" prop="hours">
              <el-input-number v-model="form.hours" :min="0.1" :max="24" :step="0.1"
                               :step-strictly="true" :controls="false"></el-input-number>
              <span style="margin-left: 5px">小时</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务进度" prop="value">
              <el-input-number v-model="form.value" :min="1" :max="100" :step="1"
                               :step-strictly="true" :controls="false"></el-input-number>
              <span style="margin-left: 5px">%</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="附件" prop="fileUrl">
              <file-upload ref="fu" @getFileUrl="getFileUrl" @removeFile="removeFile"></file-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="反馈描述" prop="description">
          <el-input v-model="form.description" type="textarea" autosize/>
        </el-form-item>
        <el-form-item label="当前达成进度" prop="descriptionDetail">
          <rich-text-editor v-model="form.descriptionDetail"></rich-text-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" size="mini">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="detailForm.id+'、'+detailForm.taskName" :visible.sync="openDetail" width="900px" class="feed-dialog"
               :close-on-click-modal="true"
               append-to-body>
      <task-detail :detailForm="detailForm"></task-detail>
    </el-dialog>

    <el-dialog title="新增日常任务" :visible.sync="openAdd" width="800px" class="feed-dialog" append-to-body
               @close="cancelAddForm">
      <el-form ref="addForm" :model="addForm" :rules="addRules" size="mini" label-width="115px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="addForm.taskName" placeholder="请输入任务名称"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="beginDate">
              <el-date-picker
                v-model="addForm.beginDate"
                type="date"
                value-format="yyyy-MM-dd"
                @change="checkDates(addForm.beginDate,addForm.endDate)"
                style="width: 220px"
                placeholder="开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker
                v-model="addForm.endDate"
                @change="checkDates(addForm.beginDate,addForm.endDate)"
                type="date"
                value-format="yyyy-MM-dd"
                style="width: 220px"
                placeholder="开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="优先级">
              <el-select
                v-model="addForm.priority"
                style="width: 220px"
                placeholder="任务优先级">
                <el-option
                  v-for="dict in dict.type.task_priority"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                  <span v-if="dict.value==='1'" style="color: #fa8888;margin-right: 5px">!!!</span>
                  <span v-else-if="dict.value==='2'" style="color: #fb7fb7;margin-right: 5px">!!</span>
                  <span v-else-if="dict.value==='3'" style="color: #40e0c3;margin-right: 5px">!</span>
                  <span v-else style="color: #5dcfff;margin-right: 5px">!</span>
                  <span>{{ dict.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务附件">
              <file-upload ref="afu" :files="addForm.fileList" @getFileUrl="getFileUrl"
                           @removeFile="removeFile"></file-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务描述" prop="description">
          <rich-text-editor v-model="addForm.description"></rich-text-editor>
        </el-form-item>
        <el-form-item label="审核流程">
          <audit-module ref="auditModule" :audit-users="auditUsers"
                        :project-audit-configs="projectAuditConfigs"></audit-module>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitAddForm">确 定</el-button>
        <el-button size="mini" @click="cancelAddForm">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getTask,
  listView,
  addTaskFeedback,
  getFeedbackList,
  confirmComment,
  addTask,
  updateTask, projectAuditConfigs
} from "@/api/task/task";
import DateUtil from "@/utils/date"
import TaskDetail from "./components/taskDetail"
import FileUpload from "@/components/FileUpload"
import RichTextEditor from '@/components/RichTextEditor'
import AuditModule from './components/auditModule'

import {mapGetters} from 'vuex'
import task from "@/views/mixins/task";
import {listProject} from "@/api/task/project";
import {getAuditUsers} from "@/api/system/user";


export default {
  components: {TaskDetail, FileUpload, RichTextEditor, AuditModule},
  dicts: ['task_status', 'feedback_type', 'task_priority'],
  mixins: [task],
  computed: {
    ...mapGetters(['userId'])
  },
  data() {
    let validateValue = (rule, value, callback) => {
      if (value === null || value === undefined) {
        return callback(new Error('进度不能为空'));
      }
      if (!Number.isInteger(value) || value < 0 || value > 100) {
        return callback(new Error('进度值必须为0到100的整数'));
      }
      return callback();
    };
    let validateHours = (rule, value, callback) => {
      // const regex = /^(?:[0-1]?\d|2[0-4])(\.\d)?$/;
      if (value < 0 || value > 24) {
        return callback(new Error('工时必须为0到24的数,最小维度为0.1小时'));
      }
      if (!value) {
        return callback(new Error('工时不能为空'));
      }
      return callback();
    };
    let validateDescription = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('反馈描述不能为空'));
      }
      if (value.length < 5 || value.length > 500) {
        return callback(new Error('反馈描述字符数在5到500之间'));
      }
      return callback();
    };
    let validateDescriptionDetail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('当前达成进度不能为空'));
      }
      let text = value.replaceAll('<p>', '').replaceAll('</p>', '').replaceAll('<br>', '').replaceAll('&nbsp;', '').trim();
      if (text.length === 0) {
        return callback(new Error('当前达成进度不能为空'));
      }
      return callback();
    };

    return {
      queryParams: {
        projectId: undefined,
        startDate: undefined,
        endDate: undefined,
        statusGroup: ['0', '1', '2', '3'],
        priority: undefined,
        userId: undefined
      },
      projectTree: [],
      tableHeaders: [],
      tableData: [],

      open: false,
      form: {},
      feedbacks: [],
      rules: {
        feedbackType: [
          {required: true, message: "反馈类型不能为空", trigger: "change"}
        ],
        value: [
          {required: true, validator: validateValue, trigger: 'blur'}
        ],
        hours: [
          {required: true, validator: validateHours, trigger: 'blur'}
        ],
        description: [
          {required: true, validator: validateDescription, trigger: "blur"},
        ],
        descriptionDetail: [
          {required: true, validator: validateDescriptionDetail, trigger: "change"},
        ]
      },
      openDetail: false,
      detailForm: {},
      openAdd: false,
      addForm: {},
      addRules: {
        taskName: [
          {required: true, message: "任务名称不能为空", trigger: "blur"}
        ],
        beginDate: [
          {required: true, message: "开始时间不能为空", trigger: "change"}
        ],
        endDate: [
          {required: true, message: "结束时间不能为空", trigger: "change"}
        ]
      },
      projectAuditConfigs: [],
      auditUsers: []
    }
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      this.$set(this.queryParams, 'startDate', DateUtil.beforeDay(null, 15))
      this.$set(this.queryParams, 'endDate', DateUtil.afterDay(null, 15))
      this.getList()
    },
    getList() {
      if (DateUtil.unix(this.queryParams.startDate) > DateUtil.unix(this.queryParams.endDate)) {
        this.$message.warning("开始时间不能超过结束时间")
        return
      }
      let dayDiff = DateUtil.dayDiff(this.queryParams.startDate, this.queryParams.endDate);
      if (dayDiff > 366) {
        this.$message.warning("时间跨度不可超过一年")
        return
      }
      this.queryParams.userId = this.userId
      listView(this.queryParams).then(res => {
        let data = res.data.data || []
        if (data.length > 0) {
          this.tableHeaders = res.data.headers.map(header => {
            let dayHours = 0;
            data.forEach(item => {
              if (item[header.day].hours) {
                dayHours += item[header.day].hours
              }
            })
            header['dayHours'] = dayHours
            return header;
          })
        } else {
          this.tableHeaders = res.data.headers
        }
        this.tableData = res.data.data
      })
    },

    cellStyle({row, column, rowIndex, columnIndex}) {
      let style = {
        // fontSize: '12px',
        padding: '2px 0'
      }
      if (row[column.property]) {
        style.background = this.cellColorMap[row[column.property].color]
      }
      return style
    },

    cellClick(row, column, cell, event) {
      this.feedbacks = []
      if (!row[column.property].value || row[column.property].value === '') {
        return;
      }
      let date = row[column.property].date
      if (DateUtil.unix(date) > DateUtil.unix()) {
        return;
      }
      getFeedbackList(row.id, date).then(res => {
        this.feedbacks = res.data.map(item => {
          item['executor'] = row.executor
          return item
        })
      })
    },
    cellDbClick(row, column, cell, event) {
      if (row.status === '4' || row.status === '5') {
        this.$message.warning("任务已完成,不可反馈")
        return;
      }
      if (row.status === '5') {
        this.$message.warning("任务已终止,不可反馈")
        return;
      }
      let feedbackDate = DateUtil.getFeedBackDate(this.queryParams.startDate, this.queryParams.endDate, column.property)
      if (DateUtil.unix(feedbackDate) > DateUtil.unix()) {
        this.$message.warning("反馈时间不能超过:" + DateUtil.day())
        return;
      }

      this.form = {
        id: undefined,
        taskName: row.taskName,
        taskId: row.id,
        projectName: row.projectName,
        feedbackDate: feedbackDate,
        planHours: row.planHours,
        feedbackHours: row.feedbackHours,
        feedbackType: '1',
        value: row.progressValue,
        hours: undefined,
        fileUrl: undefined,
        description: undefined
      };
      this.open = true
    },
    rowClick(row, column, event) {
      if (column.property != "taskName") {
        return
      }
      getTask(row.id).then(res => {
        this.detailForm = res.data
        this.openDetail = true
      })
    },

    feedbackTypeChange(val) {
      if (val === '2') {
        this.form.value = 100
      } else {
        this.form.value = undefined
      }
    },
    // 取消按钮
    cancel() {
      this.$refs.fu.clear();
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        taskName: undefined,
        taskId: undefined,
        projectName: undefined,
        feedbackDate: undefined,
        feedbackType: undefined,
        value: undefined,
        hours: undefined,
        fileUrl: undefined,
        description: undefined
      };
      this.resetForm("form");
    },
    getFileUrl(val) {
      this.form.files = val
    },
    removeFile(val) {
      this.form.files = val
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.files) {
            let files = this.form.files.map(item => item.name);
            this.form.fileUrl = JSON.stringify(files)
          }
          let descriptionDetail = _.cloneDeep(this.form.descriptionDetail)
          if (!this.checkRichText(descriptionDetail)) {
            this.form.descriptionDetail = null
          }
          addTaskFeedback(this.form).then(res => {
            if (res.code === 'S.F-2001') {
              let message = ''
              res.data.forEach(item => {
                message += item.taskName + '   '
              })
              this.$alert(message, res.message);
            } else {
              this.$message.success("反馈成功");
              this.open = false;
              this.getList();
            }
          });
        }
      })
    },

    getFeedbackTypeName(type) {
      if (type === '1') {
        return '进度反馈'
      } else if (type === '2') {
        return '完成'
      } else if (type === '3') {
        return '终止'
      } else if (type === '4') {
        return '评论'
      }
      return '审批'
    },
    /** 确认收到评论 */
    confirmComment(row) {
      confirmComment({feedbackId: row.id}).then(res => {
        if (res.code === '2000') {
          this.$message.success("操作成功")
          this.getList()
        }
      })
    },

    hoursChange() {
      let planHours = Number.parseFloat(this.form.planHours)
      let hours = Number.parseFloat(this.form.hours)
      if (planHours && hours) {
        let feedbackHours = Number.parseFloat(this.form.feedbackHours)
        let percent = (hours + feedbackHours) / planHours * 100;
        let value = Number.parseInt(percent > 100 ? 100 : percent);
        this.form.value = value === 0 ? 1 : value
      }
    },


    handleAdd() {
      this.resetAdd();
      this.openAdd = true;
      this.$set(this.addForm, 'priority', '4')
      this.$set(this.addForm, 'executor', this.userId)
      this.$set(this.addForm, 'projectId', 751562823)
      projectAuditConfigs({projectId: this.addForm.projectId}).then(res => {
        this.projectAuditConfigs = res.data
      })
      getAuditUsers().then(res => {
        this.auditUsers = res.data
      })
    },
    submitAddForm() {
      if (DateUtil.unix(this.addForm.beginDate) > DateUtil.unix(this.addForm.endDate)) {
        this.$message.warning("开始时间不能超过结束时间")
        return
      }
      this.$refs["addForm"].validate(valid => {
        if (valid) {
          if (this.addForm.files) {
            let tempFiles = this.addForm.files.map(item => item.name);
            this.addForm.fileUrl = JSON.stringify(tempFiles)
          }
          this.addForm['auditConfigs'] = this.$refs.auditModule.getAuditConfigs()
          this.addForm.checkTaskConflict = false;
          addTask(this.addForm).then(res => {
            this.$message.success("新增成功");
            this.openAdd = false;
            this.resetAdd();
            this.getList();
          });

        }
      });
    },
    cancelAddForm() {
      this.$refs.afu.clear()
      this.resetAdd()
      this.openAdd = false;
    },
    resetAdd() {
      this.addForm = {
        id: undefined,
        taskName: undefined,
        projectId: undefined,
        executor: undefined,
        planHours: undefined,
        beginDate: undefined,
        endDate: undefined,
        description: undefined,
        priority: undefined
      };
      this.resetForm("addForm");
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep.el-table .cell {
  padding: 0px;
}

::v-deep.el-table th.el-table__cell > .cell {
  padding: 0px;
}

.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
  margin-bottom: 10px;
}

.view-cell {
  width: 40px;
  font-size: 10px;
  text-align: center
}

.comment-badge {
  height: 10px;
  width: 10px;
  border-radius: 5px;
  background-color: #409eff;
  position: absolute;
  top: 1px;
  right: 1px;
  font-size: 8px;
  color: white;
  vertical-align: text-top;
}

.audit-badge {
  height: 10px;
  width: 10px;
  border-radius: 5px;
  background-color: #ff4949;
  position: absolute;
  top: 1px;
  right: 1px;
  font-size: 8px;
  color: white;
  vertical-align: text-top;
}

.feed-dialog ::v-deep .el-dialog__body {
  padding: 0 20px 10px 20px;
}

.el-tag--dark {
  border-color: white;
}

</style>
