<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="学号" prop="stuNo">
        <el-input v-model="search.stuNo" placeholder="请输入学号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="学生姓名" prop="name">
        <el-input v-model="search.name" placeholder="请输入请学生姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="班级" label-width="40px">
        <el-select v-model="search.className" style="width: 100%" size="mini" @change="changeSelect">
          <el-option v-for="(v, i) in class_list" :key="i" :label="v.className" :value="v.className" />
        </el-select>
      </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">
        <el-button v-hasPermi="['routine:leaveApplication:add']" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['routine:leaveApplication:export']" type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="leaveApplicationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学号" align="center" prop="stuNo" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="请假原因" align="center" prop="reason" />
      <el-table-column label="请假类型" align="center" prop="leaveType">
        <!-- 请假类型：0病假 1事假 -->
        <template slot-scope="scope">
          <el-tag v-if="scope.row.leaveType == 0" type="success">病假</el-tag>
          <el-tag v-else type="danger">事假</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="请假天数" align="center" prop="leaveDays" />
      <el-table-column label="起止时间" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>~
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <!-- 审批状态（0、待审批；1、已通过； -->
          <el-tag v-if="scope.row.status == 0">待审批</el-tag>
          <el-tag v-else-if="scope.row.status == 1">已通过</el-tag>
          <el-tag v-else-if="scope.row.status == 2">已驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="假条状态" align="center" prop="cancellation">
        <template slot-scope="scope">
          <!-- 销假状态：0-未销假；1-销假申请；2-已销假 -->
          <el-tag v-if="scope.row.cancellation == 0" type="danger">未销假</el-tag>
          <el-tag v-else-if="scope.row.cancellation == 1">销假申请中</el-tag>
          <el-tag v-else-if="scope.row.cancellation == 2">已销假</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="createTime" />
      <el-table-column label="提交状态" align="center" prop="leaveStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.rt_submission_status" :value="scope.row.leaveStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.leaveStatus == 0" v-hasPermi="['routine:leaveApplication:edit']" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button v-if="scope.row.leaveStatus == 0" v-hasPermi="['routine:leaveApplication:remove']" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button v-if="scope.row.leaveStatus == 1" size="mini" type="text" icon="el-icon-info" @click="detail(scope.row)">详情</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" />

    <!-- 添加或修改学生请假申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="学号" prop="stuNo">
              <el-input v-model="stuInfo.stuNo" placeholder="学号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="stuNo">
              <el-input v-model="stuInfo.studentName" placeholder="姓名" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="stuNo">
              <el-input v-model="stuInfo.gender" placeholder="性别" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="院部" prop="departmentName">
              <el-input v-model="stuInfo.departmentName" placeholder="院部" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="班级" prop="className">
              <el-input v-model="stuInfo.className" placeholder="班级" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="phoneNumber">
              <el-input v-model="stuInfo.phoneNumber" placeholder="联系电话" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="家长姓名" prop="fatherName">
              <el-input v-model="stuInfo.fatherName" placeholder="家长姓名" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="家长联系电话" prop="fatherRelation">
              <el-input v-model="stuInfo.fatherRelation" placeholder="家长联系电话" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="请假事由" prop="reason">
              <el-radio v-model="form.leaveType" label="0">病假</el-radio>
              <el-radio v-model="form.leaveType" label="1">事假</el-radio>
              <span>（备注：学生因病请假的，辅导员必须在OA提交因病缺勤追踪登记表）</span>
              <br>
              <el-input v-model="form.reason" placeholder="请输入请假事由" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="请假起始时间" prop="startDate">
              <el-date-picker v-model="form.startDate" clearable type="date" value-format="yyyy-MM-dd" placeholder="请选择请假起始时间" @change="calculateLeaveDays" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="请假截止时间" prop="endDate">
              <el-date-picker v-model="form.endDate" clearable type="date" value-format="yyyy-MM-dd" placeholder="请选择请假截止时间" @change="calculateLeaveDays" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="请假天数" prop="leaveDays">
              <el-input v-model="form.leaveDays" placeholder="请输入请假天数" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="目的地" prop="destination">
              <el-input v-model="form.destination" placeholder="请输入目的地" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="目的地详细" prop="destinationDetails">
              <el-input v-model="form.destinationDetails" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="安全承诺书" prop="safetyPromise">
              <el-checkbox v-model="form.safetyPromise">签署</el-checkbox>
              <span>《广西水利电力职业技术学院安全承诺书》</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="请假人签字上传" prop="applicantSignature">
              <image-upload v-model="form.applicantSignature" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="材料附件" prop="attachment">
              <image-upload v-model="form.attachment" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" @click="save">保 存</el-button>
        <el-button type="primary" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getListLeaveApplication, getLeaveApplication, delLeaveApplication, addLeaveApplication, updateLeaveApplication, getStuInfo, save } from '@/api/routine/leaveApplication'
import { listOwnClass } from '@/api/stuCQS/info-fill/stu_eva_task'
import Signature from '@/components/signature.vue'
import store from '@/store'

