<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card>
          <template slot="header">
            <span>提交请假申请</span>
          </template>
          <!-- 左侧是新增表单 -->
          <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-loading="loading">
            <el-form-item label="审批部门" prop="applicantDeptName">
              <!-- <dict-select v-model="form.applicantDeptName" dict-type="hrm_department"
                placeholder="请选择审批部门"></dict-select> -->
              <el-select v-model="form.applicantDeptName" placeholder="请选择审批部门" filterable @change="getDeptLeader">
                <el-option v-for="item in deptOptions" :key="item.deptId"
                  :label="item.deptName + '(' + (item.leader || '无负责人') + ')'" :value="item.deptName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="请假类型" prop="leaveType">
              <el-select v-model="form.leaveType" placeholder="请选择请假类型">
                <el-option v-for="dict in dict.type.hrm_leave_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="请假人姓名" prop="applicantName">
              <dict-select v-model="form.applicantName" dict-type="hrm_leave_employee"
                placeholder="请选择请假人姓名"></dict-select>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable v-model="form.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择请假开始时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable v-model="form.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择请假结束时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="请假班次" prop="leaveShift">
              <el-select v-model="form.leaveShift" placeholder="请选择请假班次">
                <el-option v-for="dict in dict.type.hrm_leave_shift" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="请假天数" prop="leaveDays">
              <el-input v-model="form.leaveDays" placeholder="选择时间后自动计算，也可手动修改" />
            </el-form-item>
            <el-form-item label="请假原因" prop="leaveReason">
              <el-input v-model="form.leaveReason" type="textarea" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="附件" prop="attachmentUrls">
              <FileUpload v-model="form.attachmentUrls" :max-count="1" :show-file-list="true" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-form>
          <div style="text-align: center;">
            <el-button type="primary" @click="handleSubmit" v-loading="loading">{{ form.applyId ? '更新申请' : '提交申请' }}</el-button>
            <el-button @click="handleReset">重置表单</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card>
          <template slot="header">
            <span>请假申请列表</span>
            <el-button style="float: right;" icon="el-icon-refresh" @click="getList">刷新</el-button>
          </template>
          <el-table v-loading="loading" :data="leaveRequestList">
            <el-table-column label="申请状态" align="center" prop="approvalStatus"></el-table-column>
            <el-table-column label="请假类型" align="center" prop="leaveType">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.hrm_leave_type" :value="scope.row.leaveType" />
              </template>
            </el-table-column>
            <el-table-column label="请假人姓名" align="center" prop="applicantName">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.hrm_leave_employee" :value="scope.row.applicantName" />
              </template>
            </el-table-column>
            <el-table-column label="审批人" align="center" prop="approverName"></el-table-column>
            <el-table-column label="开始时间" align="center" prop="startTime" width="120">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center" prop="endTime" width="120">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="请假班次" align="center" prop="leaveShift">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.hrm_leave_shift" :value="scope.row.leaveShift" />
              </template>
            </el-table-column>
            <el-table-column label="具体原因" align="center" prop="leaveReason" show-overflow-tooltip />
            <el-table-column label="请假天数" align="center" prop="leaveDays" />
            <el-table-column label="操作" align="center" width="160">
              <template slot-scope="scope" v-if="scope.row.approvalStatus === '待审批'">
                <el-button icon="el-icon-edit" size="mini" @click="handleEdit(scope.row)">修改</el-button>
                <el-button icon="el-icon-delete" size="mini" @click="handleWithdraw(scope.row)">撤回</el-button>
                <!-- <el-button type="primary" size="mini" @click="handleApprove(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-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getLeaveRequest, addLeaveRequest, updateLeaveRequest } from "@/api/wms/leaveRequest";
import { listApproval, updateApproval } from "@/api/wms/approval"
import { listDept } from "@/api/system/dept"
import FileUpload from '@/components/FileUpload'
import DictSelect from '@/components/DictSelect'

