<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true">
      <el-form-item prop="projectId">
        <el-cascader
          :options="projectTree"
          @change="selectProjectChange"
          :props="{ expandTrigger: 'hover',value:'id',label:'name', checkStrictly: true }"
          collapse-tags
          placeholder="选择分类/项目"
          :show-all-levels="false" clearable></el-cascader>
      </el-form-item>
      <el-form-item prop="executors">
        <dept-user-tree ref="dut" :userList="userList" :multiple="true"
                        @selected="selectExecutors"></dept-user-tree>
      </el-form-item>
      <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.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-table
      class="view-table"
      :data="tableData"
      v-el-table-infinite-scroll="loadData"
      :infinite-scroll-disabled="disabled"
      size="mini"
      @cell-mouse-enter="cellMouseEnter"
      @cell-mouse-leave="cellMouseLeave"
      :cell-style="cellStyle"
      @row-click="rowClick"
      height="calc(100vh - 110px)"
      row-key="id"
      lazy
      :indent="10"
      :load="loadChildren"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      border>
      <el-table-column fixed prop="id" header-align="center" label="编号"/>
      <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">
          <div style="width:40px;text-align: center">
            <div style="font-size: 10px;text-align: center">{{ 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>
        </template>
        <template slot-scope="scope">
          <span v-if="scope.row[header.day].comment" class="comment-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>
                </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="100px">
        <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-form-item label="附件" prop="fileUrl">
          <file-upload ref="fu" @getFileUrl="getFileUrl" @removeFile="removeFile"></file-upload>
        </el-form-item>
        <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="detailForm.id+'、'+detailForm.taskName" :visible.sync="auditOpen" width="900px" class="add-dialog"
               append-to-body @close="auditCancel">
      <task-detail :detail-form="detailForm"></task-detail>
      <el-form ref="auditForm" :model="auditForm" :rules="auditRules" size="mini" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="审核意见" prop="auditResult">
              <el-radio-group v-model="auditForm.auditResult">
                <el-radio label="1">确认完成</el-radio>
                <el-radio label="0">驳回</el-radio>
                <el-radio label="9">评论</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="auditForm.auditResult==='0'" label="进度（%）" prop="value">
              <el-input-number v-model="auditForm.value" :min="1" :max="99"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="审核备注" prop="auditOpinion">
          <el-input v-model="auditForm.auditOpinion" type="textarea" :maxlength="1000"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="submitAudit">确 定</el-button>
        <el-button size="mini" @click="auditCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getTask,
  listView,
  addTaskFeedback,
  getFeedbackList,
  confirmComment,
  listProjectView,
  childrenTask, auditTask
} from "@/api/task/task";
import {getProjectList, getProjectTree} from "@/api/task/project";
import DateUtil from "@/utils/date"
import TaskDetail from "./components/taskDetail"
import FileUpload from "@/components/FileUpload"
import DeptUserTree from "@/components/DeptUserTree"
import RichTextEditor from "@/components/RichTextEditor"
import {getDeptUserTree} from "@/api/system/user";
import task from "@/views/mixins/task";
import elTableInfiniteScroll from 'el-table-infinite-scroll'
import {mapGetters} from "vuex";

export default {
  components: {TaskDetail, FileUpload, DeptUserTree, RichTextEditor},
  dicts: ['task_status', 'task_priority'],
  directives: {
    'el-table-infinite-scroll': elTableInfiniteScroll
  },
  mixins: [task],
  computed: {
    ...mapGetters(['userId'])
  },
  data() {
    return {
      queryParams: {
        projectId: undefined,
        startDate: undefined,
        endDate: undefined,
        statusGroup: ['0', '1', '2', '3'],
        priority: undefined
      },
      projectTree: [],
      userList: [],
      tableHeaders: [],
      totalData: [],
      disabled: false,
      tableData: [],
      page: 0,
      total: 0,

      clickCount: 0,
      timer: null,

      open: false,
      form: {},
      feedbacks: [],
      rules: {
        description: [
          {required: true, message: "描述不能为空", trigger: "blur"},
          {min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur'}
        ]
      },
      openDetail: false,
      detailForm: {},
      auditOpen: false,
      auditForm: {},
      auditRules: {
        auditResult: [
          {required: true, message: "审核意见不能为空", trigger: "change"}
        ],
        value: [
          {required: true, message: "进度不能为空", trigger: "blur"}
        ]
      }
    }
  },
  watch: {
    totalData: {
      handler(newVal, oldVal) {
        this.loadData()
      },
      deep: true,
      immediate: true
    }
  },
  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()
      getProjectTree({status: '0'}).then(res => {
        this.projectTree = res.data
      })
      getDeptUserTree('1').then(res => {
        this.userList = res.data
      })
    },
    //项目选择事件
    selectProjectChange(val) {
      this.queryParams.projectId = val[val.length - 1]
      this.getList()
    },
    selectExecutors(val) {
      this.queryParams.executors = val
      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
      }
      listProjectView(this.queryParams).then(res => {
        this.tableData = []
        this.page = 0
        this.disabled = false
        this.tableHeaders = res.data.headers
        this.totalData = res.data.data || []
        this.total = this.totalData.length > 0 ? Number.parseInt(this.totalData.length / 15) + 1 : 0
      })
    },
    loadData() {
      if (this.disabled) return;
      if (this.totalData.length === 0) return;
      if (this.page < this.total) {
        let temp = this.totalData.slice(this.page * 15, (this.page + 1) * 15)
        this.tableData = this.tableData.concat(temp);
      }
      this.page++;
      if (this.page === this.total) {
        this.disabled = true;
      }
    },

    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') {
        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,
        feedbackType: '4',
        fileUrl: undefined,
        description: undefined
      };
      this.open = true
    },
    rowClick(row, column, event) {
      if (column.property === "taskName") {
        if (row.status === '6' && row.auditUserId === this.userId) {
          getTask(row.id).then(res => {
            if (res.data.ancestorsTask && res.data.ancestorsTask.length === 0) {
              this.detailForm = res.data;
              this.auditForm = {
                taskId: row.id,
                auditResult: undefined,
                value: undefined,
                auditOpinion: undefined
              }
              this.auditOpen = true;
            } else {
              this.detailForm = res.data
              this.openDetail = true
            }
          })
        } else {
          getTask(row.id).then(res => {
            this.detailForm = res.data
            this.openDetail = true
          })
        }
      }

      this.clickCount++;
      // 判断点击次数，如果是首次点击，则启动延时器
      if (this.clickCount === 1) {
        this.timer = setTimeout(() => {
          // 执行单击操作
          this.cellClick(row, column);
          this.clickCount = 0
        }, 300); // 设置延时时间，单位为毫秒
      } else {
        // 如果点击次数大于1，则说明是双击操作，清除延时器，并执行双击操作
        clearTimeout(this.timer);
        this.cellDbClick(row, column);
        this.clickCount = 0
      }


    },
    feedbackTypeChange(val) {
      if (val === '2') {
        this.form.value = 100
      } else {
        this.form.value = undefined
      }
    },
    // 取消按钮
    cancel() {
      this.$refs.fu.clear()
      this.reset();
      this.open = false;
    },
    // 表单重置
    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 => {
            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.getList()
        }
      })
    },

    loadChildren(tree, treeNode, resolve) {
      let params = {
        projectId: this.queryParams.projectId,
        startDate: this.queryParams.startDate,
        endDate: this.queryParams.endDate,
        status: this.queryParams.status,
        priority: undefined,
        parentTaskId: tree.id
      }
      childrenTask(params).then(res => {
        resolve(res.data)
      })
    },
    /** 审核任务提交按钮 */
    submitAudit() {
      this.$refs["auditForm"].validate(valid => {
        if (valid) {
          if (this.auditForm.auditResult != '9') {
            auditTask(this.auditForm).then(res => {
              this.$message.success("操作成功");
              this.getList()
              this.auditCancel()
            })
          } else {
            let data = {
              taskId: this.auditForm.taskId,
              feedbackDate: DateUtil.day(),
              feedbackType: '4',
              description: this.auditForm.auditOpinion
            }
            addTaskFeedback(data).then(res => {
              this.$message.success("评论成功");
              this.auditCancel()
            });
          }
        }
      });
    },
    // 审核取消按钮
    auditCancel() {
      this.detailForm = {};
      this.auditForm = {
        taskId: undefined,
        auditResult: undefined,
        value: undefined,
        auditOpinion: undefined
      }
      this.resetForm("auditForm");
      this.auditOpen = false;
    },
  }
}
</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;
}

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

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

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

</style>