export default {
  name: 'LeaveApplication',
  components: {
    Signature,
  },
  dicts: ['rt_submission_status'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生请假申请表格数据
      leaveApplicationList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stuId: null,
        reason: null,
        leaveType: null,
        startDate: null,
        endDate: null,
        leaveDays: null,
        destination: null,
        destinationDetails: null,
        safetyPromise: null,
        applicantSignature: null,
        attachment: null,
        counselorComments: null,
        cancellation: null,
        leaveStatus: null,
        leavingGx: null,
        status: null,
      },
      search: {
        stuNo: '',
        className: '',
        name: '',
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        reason: [{ required: true, message: '请假事由不能为空', trigger: 'blur' }],
        leaveType: [{ required: true, message: '请假类型不能为空', trigger: 'change' }],
        startDate: [{ required: true, message: '请假起始时间不能为空', trigger: 'blur' }],
        endDate: [{ required: true, message: '请假截止时间不能为空', trigger: 'blur' }],
        leaveDays: [{ required: true, message: '请假天数不能为空', trigger: 'blur' }],
        destination: [{ required: true, message: '目的地不能为空', trigger: 'blur' }],
        safetyPromise: [{ required: true, message: '请勾选安全承诺书', trigger: 'change' }],
        applicantSignature: [{ required: true, message: '请假人签字不能为空', trigger: 'blur' }],
      },
      class_list: [],
      stuInfo: {},
      isShowSignature: false,
      signature: '',
      userRole: [],
    }
  },
  created() {
    this.getList()
    this.listOwnClass()
    this.getRoles()
  },
  methods: {
    // 获取角色信息
    getRoles() {
      this.userRole = store.state.user.roles
    },
    /** 查询学生请假申请列表 */
    getList() {
      this.loading = true
      getListLeaveApplication(this.search).then((response) => {
        this.leaveApplicationList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        leaveApplicationId: null,
        stuId: null,
        reason: null,
        leaveType: null,
        startDate: null,
        endDate: null,
        leaveDays: null,
        destination: null,
        destinationDetails: null,
        safetyPromise: null,
        applicantSignature: null,
        attachment: null,
        counselorComments: null,
        cancellation: null,
        leaveStatus: null,
        leavingGx: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: 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.leaveApplicationId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getStuInfo()
      this.open = true
      this.title = '添加学生请假申请'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getStuInfo()
      const leaveApplicationId = row.leaveApplicationId || this.ids
      getLeaveApplication(leaveApplicationId).then((response) => {
        this.form = response.data
        this.form.safetyPromise = this.form.safetyPromise == '0' ? false : true
        this.open = true
        this.title = '修改学生请假申请'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$modal.loading('正在生成请假单，请稍等。。。')
          this.form.safetyPromise = this.form.safetyPromise == true ? '1' : '0'

          if (this.form.leaveApplicationId != null) {
            updateLeaveApplication(this.form).then((response) => {
              this.$modal.closeLoading()
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addLeaveApplication(this.form).then((response) => {
              this.$modal.closeLoading()

              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const leaveApplicationIds = row.leaveApplicationId || this.ids
      this.$modal
        .confirm('是否确认删除学生请假申请编号为"' + leaveApplicationIds + '"的数据项？')
        .then(function () {
          return delLeaveApplication(leaveApplicationIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'routine/leaveApplication/export',
        {
          ...this.queryParams,
        },
        `leaveApplication_${new Date().getTime()}.xlsx`
      )
    },
    async listOwnClass() {
      this.loading = true
      let res = await listOwnClass()
      this.loading = false
      if (res.code == 200) {
        this.class_list = [...res.data]
      }
    },
    async changeSelect() {
      let status = this.search.status
      let className = this.search.className
      let year = this.search.stuYearName
      if (!isEmpty(className)) {
        if (!isEmpty(status)) {
          if (!isEmpty(year)) {
            let temp1 = []
            let temp2 = [...this.all_stu_list]
            temp2.map((x) => {
              if (x.status == status && x.className == className && x.stuYearName == year) {
                temp1.push(x)
              }
            })
            this.total = 0
            this.queryParams.pageSize = temp1.length
            this.stu_list = [...temp1]
            return
          } else {
            let temp1 = []
            let temp2 = [...this.all_stu_list]
            temp2.map((x) => {
              if (x.status == status && x.className == className) {
                temp1.push(x)
              }
            })
            this.total = 0
            this.queryParams.pageSize = temp1.length
            this.stu_list = [...temp1]
            return
          }
        } else {
          if (!isEmpty(year)) {
            let temp1 = []
            let temp2 = [...this.all_stu_list]
            temp2.map((x) => {
              if (x.className == className && x.stuYearName == year) {
                temp1.push(x)
              }
            })
            this.total = 0
            this.queryParams.pageSize = temp1.length
            this.stu_list = [...temp1]
            return
          } else {
            let temp1 = []
            let temp2 = [...this.all_stu_list]
            temp2.map((x) => {
              if (x.className == className) {
                temp1.push(x)
              }
            })
            this.total = 0
            this.queryParams.pageSize = temp1.length
            this.stu_list = [...temp1]

            return
          }
        }
      }
    },
    getStuInfo() {
      getStuInfo().then((res) => {
        if (res.code == 200) {
          // console.log(res)
          this.stuInfo = res.data
          // console.log('学生数据', this.stuInfo)
        }
      })
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.safetyPromise = this.form.safetyPromise == true ? '1' : '0'

          save(this.form).then((response) => {
            this.$modal.msgSuccess('修改成功')
            this.open = false
            this.getList()
          })
        }
      })
    },
    calculateLeaveDays() {
      if (this.form.startDate && this.form.endDate) {
        const start = new Date(this.form.startDate)
        const end = new Date(this.form.endDate)
        const days = Math.ceil((end - start) / (1000 * 60 * 60 * 24))
        this.form.leaveDays = days.toString()
      } else {
        this.form.leaveDays = null
      }
    },
    onShowSignature() {
      this.isShowSignature = true
    },
    onSignatureDone(base64) {
      this.signature = base64
      this.isShowSignature = false
    },
    onSignatureClear() {
      this.signature = ''
      this.isShowSignature = false
    },
    detail(row) {
      this.$router.push({
        path: '/routine/leaveApplication/detail',
        query: {
          procInsId: row.processInstanceId,
          deployId: row.deployId,
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.signature {
  width: 100vw;
}
</style>
