<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true">
      <el-form-item label="所属项目" prop="projectId">
        <el-cascader
          :options="projectTree"
          @change="selectProjectChange"
          :props="{ expandTrigger: 'hover',value:'id',label:'name', checkStrictly: true }"
          collapse-tags
          :show-all-levels="false" clearable></el-cascader>
      </el-form-item>
      <el-form-item label="执行（负责）人" prop="executors">
        <dept-user-tree ref="dut" :userList="userList" :multiple="true"
                        @selected="selectExecutors"></dept-user-tree>
      </el-form-item>
      <el-form-item label="日期" prop="month">
        <el-date-picker
          v-model="queryParams.rangeDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          @change="getList"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
          style="width: 220px">
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="status">
        <el-radio-group v-model="queryParams.status" size="mini" @change="getList">
          <el-radio-button
            v-for="dict in dict.type.task_status"
            :key="dict.value"
            :label="dict.value"
          >{{ dict.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <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 - 140px)"
      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="上月延期" width="40">
        <template slot-scope="scope">
          <span v-if="scope.row.formLastMonth" style="color: red">是</span>
        </template>
      </el-table-column>
      <el-table-column align="center" v-for="item in tableHeaders" :key="item.day" :prop="item.day" width="38">
        <template slot="header" slot-scope="scope">
          <div style="width:28px;font-size: 9px">{{ item.day }}</div>
          <div v-if="item.week=='周六'" style="width: 24px;font-size: 12px;color: #1c84c6">{{ item.week }}</div>
          <div v-else-if="item.week=='周日'" style="width: 24px;font-size: 12px;color: #1c84c6">{{ item.week }}</div>
          <div v-else-if="item.week=='今日'" style="width: 24px;font-size: 12px;color: #008000">{{ item.week }}</div>
          <div v-else style="width: 24px;font-size: 12px">{{ item.week }}</div>
        </template>
        <template slot-scope="scope">
          <span v-if="scope.row[item.day].comment" class="comment-badge"></span>
          <el-popover
            v-if="scope.row[item.day].value!=''"
            placement="top"
            width="680"
            trigger="click">
            <el-table :data="feedbacks" border size="mini">
              <el-table-column width="75" label="反馈状态">
                <template slot-scope="scope">
                  <div>{{ getFeedbackTypeName(scope.row.feedbackType) }}</div>
                </template>
              </el-table-column>
              <el-table-column width="60" property="userName" label="反馈人"></el-table-column>
              <el-table-column width="55" label="完成度">
                <template slot-scope="scope">
                  <div>{{ scope.row.feedbackType === '4' ? '' : scope.row.value + '%' }}</div>
                </template>
              </el-table-column>
              <el-table-column width="110" property="createTime" label="反馈时间">
                <template slot-scope="scope">
                  <div>{{ parseTime(scope.row.createTime) }}</div>
                </template>
              </el-table-column>
              <el-table-column label="反馈备注">
                <template slot-scope="scope">
                  <div>
                    <span style="margin-right: 5px">{{ scope.row.description }}</span>
                    <span v-for="(file,index) in scope.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="80px">
                <template slot-scope="scope">
                  <el-popover
                    placement="top"
                    width="600"
                    trigger="hover">
                    <div v-html="scope.row.descriptionDetail"></div>
                    <el-button slot="reference" type="text">详情</el-button>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>
            <div slot="reference" style="font-size: 10px;cursor: pointer">{{ scope.row[item.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 ref="rtEditor" @getHtml="(val)=>form.descriptionDetail=val"></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="任务详情" :visible.sync="openDetail" width="760px" class="feed-dialog" append-to-body>
      <task-detail :detailForm="detailForm"></task-detail>
    </el-dialog>

  </div>
</template>

<script>
import {getTask, listView, addTaskFeedback, getFeedbackList, confirmComment} 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";

const statusMap = {
  '0': {name: '待查看', type: 'info'},
  '1': {name: '未开始', type: 'info'},
  '2': {name: '进行中', type: ''},
  '3': {name: '延期', type: 'danger'},
  '4': {name: '完成', type: 'success'},
  '5': {name: '终止', type: 'warning'}
}

export default {
  components: {TaskDetail, FileUpload, DeptUserTree, RichTextEditor},
  dicts: ['task_status',],
  data() {
    return {
      queryParams: {
        projectId: undefined,
        month: undefined,
        status: '0'
      },
      projectTree: [],
      userList: [],
      tableHeaders: [],
      tableData: [],
      statusMap: statusMap,
      open: false,
      form: {},
      feedbacks: [],
      rules: {
        description: [
          {required: true, message: "描述不能为空", trigger: "blur"},
          {min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur'}
        ]
      },
      openDetail: false,
      detailForm: {},
      cellColorMap: {
        '1': '#fefeff',
        '2': '#a6a9ad',
        '3': '#f56c6c',
        '4': '#67c23a',
        '5': '#e6a23c',
      }
    }
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      let today = new Date();
      let month = [DateUtil.beforeDay(today, 15), DateUtil.afterDay(today, 15)];
      this.$set(this.queryParams, 'rangeDate', month)
      this.getList()
      getProjectTree().then(res => {
        this.projectTree = res.data
      })
      getDeptUserTree('').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 (this.queryParams.rangeDate && this.queryParams.rangeDate.length === 2) {
        this.queryParams.startDate = this.queryParams.rangeDate[0]
        this.queryParams.endDate = this.queryParams.rangeDate[1]
      }
      let dayDiff = DateUtil.dayDiff(this.queryParams.startDate, this.queryParams.endDate);
      if (dayDiff > 366) {
        this.$message.warning("时间跨度不可超过一年")
        return
      }
      listView(this.queryParams).then(res => {
        this.tableHeaders = res.data.headers
        this.tableData = res.data.data
      })
    },
    cellMouseEnter(row, column, cell, event) {
      if (column.property != 'taskName') {
        return
      }
      cell.style.color = '#306FB1';
      cell.style.cursor = 'pointer';
      cell.style.textDecoration = 'underline';
    },
    cellMouseLeave(row, column, cell, event) {
      if (column.property != 'taskName') {
        return
      }
      cell.style.color = '#606266';
      cell.style.textDecoration = 'none';
    },
    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) {
      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) {
      let feedbackDate = DateUtil.getFeedBackDate(this.queryParams.rangeDate, 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") {
        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.rtEditor.clear()
      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)
          }
          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()
        }
      })
    }
  }
}
</script>

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

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

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

.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;
}
</style>