export default {
  name: 'LeaveApply',
  dicts: ['hrm_leave_shift', 'hrm_leave_type', 'hrm_department', 'hrm_leave_employee'],
  components: {
    FileUpload,
    DictSelect
  },
  data() {
    return {
      // 表单参数
      form: {},
      loading: false,
      buttonLoading: false,
      leaveRequestList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        leaveStatus: undefined,
        applyType: 'leave',
        createBy: this.$store.getters.name,
      },
      // 表单校验规则【核心新增：完整必填校验】
      rules: {
        leaveTitle: [{ required: true, message: '请假原因不能为空', trigger: ['blur', 'change'] }],
        leaveType: [{ required: true, message: '请假类型不能为空', trigger: 'change' }],
        applicantName: [{ required: true, message: '请假人姓名不能为空', trigger: 'change' }],
        startTime: [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
        endTime: [{ required: true, message: '结束时间不能为空', trigger: 'change' }],
        leaveShift: [{ required: true, message: '请假班次不能为空', trigger: 'change' }],
        leaveDays: [
          { required: true, message: '请假天数不能为空', trigger: ['blur', 'change'] },
        ],
        applicantDeptName: [{ required: true, message: '审批部门不能为空', trigger: 'change' }],
      },
      deptOptions: []
    }
  },
  // 核心新增：监听开始/结束时间变化，自动计算天数
  watch: {
    'form.startTime': {
      handler() {
        this.calculateLeaveDays()
      },
      immediate: false
    },
    'form.endTime': {
      handler() {
        this.calculateLeaveDays()
      },
      immediate: false
    },
  },
  created() {
    this.getList();
    this.getDeptList();
  },
  methods: {
    getDeptList() {
      listDept().then(response => {
        this.deptOptions = response.data
      })
    },
    // 获取部门负责人
    getDeptLeader() {
      const selectedDept = this.deptOptions.find(item => item.deptName === this.form.applicantDeptName)
      const approverName = selectedDept.leader;
      if (!approverName) {
        this.$message.warning('该部门无负责人，申请将无人审批');
        return;
      }
      this.form.approverName = approverName
    },
    /** 查询员工请假申请列表 */
    getList() {
      this.loading = true;
      listApproval(this.queryParams).then(response => {
        this.leaveRequestList = response.rows.map(item => {
          return {
            approvalStatus: item.approval.approvalStatus,
            applyId: item.approval.applyId,
            approvalId: item.approval.approvalId,
            approvalType: item.approval.approvalType,
            approverName: item.approval.approverName,
            ...item.detail,
          }
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    handleReset() {
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        leaveId: undefined,
        leaveTitle: undefined,
        leaveType: undefined,
        applicantName: undefined,
        applicantDeptName: undefined,
        startTime: undefined,
        endTime: undefined,
        leaveShift: undefined,
        leaveDays: undefined,
        leaveReason: undefined,
        attachmentUrls: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.loading = true;
      this.reset();
      const leaveId = row.applyId
      getLeaveRequest(leaveId).then(response => {
        this.loading = false;
        this.form = response.data;
      });
    },
    /** 提交按钮 */
    handleSubmit() {
      this.form.leaveTitle = `${this.form.applicantName}-${this.form.leaveType}-${this.form.startTime}-${this.form.leaveReason || ''}`
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.leaveId != null) {
            updateLeaveRequest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
              this.reset()
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addLeaveRequest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.getList();
              this.reset()
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    handleWithdraw(row) {
      this.$modal.confirm('是否确认撤回请假申请编号为"' + row.applyId + '"的数据项？').then(() => {
        this.loading = true;
        return updateApproval({
          approvalId: row.approvalId,
          approvalStatus: '已撤销'
        });
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("撤回成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    // 核心新增：自动计算请假天数的方法
    calculateLeaveDays() {
      const { startTime, endTime } = this.form;
      // 两个时间都选择后才计算
      if (startTime && endTime) {
        // 转成时间戳
        const start = new Date(startTime).getTime();
        const end = new Date(endTime).getTime();
        // 判断结束时间不能小于开始时间
        if (end < start) {
          this.$modal.msgWarning('结束时间不能早于开始时间，请重新选择！');
          this.form.leaveDays = undefined;
          return;
        }
        // 计算时间差(毫秒) → 转天 → 保留2位小数
        const diffTime = end - start;
        const diffDays = (diffTime / (1000 * 60 * 60 * 24)).toFixed(2);
        // 赋值到天数输入框
        this.form.leaveDays = diffDays;
      }
    }
  }
}
</script>