<template>
  <div class="app-container">
    <div class="task-container">
      <div class="task-left-menu">
        <el-tabs tab-position="left" v-model="taskState" @tab-click="handleSelectState">
          <el-tab-pane :name="State.MY_TASK">
            <span slot="label"><i class="el-icon-user"></i> 我的任务</span>
          </el-tab-pane>
          <el-tab-pane :name="State.HISTORY_TASK">
            <span slot="label"><i class="el-icon-time"></i> 历史任务</span>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="task-right-content">
        <el-table v-loading="loading" :data="teacherLeaveList" @selection-change="handleSelectionChange">
          <el-table-column label="标题" v-if="columns[0].visible" width="120" align="center" prop="title"
                           show-overflow-tooltip/>
          <el-table-column label="教师姓名" v-if="columns[1].visible" width="100" show-overflow-tooltip align="center"
                           prop="teacherName"/>

          <el-table-column label="请假类型" v-if="columns[7].visible" align="center" prop="type" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.biz_leave_type" :value="scope.row.type"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="请假开始时间" v-if="columns[3].visible" align="center" prop="startTime" width="120">
          </el-table-column>
          <el-table-column label="请假结束时间" v-if="columns[4].visible" align="center" prop="endTime" width="120">

          </el-table-column>
          <el-table-column label="请假时长" v-if="columns[5].visible" align="center" prop="totalTime" width="150"/>
          <el-table-column label="申请人" v-if="columns[7].visible" align="center" prop="applyUser" width="100"
                           show-overflow-tooltip/>
          <el-table-column label="申请时间" v-if="columns[8].visible" align="center" prop="applyTime" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="任务状态" v-if="columns[7].visible" align="center" width="120" prop="taskName">
            <template slot-scope="scope">
              <el-tag effect="dark" v-show="scope.row.taskName">{{ scope.row.taskName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" v-if="columns[9].visible" min-width="100" align="center"
                           class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                v-if="taskState === State.MY_TASK"
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="handleResolve(scope.row, false)"
              >办理
              </el-button>
              <el-button
                v-if="taskState===State.HISTORY_TASK"
                type="text"
                size="mini"
                icon="el-icon-time"
                @click="handleResolve(scope.row, true)"
              >历史
              </el-button>
            </template>
          </el-table-column>

        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>

    <HandleResolve
      v-if="process.open"
      :process-open.sync="process.open"
      :instanceId="process.instanceId"
      :id="process.id"
      :taskId="process.taskId"
      :readOnly="process.readOnly"
      :revoke="process.revoke"
      @refreshData="refreshData"
    ></HandleResolve>
  </div>
</template>
<script>
import {State} from "@/enums/apply";
import {CustomCellStyle} from "@/enums/customStyle";
import HandleResolve from "@/views/smartSchool/teacherManage/teacherLeave/components/HandleResolve";
import {
  getTeacherLeave,
  delTeacherLeave,
  addTeacherLeave,
  updateTeacherLeave,
  taskList,
  taskDoneList,
  listHistory,
  viewSchedule,
  submitApply
} from "@/api/smartSchool/teacherManage/teacherLeave";

export default {
  name: "MyTask",
  dicts: ['biz_leave_type'],
  components: {
    HandleResolve
  },
  data() {
    return {
      State,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 老师请假信息表格数据
      teacherLeaveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        leaveReason: null,
        startTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
      // 列信息
      columns: [
        {key: 0, label: `标题`, visible: true},
        {key: 1, label: `老师名称`, visible: true},
        {key: 2, label: `请假原因`, visible: true},
        {key: 3, label: `请假开始时间`, visible: true},
        {key: 4, label: `请假结束时间`, visible: true},
        {key: 5, label: `请假时长`, visible: true},
        {key: 6, label: `流程实例ID`, visible: true},
        {key: 7, label: `申请人`, visible: true},
        {key: 8, label: `申请时间`, visible: true},
        {key: 9, label: `操作`, visible: true},
      ],
      // 表单校验
      rules: {
        leaveReason: [
          {required: true, message: "请假原因不能为空", trigger: "blur"}
        ],
        startTime: [
          {required: true, message: "请假开始时间不能为空", trigger: "blur"}
        ],
        endTime: [
          {required: true, message: "请假结束时间不能为空", trigger: "blur"}
        ],
      },
      // 任务状态
      taskState: State.MY_TASK,
      // 自定义单元格
      customCellStyle: CustomCellStyle,
      // 办理流程
      process: {
        id: undefined,
        instanceId: undefined,
        taskId: undefined,
        open: false,
        title: '流程办理',
        readOnly: false,
        // 是否销假
        revoke: false
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 任务状态发生变化 */
    handleSelectState({name}) {
      this.resetQuery();
    },
    /** 办理/历史/销假 */
    handleResolve({id, taskId, instanceId, taskName}, readOnly, revoke = false) {
      const isRevoke = new RegExp('销假', 'g');
      this.process.open = true;
      this.process.instanceId = instanceId;
      this.process.id = id;
      this.process.taskId = taskId;
      this.process.readOnly = readOnly; // 主要用来判断是否为历史任务。或者是申请人查看
      // 是等待销假状态，同时保证不是在历史任务中
      this.process.revoke = isRevoke.test(taskName) && !readOnly;
    },
    /** 审核人提交表单(刷新数据) */
    refreshData() {
      this.getList();
    },
    /** 查询任务列表 */
    async getList() {
      let response = null; // 返回结果
      try {
        this.loading = true; // 加载效果
        switch (this.taskState) {
          case State.MY_TASK:
            response = await taskList(this.queryParams);
            break;
          case State.HISTORY_TASK:
            response = await taskDoneList(this.queryParams);
            break;
          case State.REVOKE:
            response = await revokeList(this.queryParams);
            break;
          default:
            break;
        }
        this.loading = false;
        this.teacherLeaveList = response.rows;
        this.total = response.total;
      } catch (exception) {
        this.loading = false;
      }
    },
    // 取消按钮
    cancel() {
      this.dialogTeacherLeave = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        title: null,
        teacherId: null,
        teacherName: null,
        reasonForLeave: null,
        startTime: null,
        endTime: null,
        totalTime: null,
        state: null,
        instanceId: null,
        applyUser: null,
        applyTime: null,
        realityStartTime: null,
        realityEndTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTeacherLeave(id).then(response => {
        this.form = response.data;
        this.dialogTeacherLeave = true;
        this.title = "老师请假信息详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTeacherLeave(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dialogTeacherLeave = false;
              this.getList();
            });
          } else {
            addTeacherLeave(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialogTeacherLeave = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(`是否确认删除？`).then(() => {
        this.loading = true;
        return delTeacherLeave(ids);
      }).then(() => {
        this.getList();
        this.loading = false;
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 提交申请
    submitApply(row) {
      console.log(row, "row")
      this.$confirm('确认要提交申请?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        submitApply(row, row.id).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '提交成功!'
            });
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消提交'
        });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm(`是否确认导出${!!this.ids.length ? this.ids.length + '条' : '所有'}数据？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.ids.length) {
          console.log("this.ids", this.ids)
          this.download('/school/teacherLeave/export/' + this.ids, {
            ...this.queryParams
            // }, `user_${new Date().getTime()}.xlsx`)
          }, `学校信息推送.xlsx`)
        } else {
          this.download('/school/teacherLeave/export', {
            ...this.queryParams
          }, `学校信息推送.xlsx`)
        }
      }).catch(() => {
      });
    },
    dialogOpenApproveHistory(row) {

      this.dialogApproveHistory = true
      this.getApproveHistoryList(row)
    },
    getApproveHistoryList(row) {
      listHistory({instanceId: row.instanceId}).then(res => {
        console.log(res, 'listHistory')
      })
    },
    dialogOpenScheduleView(row) {
      this.dialogScheduleView = true
      viewSchedule(row).then(res => {
      })
    },
    openViewTeacherLeaveForm(row) {
      this.reset();
      const id = row.id || this.ids
      getTeacherLeave(id).then(response => {
        this.form = response.data;
        this.dialogViewTeacherLeave = true;
      });
    },
    dateFormat(row, column, cellValue, index) {
      const data = row[column.property]
      if (data) {
        let date1 = new Date(data.date).toJSON();
        let date = new Date(+new Date(date1) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
        //date.substr(0,10); //接取2020-04-02
        return date;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/moduleStyle/custom-global-style.scss";
</style>
