<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="6">
        <div class="head-container">
          <el-date-picker
            v-model="yearValue"
            type="year" value-format="yyyy" format="yyyy"
            placeholder="选择年查询" size="small" @change="getData">
          </el-date-picker>
          <el-button type="primary" plain icon="el-icon-plus" style="margin-left: 20px" @click="addScoreWin">创建评分
          </el-button>
        </div>
        <div>
          <el-tree ref="dateTree" node-key="id" :default-expand-all="true" highlight-current :data="data"
                   :props="defaultProps" @node-click="handleNodeClick"></el-tree>
        </div>
      </el-col>

      <el-col :span="18">
        <el-form :model="queryParams" :inline="true">
          <el-form-item>
            <div style="font-weight: 700">{{ title }}</div>
          </el-form-item>
          <el-form-item label="被评分人:" label-width="120px">
            <dept-user-tree ref="dut" :userList="userList" :multiple="true" :placeholder="'请选择被评分人'"
                            @selected="(val)=>queryParams.scoreUsers=val" style="width: 350px"></dept-user-tree>

            <!--            <el-input v-model="editForm.scoreUsers" :readonly="true" style="width: 350px">-->
            <!--              <el-button @click="openUsers1" icon="el-icon-search" type="primary" slot="append"></el-button>-->
            <!--            </el-input>-->
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getPerformanceScoreLists">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-download" @click="exportOutPerformanceScore">导出绩效评分</el-button>
          </el-form-item>
        </el-form>

        <el-collapse v-model="activeNames" accordion>
          <template v-for="(item,index) in taskDatas">
            <el-collapse-item :name="index">
              <template slot="title">
                <div style="display: flex;justify-content:start">
                  <div>{{ index + 1 }}、</div>
                  <div style="width: 100px"> {{ item.userName }}</div>
                  <div>总计工时:</div>
                  <div style="width: 40px;text-align: center;font-weight: 600"> {{ item.totalWorkTime }}</div>
                  <div>小时，任务数量:</div>
                  <div style="width: 30px;text-align: center;font-weight: 600">{{ item.totalTaskNum }}</div>
                  <div> ,已完成</div>
                  <div style="width: 30px;text-align: center;font-weight: 600">{{ item.completeTaskNum }}</div>
                </div>
                <div style="margin-left: 100px">
                  评分：
                  <el-input-number size="mini" v-model="item.workScore" :min="0" :max="10" :step="0.1" :precision="2"
                                   :controls="false" style="width: 100px" @change="userWorkScore(item,index)">
                    <el-button v-if="false" size="mini" type="primary" slot="append" @click="userWorkScore(item)">评分
                    </el-button>
                  </el-input-number>
                </div>

              </template>

              <el-table :data="item.tasks" size="mini">
                <el-table-column label="序号" width="50" type="index"></el-table-column>
                <el-table-column prop="taskName" label="任务名称" width="250"
                                 :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="remark" label="任务详情" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    <div v-html="scope.row.description"></div>
                  </template>
                </el-table-column>
                <el-table-column prop="beginDate" label="开始时间" width="100"/>
                <el-table-column prop="endDate" label="结束时间" width="100"/>
                <el-table-column prop="usedWorkTime" label="已用工时" width="80"/>
                <el-table-column prop="taskStatus" label="任务状态" width="80">
                  <template slot-scope="scope">
                    <el-tag size="mini" :type="statusMap[scope.row.taskStatus].type">
                      {{ statusMap[scope.row.taskStatus].name }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
          </template>
        </el-collapse>

      </el-col>
    </el-row>

    <!--评分日期规则-->
    <el-dialog title="创建评分日期规则" :visible.sync="editFormVisible" center width="400px" @click="closeDialog"
               :close-on-click-modal="false">
      <el-form label-width="100px" ref="editForm" :model="editForm" :rules="rules" size="mini">
        <el-form-item label="评分名称:" prop="name">
          <el-input size="mini" v-model="editForm.name" placeholder="" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="评分类型:" prop="scoreType">
          <el-radio v-model="editForm.scoreType" label="0">周度评分</el-radio>
          <el-radio v-model="editForm.scoreType" label="1">月度评分</el-radio>
        </el-form-item>
        <el-form-item label="评分年月:" prop="yearMonth">
          <el-date-picker v-model="editForm.yearMonth"
                          type="month" value-format="yyyy-MM" format="yyyy-MM">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="开始日期:" prop="beginDate">
          <el-date-picker v-model="editForm.beginDate" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
                          placeholder="请选择评分开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期:" prop="endDate">
          <el-date-picker v-model="editForm.endDate" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
                          placeholder="请选择评分结束日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="closeDialog">取消</el-button>
        <el-button size="mini" type="primary" class="title" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  addPerformanceScoreSet, editPerformanceScore,
  getDateDataList,
  getDateListByYear,
  getPerformanceScoreList,
  exportPerformanceScore
} from '@/api/performance/performance'
import {getDeptUserTree} from '@/api/system/user'
import task from "@/views/mixins/task";
import DateUtil from '@/utils/date'
import DeptUserTree from "@/components/DeptUserTree"

