<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>
    <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"></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" min-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" align="center" prop="teacherName"
        show-overflow-tooltip />
      <el-table-column label="标题" key="title" v-if="columns[1].visible" align="center" min-width="250" prop="title"
        show-overflow-tooltip />
      <el-table-column label="请假类型" key="type" min-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="请假开始时间" key="startTime" v-if="columns[3].visible" min-width="125" align="center"
        prop="startTime">
        <template slot-scope="scope">
          <span v-if="scope.row.applyType == 0">{{
            parseTime(scope.row.startTime, "{y}-{m}-{d}")
          }} 第{{ scope.row.startSort }}节课</span>
          <span v-else>{{ parseTime(scope.row.startTime, "{y}-{m}-{d}-{h}:{m}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假结束时间" key="endTime" v-if="columns[4].visible" min-width="125" align="center"
        prop="endTime">
        <template slot-scope="scope">
          <span v-if="scope.row.applyType == 0">{{
            parseTime(scope.row.endTime, "{y}-{m}-{d}")
          }} 第{{ scope.row.endSort }}节课</span>
          <span v-else>{{ parseTime(scope.row.endTime, "{y}-{m}-{d}-{h}:{m}:{s}") }}</span>
        </template>
      </el-table-column>
      <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" min-width="140" 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="handleDetailAwait(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="dialogTitle" :visible.sync="dialogTeacherLeave" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :disabled="isEdit" :rules="rules" label-width="110px"
        style="width: 100%; margin: auto">
        <el-form-item label="标题" prop="title">
          <el-input :value="title" placeholder="请输入标题" />
        </el-form-item>
        <el-row>
          <el-col :span="11">
            <el-form-item label="姓名" prop="teacherName">
              <el-input :value="form.teacherName" placeholder="请输入教师名称" />
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="级部/处室" prop="applyOrgid">
              <template v-if="!isEdit">
                <Treeselect v-model="form.applyOrgid" :options="gradeOfficeList" :disable-branch-nodes="true"
                  :searchable="true" :show-count="true" :clearable="false" @select="deptIdAndName" placeholder="请选择归属部门"
                  style="width:224px" />
              </template>
              <template v-else>
                <el-input :value="form.applyOrgname"></el-input>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="employeeType == 1">
          <el-col :span="11">
            <el-form-item label="请假开始时间" prop="startTime">
              <el-date-picker @change="leaveTime" style="width: 100%" v-model="form.startTime" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptionsStart"
                placeholder="选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :offset="2" :span="11">
            <el-form-item label="请假结束时间" prop="endTime">
              <el-date-picker @change="leaveTime" style="width: 100%" v-model="form.endTime" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptionsEnd" placeholder="选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-else>
          <!--          教师-->
          <el-col :span="7">
            <el-form-item label="请假开始时间" prop="startTime">
              <el-date-picker v-model="form.startTime" type="date" style="width: 100%" value-format="yyyy-MM-dd"
                @change="leaveTime" :picker-options="pickerOptionsStart" placeholder="日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-select v-model="form.startSort" @change="leaveTime" style="width: 100%" placeholder="课程节次">
              <el-option v-for="dict in dict.type.course_arrange" :key="dict.value" :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :offset="2" :span="7">
            <el-form-item label="请假结束时间" prop="endTime">
              <el-date-picker type="date" v-model="form.endTime" value-format="yyyy-MM-dd" @change="leaveTime"
                style="width: 100%" :picker-options="pickerOptionsEnd" placeholder="日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-select v-model="form.endSort" @change="leaveTime" style="width: 100%" placeholder="课程节次">
              <el-option v-for="dict in dict.type.course_arrange" :key="dict.value" :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row v-if="employeeType == 1">
          <el-col :span="11">
            <el-form-item label="请假时长" prop="totalTime">
              <el-input :value="form.totalTime">
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-else>
          <el-col :span="11">
            <el-form-item label="请假时间" prop="dayCourse">
              <el-input :value="form.dayCourse" placeholder="请假时间" />
            </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="handUserName1">
              <el-input :value="form.handUserName1" placeholder="请先选择级部/处室"
                @focus="openSelect('选择级部/处室主任', 'gradeOfficeDirector', 1)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="分管领导" prop="handUserName2" v-if="form.totalTime > 0.5">
              <el-input :value="form.handUserName2" placeholder="请选择分管领导"
                @focus="openSelect('选择分管领导', 'leaderList', 2)"></el-input>
            </el-form-item>
          </el-col>
          <el-col :offset="2" :span="11">
            <el-form-item label="主要领导" prop="handUserName3" v-if="form.totalTime > 2">
              <el-input :value="form.handUserName3" placeholder="请选择主要领导"
                @focus="openSelect('选择主要领导', 'leaderList', 3)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="请假事由" prop="reasonForLeave">
          <el-input type="textarea" placeholder="请输入请假事由" resize="none" :autosize="{ minRows: 5 }"
            v-model="form.reasonForLeave" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!isEdit" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    &lt;!&ndash; 查看教师请假信息对话框 &ndash;&gt;-->
    <el-dialog title="查看信息" :visible.sync="progress.open" 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="请假类型">{{ form.type }}</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="progress.open = false">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 导出对话框 -->
    <ExportTable :open-export.sync="exportOptions.open" :title="exportOptions.title" @export="exportFile"></ExportTable>

    <!-- 选择对应处理人 -->
    <SelectUser :id="selectHandles.id" :open.sync="selectHandles.open" :title="selectHandles.title"
      :width="selectHandles.width" :execute="selectHandles.method" @select="selectUser"></SelectUser>
  </div>
</template>
<script>
import {
  listTeacherLeave,
  getTeacherLeave,
  delTeacherLeave,
  addTeacherLeave,
  updateTeacherLeave,
  listHistory,
  submitApply,
} from "@/api/smartSchool/personWork/leaveApply";
import { SubmitState } from "@/enums/apply";
import { listInform } from "@/api/smartSchool/teacherManage/teacherInformation";
import { getListByRole } from "@/api/smartSchool/common";
import { ExportType } from "@/enums/common";
import TeacherSelect from '@/views/components/moduleComponets/TeacherSelect/index.vue'
import HandleResolve from "@/views/smartSchool/teacherManage/teacherLeave/components/HandleResolve";
import HandleEntrust from "@/views/components/moduleComponets/HandleEntrust";
import {
  getLeaveTime,
  getGradeOfficeList,
  getGradeOfficeDirectorList,
  getLeaderList
} from "@/api/smartSchool/personWork/leaveApply";
import { formatDate } from "../../../../utils";
import { getDepId, getDepids } from "../../../../api/smartSchool/personWork/leaveApply";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import SelectUser from "./components/SelectUser";

export default {
  name: "index",
  dicts: ['biz_leave_type', 'course_arrange'],
  components: {
    TeacherSelect,
    HandleResolve,
    HandleEntrust,
    Treeselect,
    SelectUser
  },
  computed: {
    title: function () {
      //如果是教工
      if (this.employeeType == 0) {
        if (this.form.startTime && this.form.type && this.form.startSort) {
          return `${this.form.teacherName}-${this.selectDictLabel(this.dict.type.biz_leave_type, this.form.type)}-${this.form.startTime}-${this.selectDictLabel(this.dict.type.course_arrange, this.form.startSort)}`
        } else {
          return `${this.form.teacherName}`
        }
      } else {
        //如果是职工
        if (this.form.startTime && this.form.type) {
          return `${this.form.teacherName}-${this.selectDictLabel(this.dict.type.biz_leave_type, this.form.type)}-${formatDate(this.form.startTime)}`
        } else {
          return `${this.form.teacherName}`
        }
      }


    }
  },
  created() {
    this.getList();
    this.schoolLeader();
    // this.employeeType = this.$store.state.user.employeeType;
    this.form.teacherId = this.$store.state.user.userId;

  },
  data() {
    return {
      allowClick: true,
      isEdit: false,
      //当前登录人类型 0代表教工，1代表职工
      employeeType: "",
      //后端传的级部/处室信息列表
      gradeOfficeList: [],
      // 级部/处室选择框默认值
      applyOrgname: {},
      //后端传的级部/处室主任信息列表
      gradeOfficeDirectorList: [],
      //后端传校领导列表
      schoolLeaderList: [],
      // 审批人
      entrust: {
        open: false,
        title: '选择审批人'
      },
      // 部门树选项
      deptOptions: undefined,
      teacherSelect: '教师信息',
      teacherSelectDialog: false,
      // tab标签选中值
      activeName: SubmitState.WILL_SUBMIT,
      SubmitState,
      // 显示搜索条件
      showSearch: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: true,
      // 弹出层标题
      dialogTitle: "",
      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: {
        teacherName: [{ required: true, message: '教师名称不能为空', trigger: 'change' }],
        applyOrgname: [{ required: true, message: '级部/处室不能为空', trigger: 'change' }],
        handUserName1: [{ required: true, message: '级部/处室主任不能为空', trigger: 'change' }],
        handUserName2: [{ required: true, message: '分管领导', trigger: 'change' }],
        handUserName3: [{ required: true, message: '主要领导', trigger: 'change' }],
        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
      },
      pickerOptionsStart: {
        disabledDate: (time) => {
          let endDateVal = this.form.endTime;
          if (endDateVal) {
            return (
              time.getTime() > new Date(endDateVal).getTime() || time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
            );
          }
          return time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
        },
      },
      pickerOptionsEnd: {
        disabledDate: (time) => {
          let beginDateVal = this.form.startTime;
          if (beginDateVal && this.form.id) {
            return (
              time.getTime() < new Date(beginDateVal).getTime()

            );
          } else if (beginDateVal) {
            return (
              time.getTime() < new Date(beginDateVal).getTime() - 24 * 3600 * 1000

            );
          }
        }
      },
      // 选择对应处理人
      selectHandles: {
        id: null,
        open: false,
        title: '',
        width: '50%',
        method: null,
        type: null // 处理类型： 1 级部/处室； 2 分管； 3 主管
      }
    };
  },
  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.isEdit = false;
      this.reset();
      this.$set(this.form, 'teacherName', this.$store.state.user.name);
      this.formReady();
      this.dialogTeacherLeave = true;
      this.dialogTitle = "新增教师请假信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isEdit = false;
      this.reset();
      this.$set(this.form, 'teacherName', this.$store.state.user.name);
      const id = row.id || this.ids;
      // this.formReady();
      getTeacherLeave(id).then(response => {
        this.form = response.data;
        if (this.form.applyType == 0) {
          this.form.startTime = this.getFormatDate(this.form.startTime)
          this.form.endTime = this.getFormatDate(this.form.endTime)
        }
        this.dialogTeacherLeave = true;
        this.dialogTitle = "修改教师请假信息";
      });
    },
    /** 删除按钮操作 */
    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(() => {
      });
    },

    deptIdAndName(node) {
      console.log(node);
      getDepids(node.id).then(response => {
        this.employeeType = response.employeeType;

      });

      // this.form.applyOrgname = node.label;
      // this.form.handUserName1 = undefined;
      // this.gradeDirectorList()
    },
    /** 导出按钮操作 */
    handleExport() {
      // 导出选中，导出全部，根据查询条件导出
      this.exportOptions.open = true;
    },

    /** 导出 */
    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 = {
        teacherId: this.$store.state.user.userId,
        teacherName: null,
        applyOrgname: null,
        startTime: null,
        endTime: null,
        startSort: null,
        endSort: null,
        totalTime: 0,
        type: null,
        handUserName1: null,
        handUserName2: null,
        handUserName3: null,
        reasonForLeave: null,
      }
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        let temp1, temp2, temp3
        [this.form.startTime,
        this.form.endTime,
          temp1,
          temp2,
          temp3] =
          [formatDate(this.form.startTime),
          formatDate(this.form.endTime),
          this.form.startTime,
          this.form.endTime,
          this.title]
        console.log(temp1, temp2)
        if (valid) {
          if (this.form.totalTime < 2) {
            this.form.handUserName3 = null;
            this.form.handUserId3 = null;
            if (this.form.totalTime < 0.5) {
              this.form.handUserName2 = null;
              this.form.handUserId2 = null;
            }
          }

          if (this.form.id != null) {
            updateTeacherLeave({ ...this.form, title: temp3 }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dialogTeacherLeave = false;
              this.getList();
            });
          } else {
            addTeacherLeave({ ...this.form, title: temp3 }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialogTeacherLeave = false;
              this.getList();
            });
          }
        } else {
          this.form.startTime = temp1
          this.form.endTime = temp2
        }
      });
    },
    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) {
      this.$confirm('确认要提交申请?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 打开遮罩层
        this.$modal.loading("正在提交请假申请，请稍后...");
        submitApply(row.id).then(res => {
          if (res.code == 200) {
            // 关闭遮罩层
            this.$modal.closeLoading();
            this.$message({
              type: 'success',
              message: '提交成功!'
            });
            this.getList()
          }
        })
      }).catch(() => {
        // 关闭遮罩层
        this.$modal.closeLoading();
      });
    },
    /** 查看详情 */
    handleDetailAwait(row) {
      console.log(725, row)
      this.reset();
      this.isEdit = true;
      const teacherId = this.ids || row.id;
      getTeacherLeave(teacherId).then(response => {
        this.form = response.data;
        // this.dialogTeacherLeaveView = true;
        this.dialogTeacherLeave = true;
        this.dialogTitle = "请假信息详情";
      });
    },
    /** 【已提交】查看详情 */
    handleDetail(row) {
      this.form = row
      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);
    // },
    //获取级部/处室下拉框
    // getGradeOffice() {
    //   getGradeOfficeList().then(((res) => {
    //     if (res.code == 200) {
    //       console.log(res, 728)
    //       this.gradeOfficeList = res.data[0].children
    //       // this.form.applyOrgname
    //       // this.applyOrgname = this.gradeOfficeList[0]
    //     }
    //   }))
    // },
    //获校领导下拉框、
    schoolLeader() {
      getLeaderList().then(((res) => {
        if (res.code == 200) {
          this.schoolLeaderList = res.rows
        }
      }))
    },

    //填充级部/处室数据到form,并且根据id获取主任列表
    getGradeOfficeDirector(data) {
      if (this.form.handUserName1) {
        this.form.handUserName1 = ""
      }
      const { id, label } = data;
      console.log(id, label, 758)
      this.form.applyOrgname = label;
      this.form.applyOrgid = id;
      getGradeOfficeDirectorList(id).then(((res) => {
        if (res.code == 200) {
          this.gradeOfficeDirectorList = res.rows
        }
      }))
    },
    handleDirector(data) {
      const { handUserName1, handUserId1 } = data;
      this.form.handUserName1 = handUserName1;
      this.form.handUserId1 = handUserId1;
    },
    handleDeputyLeader(data) {
      const { handUserName2, handUserId2 } = data;
      this.form.handUserName2 = handUserName2;
      this.form.handUserId2 = handUserId2;
    },


    handleLeader(data) {
      const { handUserName3, handUserId3 } = data;
      this.form.handUserName3 = handUserName3;
      this.form.handUserId3 = handUserId3;
    },

    leaveTime() {
      //0代表教工，1代表职工
      if (this.employeeType == 0) {
        if (this.form.startTime && this.form.endTime && this.form.startSort && this.form.endSort) {
          getLeaveTime({
            startTime: formatDate(this.form.startTime),
            endTime: formatDate(this.form.endTime),
            startSort: this.form.startSort,
            endSort: this.form.endSort,
            applyType: this.employeeType
          }).then((res) => {
            if (res.code == 200) {
              this.$set(this.form, 'dayCourse', res.dayCourse)
              this.$set(this.form, 'totalTime', res.data)
            }
          })
        }
      } else {
        if (this.form.startTime && this.form.endTime) {
          getLeaveTime({
            startTime: formatDate(this.form.startTime),
            endTime: formatDate(this.form.endTime),
            applyType: this.employeeType
          }).then((res) => {
            if (res.code == 200) {
              this.$set(this.form, 'totalTime', res.data)
            }
          })
        }
      }
    },
    getFormatDate(timeDate) {
      let date = new Date(timeDate);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      return [year, '-', month, '-', day].join('');
    },

    //获取级部/处室  主任  下拉框
    gradeDirectorList() {
      this.$nextTick(() => {
        getGradeOfficeDirectorList(this.form.applyOrgid).then(((res) => {
          if (res.code == 200) {
            this.gradeOfficeDirectorList = res.rows
          }
        }))
      })
    },

    formReady() {
      //获取级部处室下拉框
      getGradeOfficeList().then(((res) => {
        this.gradeOfficeList = res.data;
      })).then(() => {
        getDepId().then(res => {
          this.$set(this.form, "applyOrgid", res.data);
          this.form.applyOrgid = res.data
          this.employeeType = res.employeeType
          console.log(this.employeeType, '22');
          let arr = this.readNodes(this.gradeOfficeList)
          const node = arr.find(item => {
            if (item.id == this.form.applyOrgid) {
              return item
            }
          })
          this.form.applyOrgname = node.label
          //获取级部/处室  主任  下拉框
          // getGradeOfficeDirectorList(this.form.applyOrgid).then(((res) => {
          //   if (res.code == 200) {
          //     this.gradeOfficeDirectorList = res.rows
          //   }
          // }))
        })
      })
    },
    readNodes(nodes = [], arr = []) {
      for (let item of nodes) {
        arr.push({ id: item.id, label: item.label })
        if (item.children && item.children.length) this.readNodes(item.children, arr)
      }
      return arr
    },

    // 选择处理人:打开对话框
    openSelect(title, method, type) {
      this.selectHandles.open = true;
      this.selectHandles.title = title;
      this.selectHandles.method = method;
      this.selectHandles.type = type;
      // 将级部、处室 id赋值
      this.selectHandles.id = this.form.applyOrgid;
      console.log('this.selectHandles', this.selectHandles);
    },
    // 选择处理人
    selectUser(select) {
      console.log('this.form1', this.form);

      // 这种写法存在一定危险，后续最好是可以有更好的字段名对应
      this.$set(this.form, `handUserName${this.selectHandles.type}`, select.name);
      this.$set(this.form, `handUserId${this.selectHandles.type}`, select.id);
      console.log('this.form', this.form);
    }
  }
};
</script>
