<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>
        <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">
        <el-button type="info" plain icon="el-icon-search" size="mini" @click="handleDetailAwait" :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="teacherLeaveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="流程实例ID" prop="instanceId" width="100" key="instanceId"
                       v-if="activeName === SubmitState.HAS_SUBMIT" align="center"></el-table-column>
      <el-table-column label="教师名称" key="teacherName" v-if="columns[0].visible" width="120" align="center"
                       prop="teacherName"
                       show-overflow-tooltip/>
      <el-table-column label="标题" key="title" v-if="columns[1].visible" align="center" width="200" prop="title"
                       show-overflow-tooltip/>
      <el-table-column label="请假类型" key="type" width="100" v-if="columns[7].visible" align="center" prop="type">
        <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[2].visible" align="center" prop="reasonForLeave" width="150"/>-->
      <el-table-column label="请假开始时间" key="startTime" v-if="columns[3].visible" width="120" align="center"
                       prop="startTime">
        <!--<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[4].visible" width="120" align="center" prop="endTime">
        <!--<template slot-scope="scope">-->
        <!--  <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>-->
        <!--</template>-->
      </el-table-column>
      <!--      <el-table-column label="创建人" v-if="columns[7].visible" align="center" prop="createBy"/>-->
      <!--      <el-table-column label="审批人" v-if="columns[7].visible" align="center" prop="applyUser"/>-->
      <el-table-column label="申请人" key="applyUser" align="center" prop="applyUser"
                       v-if="columns[8].visible && activeName === SubmitState.HAS_SUBMIT">
      </el-table-column>
      <el-table-column label="当前任务名称" key="taskName" prop="taskName" width="120" align="center">
        <template slot-scope="scope">
          <el-tag effect="dark">{{ scope.row.taskName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" v-if="columns[9].visible" align="center"
                       class-name="small-padding fixed-width" min-width="180" 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:teacherLeave: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:teacherLeave: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>

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


    <!-- 添加或修改教师请假信息对话框 -->
    <el-dialog :title="title" :visible.sync="dialogTeacherLeave" 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" @click.native="openTeacherSelect"
                        placeholder="请输入教师名称"/>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题"/>
            </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"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :offset="2" :span="11">
            <el-form-item label="请假结束时间" prop="endTime">
              <el-date-picker
                style="width: 100%"
                v-model="form.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :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.biz_leave_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="审批人" prop="userName">
              <el-input
                v-model="form.handUserName"
                tyle="width: 100%;"
                disabled
                @focus="entrust.open = true"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="请假原因" prop="reasonForLeave">
          <el-input
            type="textarea"
            resize="none"
            :autosize="{minRows: 5}"
            v-model="form.reasonForLeave"
          />
        </el-form-item>

      </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>
    <!-- 查看教师请假信息对话框 -->
    <el-dialog :title="title" :visible.sync="dialogTeacherLeaveView" width="1000px" append-to-body>
      <el-card>
        <el-descriptions title="请假基本消息">
          <el-descriptions-item label="教师名称">{{ form.teacherName }}</el-descriptions-item>
          <el-descriptions-item label="标题">{{ form.title }}</el-descriptions-item>
          <el-descriptions-item label="请假开始时间">{{ form.startTime }}</el-descriptions-item>
          <el-descriptions-item label="请假结束时间">{{ form.endTime }}</el-descriptions-item>
          <el-descriptions-item label="请假类型">
            <dict-tag :options="dict.type.biz_leave_type" :value="form.type"/>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      <br/>
      <el-card>
        <el-descriptions title="请假原因"/>
        <span v-html="form.reasonForLeave"/>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogTeacherLeaveView=false">确 定</el-button>
      </div>
    </el-dialog>

    <!--选择老师-->
    <TeacherSelect
      v-if="teacherSelectDialog"
      :openSelect.sync="teacherSelectDialog"
      :title="teacherSelect"
      @getTeacherList="getTeacherList"
      @setTeacherInfo="setTeacherInfo"
    ></TeacherSelect>
    <!--选择审批人-->
    <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 {
  listTeacherLeave,
  getTeacherLeave,
  delTeacherLeave,
  addTeacherLeave,
  updateTeacherLeave,
  listHistory,
  submitApply,
} from "@/api/smartSchool/teacherManage/teacherLeave";
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/teacherLeave/components/HandleResolve";
import HandleEntrust from "@/views/components/moduleComponets/HandleEntrust";
import { getListByRole } from "@/api/smartSchool/common";
import { ExportType } from "@/enums/common";

export default {
  name: "index",
  dicts: ['biz_leave_type'],
  components: { TeacherSelect, HandleResolve, HandleEntrust, },
  created() {
    this.getList();
  },
  data() {
    return {
      // 审批人
      entrust: {
        open: false,
        title: '选择审批人'
      },
      teacherSelect: '教师信息',
      teacherSelectDialog: false,
      // tab标签选中值
      activeName: SubmitState.WILL_SUBMIT,
      SubmitState,
      // 显示搜索条件
      showSearch: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      dialogTeacherLeaveView: false,
      dialogViewTeacherLeave: false,
      dialogTeacherLeave: false,
      // 教师请假信息表格数据
      // 表单参数
      form: {},
      teacherLeaveList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        submitState: 0,
        teacherName: null,
      },
      // 总数
      total: 0,

      // 进度查看
      progress: {
        title: "审批查看",
        open: false,
        id: undefined,
        instanceId: undefined
      },

      // 列信息
      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: {
        handUserId: [{ required: true, message: '审批人不能为空', trigger: 'change' }],
        teacherName: [{ required: true, message: '教师名称不能为空', trigger: 'change' }],
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        startTime: [{ required: true, message: '请假开始时间不能为空', trigger: 'blur' }],
        endTime: [{ required: true, message: '请假结束时间不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '请假类型不能为空', trigger: 'blur' }],
        reasonForLeave: [{ required: true, message: '请假原因不能为空', trigger: 'blur' }]
      },
      // 导出选项
      exportOptions: {
        title: '选择导出类别',
        open: false
      }
    };
  },
  methods: {

    /** 查询教师请假信息列表 */
    getList() {
      this.loading = true;
      listTeacherLeave(this.queryParams).then(response => {
        this.teacherLeaveList = 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.$set(this.queryParams, 'submitState', Number(name));
      this.resetQuery();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.dialogTeacherLeave = true;
      this.title = "新增教师请假信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTeacherLeave(id).then(response => {
        this.form = response.data;
        this.form.handUserName = 'admin';
        this.form.handUserId = 1;
        this.dialogTeacherLeave = 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 delTeacherLeave(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/teacherLeave/export/' + this.ids, {
      //       ...this.queryParams
      //     }, `教师请假信息.xlsx`)
      //   } else {
      //     this.download('/school/teacherLeave/export', {
      //       ...this.queryParams
      //     }, `教师请假信息.xlsx`)
      //   }
      // }).catch(() => {
      // });
    },

    /** 导出 */
    exportFile(callback) {
      const ids = this.ids;
      // TODO: 这里因为是两种状态： 提交和未提交，所以需要判断状态
      const options = [
        { type: ExportType.TOTAL, path: '/school/teacherLeave/export', params: {} },
        {
          type: ExportType.SELECT,
          path: '/school/teacherLeave/export/' + ids,
          params: {}
        },
        { type: ExportType.QUERY, path: '/school/teacherLeave/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/, '');
        return date;
      }
    },
    // 表单重置
    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,
        handUserName: 'admin',
        handUserId: 1
      }
      this.resetForm("form");
    },
    /** 提交按钮 */
    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();
            });
          }
        }
      });
    },
    confirm() {
      this.dialogViewTeacherLeave = false;
    },
    // 取消按钮
    cancel() {
      this.dialogTeacherLeave = false;
      this.reset();
    },
    openViewTeacherLeaveForm(row) {
      this.reset();
      const id = row.id || this.ids
      getTeacherLeave(id).then(response => {
        this.form = response.data;
        this.dialogViewTeacherLeave = true;
      });
    },
    dialogOpenApproveHistory(row) {
      this.dialogApproveHistory = true
      this.getApproveHistoryList(row)
    },
    getApproveHistoryList(row) {
      listHistory({ instanceId: row.instanceId }).then(res => {
      })
    },
    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) {
      console.log(row, "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(() => {
      });
    },
    /** 【未提交】查看详情 */
    handleDetailAwait() {
      this.reset();
      let teacherId = this.ids
      getTeacherLeave(teacherId).then(response => {
        this.form = response.data;
        this.dialogTeacherLeaveView = true;
        this.title = "教师请假信息详情";
      });
    },
    /** 【已提交】查看详情 */
    handleDetail({ id, instanceId }) {
      this.progress.id = id;
      this.progress.instanceId = instanceId;
      this.progress.open = true;
    },
    /** 获取委托人列表 */
    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>