export default {
  name: 'performance',
  mixins: [task],
  components: {DeptUserTree},
  watch: {
    filterText(val) {
      this.$refs.dept1.filter(val);
    },
  },
  data() {
    return {
      yearValue: DateUtil.year(),
      editFormVisible: false,
      activeNames: undefined,
      title: '',
      editForm: {
        id: null,
        name: '',
        scoreType: '0',
        yearMonth: null,
        beginDate: null,
        endDate: null,
        dateSetId: null,
        year: null,
        month: null
      },
      queryParams: {
        scoreSetId: undefined,
        scoreUsers: undefined
      },

      userList: [],
      data: [],
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'label'
      },
      taskDatas: [],

      rules: {
        name: [
          {required: true, message: "评分名称不能为空", trigger: "blur"}
        ],
        scoreType: [
          {required: true, message: "评分类型不能为空", trigger: "change"}
        ],
        yearMonth: [
          {required: true, message: "评分年月不能为空", trigger: "blur"}
        ],
        beginDate: [
          {required: true, message: "开始日期不能为空", trigger: "blur"}
        ],
        endDate: [
          {required: true, message: "结束日期不能为空", trigger: "blur"}
        ]
      }
    };
  },
  mounted() {
    this.getUsers()
    this.getData()
  },
  methods: {
    getUsers() {
      getDeptUserTree('1').then(res => {
        this.userList = res.data
      });
    },
    getData() {
      let year = this.yearValue
      getDateListByYear(year).then(res => {
        this.data = res.data
        // if (this.data.length > 0) {
        //   this.$nextTick(() => {
        //     this.$refs.dateTree.setCurrentKey(this.data[0].children[0].children[0].id)
        //   })
        // }
        // this.handleDefaultNodeClick(this.data)
      });
    },
    handleDefaultNodeClick(data) {
      let d = data;
      if (data.length > 0) {
        d = data[0];
        this.title = d.children[0].children[0].label
      } else {
        this.title = ''
      }
    },
    handleNodeClick(data, n, component) {
      if (!data.json) {
        this.queryParams.scoreSetId = undefined
        return
      }
      if (this.queryParams.scoreSetId === data.id) {
        return;
      }
      this.queryParams.scoreSetId = data.id
      this.title = data.label
      this.$nextTick(() => {
        this.taskDatas = []
      })
    },

    addScoreWin() {
      this.getData()
      this.editFormVisible = true;
    },
    closeDialog() {
      this.editForm = {
        id: null,
        name: '',
        scoreType: '0',
        yearMonth: null,
        beginDate: null,
        endDate: null,
        dateSetId: null,
        year: null,
        month: null
      }
      this.resetForm("editForm");
      this.editFormVisible = false;
    },
    openUsers1() {
      this.users1Visible = true
    },
    closeUser1Dialog() {
      this.users1Visible = false
    },
    submitForm() {
      let editForm = this.editForm
      //提交表单
      addPerformanceScoreSet(editForm).then(res => {
        this.$message.success("操作成功!")
        this.closeDialog()
        this.getData()
      });
    },

    exportOutPerformanceScore() {
      // let node = this.$refs.dateTree.getCurrentNode();
      // if (node.json === undefined || node.json === null || node.json === '') {
      //   this.$message.error("请选择带有时间段的节点数据!")
      //   return
      // }
      if (!this.queryParams.scoreSetId) {
        this.$message.error("请选择评分日期!")
        return;
      }
      // if (!this.queryParams.scoreUsers) {
      //   this.$message.error("请选择被评分人!")
      //   return
      // }
      let data = {
        scoreSetId: this.queryParams.scoreSetId,
        userIdStr: this.queryParams.scoreUsers.join(',')
      }
      exportPerformanceScore(data);
    },

    userWorkScore(row, index) {
      let node = this.$refs.dateTree.getCurrentNode();
      let scoreSetId = node.id
      let score = row.workScore
      if (score === undefined || score === null) {
        this.$message.error('请输入评分!')
        return
      }

      let id = row.workScoreId
      if (id === undefined) {
        id = null;
      }
      let data = {
        id: id,
        userId: row.userId,
        userName: row.userName,
        score: score,
        scoreSetId: scoreSetId
      }
      editPerformanceScore(data).then(res => {
        this.$message.success('操作成功!')
        this.getPerformanceScoreLists()
      });
    },
    getPerformanceScoreLists() {
      if (!this.queryParams.scoreSetId) {
        this.$message.error("请选择评分日期!")
        return;
      }
      let node = this.$refs.dateTree.getCurrentNode();

      // if (node.json === undefined || node.json === null || node.json === '') {
      //   this.$message.error("请选择正确的评分节点!")
      //   return
      // }
      if (!this.queryParams.scoreUsers) {
        this.$message.error("请选择被评分人!")
        return
      }
      let json = JSON.parse(node.json)
      let beginDate = json.beginDate
      let endDate = json.endDate
      let searchParam = {
        scoreSetId: this.queryParams.scoreSetId,
        beginDate: beginDate,
        endDate: endDate,
        userIds: this.queryParams.scoreUsers
      }
      getPerformanceScoreList(searchParam).then(res => {
        this.taskDatas = res.data
      });
    }
  }
}
</script>

<style scoped lang="scss">
.head-container {
  display: flex;
  margin-bottom: 20px;
  justify-content: space-between;
}
</style>
