<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="未提交" :name="SubmitState.WILL_SUBMIT"></el-tab-pane>
      <el-tab-pane label="已提交" :name="SubmitState.HAS_SUBMIT"></el-tab-pane>
    </el-tabs>
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      size="small"
      @submit.native.prevent>
      <el-form-item label="教师姓名" prop="teacherName">
        <el-input v-model="queryParams.teacherName" clearable placeholder="请输入教师姓名"
                  @keyup.enter.native="handleQuery"></el-input>
      </el-form-item>
      <!--<el-form-item label="教师部门" prop="department">-->
      <!--  <treeselect-->
      <!--    style="width: 200px;"-->
      <!--    v-model="queryParams.department"-->
      <!--    :options="deptOptions"-->
      <!--    :show-count="true"-->
      <!--    :defaultExpandLevel="2"-->
      <!--    placeholder="请选择归属部门"/>-->
      <!--</el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-show="activeName === SubmitState.WILL_SUBMIT">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['system:leave:add']">新增
        </el-button>
      </el-col>
      <!--<el-col :span="1.5" v-show="activeName === SubmitState.WILL_SUBMIT">-->
      <!--  <el-button type="info" plain icon="el-icon-search" size="mini" :disabled="single">详情-->
      <!--  </el-button>-->
      <!--</el-col>-->
      <el-col :span="1.5" v-show="activeName === SubmitState.WILL_SUBMIT">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['system:leave:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5" v-show="activeName === SubmitState.WILL_SUBMIT">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['system:leave:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['system:leave:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="teacherOvertimeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="流程实例ID" key="instanceId" v-if="activeName === SubmitState.HAS_SUBMIT" align="center"
                       prop="instanceId"/>
      <el-table-column label="教师姓名" key="teacherName" v-if="columns[0].visible" align="center" prop="teacherName"/>
      <!--<el-table-column label="所在部门" v-if="columns[4].visible" align="center" prop="department">-->
      <!--  <template slot-scope="scope">-->
      <!--    &lt;!&ndash;<dict-tag :options="dict.type.department_type" :value="scope.row.department"/>&ndash;&gt;-->
      <!--    {{ resolveDepartment(scope.row.department) }}-->
      <!--  </template>-->
      <!--</el-table-column>-->
      <el-table-column label="开始时间" key="startTime" v-if="columns[1].visible" align="center" prop="startTime"
                       width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" key="endTime" v-if="columns[2].visible" align="center" prop="endTime"
                       width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加班天数" key="days" v-if="columns[3].visible" align="center" prop="days"/>
      <el-table-column label="申请人" key="applyUser" v-if="columns[5].visible" align="center" prop="applyUser"/>
      <!--      <el-table-column label="申请时间" v-if="columns[6].visible" align="center" prop="applyTime" width="180"-->
      <!--                       :formatter="dateFormat"/>-->
      <el-table-column label="类型" key="type" v-if="columns[5].visible" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.overtime_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="当前任务名称" key="taskName" v-if="columns[7].visible" align="center" prop="taskName">
        <template slot-scope="scope">
          <el-tag type="primary" effect="dark">{{ scope.row.taskName }}</el-tag>
        </template>
      </el-table-column>
      <!--      <el-table-column label="状态" v-if="columns[7].visible" align="center" prop="state"/>-->

      <el-table-column label="操作" v-if="columns[8].visible" align="center" width="230"
                       class-name="small-padding fixed-width" key="operate">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.instanceId==null"
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="submitApply(scope.row)"
            v-hasPermi="['system:teacherLeave:edit']"
          >提交申请
          </el-button>
          <el-button
            v-if="scope.row.instanceId==null"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:teacherOvertime:edit']"
          >编辑
          </el-button>
          <el-button
            v-if="scope.row.instanceId==null"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:teacherOvertime:remove']"
          >删除
          </el-button>
          <el-button
            v-if="scope.row.instanceId!=null"
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleDetail(scope.row)"
            v-hasPermi="['system:teacherOvertime:edit']"
          >查看
          </el-button>

        </template>
      </el-table-column>


      <!--      <el-table-column label="加班原因" v-if="columns[4].visible" align="center" prop="reason"/>-->
      <!--      <el-table-column label="实际开始时间" v-if="columns[10].visible" align="center" prop="realityStartTime"-->
      <!--                       width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.realityStartTime, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="实际结束时间" v-if="columns[11].visible" align="center" prop="realityEndTime" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.realityEndTime, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->


    </el-table>


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


    <!-- 添加教师获奖情况对话框------教师信息 -->
    <TeacherSelect
      v-if="teacherSelectDialog"
      :openSelect.sync="teacherSelectDialog"
      :title="teacherSelect"
      @getTeacherList="getTeacherList"
      @setTeacherInfo="setTeacherInfo"
    ></TeacherSelect>
    <!-- 添加或修改教师加班对话框 -->
    <el-dialog :title="title" :visible.sync="dialogTeacherOvertime" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" style="width: 100%; margin: auto">
        <el-row>
          <el-col :span="11">
            <el-form-item label="教师姓名" prop="teacherName">
              <el-input v-model="form.teacherName" @focus="openTeacherSelect" placeholder="请输入教师姓名"/>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="加班类型" prop="type">
              <el-select v-model="form.type" style="width: 100%" placeholder="请选择加班类型">
                <el-option
                  v-for="dict in dict.type.overtime_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="加班开始时间" prop="startTime">
              <el-date-picker
                style="width: 100%"
                v-model="form.startTime"
                type="datetime"
                placeholder="选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="加班结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                style="width: 100%"
                type="datetime"
                placeholder="选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="加班天数" prop="days">
              <el-input v-model.number="form.days" placeholder="请输入加班天数"/>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="审批人" prop="handUserId">
              <el-input
                v-model="form.handUserName"
                disabled
                @focus="entrust.open = true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="加班原因" prop="reason">
              <el-input
                type="textarea"
                resize="none"
                :autosize="{minRows: 5}"
                v-model="form.reason"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--选择审批人-->
    <HandleEntrust
      v-if="entrust.open"
      :title="entrust.title"
      :entrust-open.sync="entrust.open"
      @getAssignorList="getAssignorList"
      @selectUser="selectAssignor"
    ></HandleEntrust>

    <HandleResolve
      v-if="progress.open"
      :id="progress.id"
      :instance-id="progress.instanceId"
      :title="progress.title"
      :is-approver="false"
      :process-open.sync="progress.open"
    ></HandleResolve>
    <!-- 导出对话框 -->
    <ExportTable
      :open-export.sync="exportOptions.open"
      :title="exportOptions.title"
      @export="exportFile"
    ></ExportTable>

  </div>
</template>
<script>
import {
  listTeacherOvertime,
  getTeacherOvertime,
  delTeacherOvertime,
  addTeacherOvertime,
  updateTeacherOvertime,
  submitApply
} from "@/api/smartSchool/teacherManage/teacherOvertime";
import {SubmitState} from "@/enums/apply";
import TeacherSelect from '@/views/components/moduleComponets/TeacherSelect/index.vue'
import {listInform} from "@/api/smartSchool/teacherManage/teacherInformation";
import HandleResolve from "@/views/smartSchool/teacherManage/teacherOverTime/components/HandleResolve";
import {ExportType, TEXT_SIZE} from "@/enums/common";
import {deptTreeSelect} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
// import {isArray} from "@/utils/validate";
import {getTreeDept} from "@/utils/utilLibrary/getTreeDept";
import {getListByRole} from "@/api/smartSchool/common";
import HandleEntrust from "@/views/components/moduleComponets/HandleEntrust";

export default {
  name: "index",
  dicts: ['overtime_type'],
  components: {
    TeacherSelect,
    HandleResolve,
    HandleEntrust,
    Treeselect
  },
  data() {
    return {
      TEXT_SIZE,
      teacherSelect: '教师信息',
      // 是否显示弹出层
      dialogFormView: false,
      dialogTeacherOvertime: false,
      dialogScheduleView: false,
      dialogApproveHistory: false,
      // 表单参数
      form: {},
      ids: [],
      // 弹出层标题
      title: "",
      // 进度查看
      progress: {
        title: "审批查看",
        open: false,
        id: undefined,
        instanceId: undefined
      },
      formApproveHistory: {},
      tableApproveHistory: [],
      teacherSelectDialog: false,
      // tab标签选中值
      activeName: SubmitState.WILL_SUBMIT,
      SubmitState,
      // 显示搜索条件
      showSearch: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: true,
      // 教师请假信息表格数据
      teacherOvertimeList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        submitState: 0,
        department: null,
      },
      // 总数
      total: 0,
      // 列信息
      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: `操作`, visible: true},
        {key: 7, label: `操作`, visible: true},
        {key: 8, label: `操作`, visible: true},
        // {key: 6, label: `流程实例ID`, visible: true},
      ],
      // 表单校验
      rules: {
        teacherName: [
          {required: true, message: "姓名不能为空", trigger: "change"}
        ],
        startTime: [
          {required: true, message: "开始时间不能为空", trigger: "blur"}
        ],
        endTime: [
          {required: true, message: "结束时间不能为空", trigger: "blur"}
        ],
        days: [
          {required: true, message: "加班天数不能为空", trigger: "blur"},
          {pattern: /^[1-9][0-9]*$/, message: '加班天数应为数字', trigger: 'blur'}
        ],
        type: [{required: true, message: '加班类型不能为空', trigger: 'blur'}],
        handUserId: [{required: true, message: '审批人不能为空', trigger: 'change'}],
        reason: [{required: true, message: '加班原因不能为空', trigger: 'blur'}]
      },
      // 导出选项
      exportOptions: {
        title: '选择导出类别',
        open: false
      },
      // 部门树选项
      deptOptions: undefined,
      // 审批人
      entrust: {
        open: false,
        title: '选择审批人'
      },
    }
  },
  computed: {
    resolveDepartment() {
      return dept => {
        return this.getDeptName(dept);
      }
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 获取部门名称 */
    getDeptName(dept) {
      const result = getTreeDept(dept, this.deptOptions);
      console.log(result);
      return result ? result.label : '';
    },
    /** 查询教师请假信息列表 */
    getList() {
      this.loading = true;
      listTeacherOvertime(this.queryParams).then(response => {
        this.teacherOvertimeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 切换tab标签 */
    handleClick({name}) {
      // this.queryParams.suspendState = Number(name);
      this.$set(this.queryParams, 'submitState', Number(name))
      this.resetQuery();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        teacherName: '',
        department: null,
        submitState: this.activeName
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.dialogTeacherOvertime = true;
      this.title = "新增教师加班信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTeacherOvertime(id).then(response => {
        this.form = response.data;
        this.form.handUserName = 'admin';
        this.form.handUserId = 1;
        this.dialogTeacherOvertime = true;
        this.title = "修改教师加班";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {

      const ids = row.id || this.ids;
      this.$modal.confirm(`是否确认删除选中的${
        Object.hasOwnProperty.call(ids, "length") ? ids.length : 1
      }条数据？`).then(() => {
        this.loading = true;
        return delTeacherOvertime(ids);
      }).then(() => {
        this.getList();
        this.loading = false;
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 导出选中，导出全部，根据查询条件导出
      this.exportOptions.open = true;
      // this.$confirm(`是否确认导出${!!this.ids.length ? this.ids.length + '条' : '所有'}数据？`, '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   if (this.ids.length) {
      //     this.download('/school/teacherOvertime/export/' + this.ids, {
      //       ...this.queryParams
      //     }, `教师加班信息.xlsx`)
      //   } else {
      //     this.download('/school/teacherOvertime/export', {
      //       ...this.queryParams
      //     }, `教师加班信息.xlsx`)
      //   }
      // }).catch(() => {
      // });
    },

    /** 导出 */
    exportFile(callback) {
      const ids = this.ids;
      // TODO: 这里因为是两种状态： 提交和未提交，所以需要判断状态
      const options = [
        {type: ExportType.TOTAL, path: '/school/teacherOvertime/export', params: {}},
        {
          type: ExportType.SELECT,
          path: '/school/teacherOvertime/export/' + ids,
          params: {}
        },
        {type: ExportType.QUERY, path: '/school/teacherOvertime/export', params: this.queryParams},
      ]
      callback(options, `老师加班信息${new Date().getTime()}.xlsx`);
    },

    //时间格式化
    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;
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        teacherId: null,
        teacherName: null,
        department: null,
        startTime: null,
        endTime: null,
        days: null,
        reason: null,
        state: null,
        applyUser: null,
        applyTime: null,
        realityStartTime: null,
        realityEndTime: null,
        instanceId: null,
        type: null,
        handUserName: 'admin',
        handUserId: 1
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      const userName = this.$store.state.user.name;
      this.form.applyUser = userName;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTeacherOvertime(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dialogTeacherOvertime = false;
              this.getList();
            });
          } else {
            addTeacherOvertime(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialogTeacherOvertime = false;
              this.getList();
            });
          }
        }
      });
    },
    // 新增操作
    handleAddLate(data) {
      this.teacherSelectDialog = false;
      this.reset();
      this.form.teacherName = data.teacherName;
      this.form.idCard = data.idCard;
      this.form.teacherId = data.id;
      this.dialogTeacherAward = true;
      this.title = "教师加班信息";
    },
    // 取消按钮
    cancel() {
      this.dialogTeacherOvertime = false;
      this.reset();
    },
    openTeacherSelect() {
      this.teacherSelectDialog = true
    },
    // 新增操作
    setTeacherInfo(data) {
      this.teacherSelectDialog = false;
      this.$set(this.form, 'teacherName', data.teacherName);
      this.$set(this.form, 'teacherId', data.id);
      this.dialogTeacherAward = true;
      this.title = "教师加班信息";
    },
    /** 获取教师信息列表 */
    getTeacherList(queryForm, callback) {
      listInform(queryForm).then(response => {
        callback(response.rows, response.total);
      }).catch(error => {
        callback([], 0);
      })
    },
    // 提交申请
    submitApply(row) {
      this.$confirm('确认要提交申请?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        submitApply(row.id).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '提交成功!'
            });
            this.getList()
          }
        })
      }).catch(() => {

      });
    },
    /** 【已提交】查看详情 */
    handleDetail({id, instanceId}) {
      this.progress.id = id;
      this.progress.instanceId = instanceId;
      this.progress.open = true;
    },

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 获取委托人列表 */
    getAssignorList(queryForm, callback) {
      const roleKey = this.$store.state.user.roleKey;
      getListByRole(roleKey, queryForm).then(response => {
        callback(response.rows, response.total);
      }).catch(error => {
        callback([], 0);
      })
    },
    /** 选择委托人 */
    selectAssignor(selectUser) {
      this.$set(this.form, 'handUserName', selectUser.userName);
      this.$set(this.form, 'handUserId', selectUser.userId);
    },
  }
};
</script>
