<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="60px">
      <el-form-item label="请假类型" prop="leaveType">
        <el-select v-model="queryParams.leaveType" placeholder="请选择请假类型" clearable>
          <el-option v-for="dict in dict.type.hrm_leave_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="请假人" prop="applicantName">
        <dict-select v-model="queryParams.applicantName" dict-type="hrm_leave_employee"
          placeholder="请选择请假人姓名"></dict-select>
      </el-form-item>
      <el-form-item label="部门名称" prop="applicantDeptName">
        <dict-select v-model="queryParams.applicantDeptName" dict-type="hrm_department"
          placeholder="请选择请假人部门名称"></dict-select>
      </el-form-item>
      <el-form-item label="请假班次" prop="leaveShift">
        <el-select v-model="queryParams.leaveShift" placeholder="请选择请假班次" clearable>
          <el-option v-for="dict in dict.type.hrm_leave_shift" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </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 type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="leaveRequestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="leaveId" v-if="false" />
      <el-table-column label="请假原因" align="center" prop="leaveTitle" />
      <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="applicantDeptName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.hrm_department" :value="scope.row.applicantDeptName" />
        </template>
      </el-table-column>
      <el-table-column label="开始时间" 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="结束时间" 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="请假班次" 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="leaveDays" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="请假原因" prop="leaveTitle">
          <el-input v-model="form.leaveTitle" placeholder="请输入请假标题" />
        </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="applicantDeptName">
          <dict-select v-model="form.applicantDeptName" dict-type="hrm_department" 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 slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLeaveRequest, getLeaveRequest, delLeaveRequest, addLeaveRequest, updateLeaveRequest } from "@/api/wms/leaveRequest";
import FileUpload from '@/components/FileUpload'
import DictSelect from '@/components/DictSelect'

export default {
  name: "LeaveRequest",
  dicts: ['hrm_leave_shift', 'hrm_leave_type', 'hrm_department', 'hrm_leave_employee'],
  components: {
    FileUpload,
    DictSelect
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工请假申请表格数据
      leaveRequestList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        leaveType: undefined,
        applicantName: undefined,
        applicantDeptName: undefined,
        leaveShift: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验规则【核心新增：完整必填校验】
      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'] },
        ],
        leaveReason: [ 
          { required: true, message: '具体原因不能为空', trigger: ['blur', 'change'] },
        ]
      }
    };
  },
  // 核心新增：监听开始/结束时间变化，自动计算天数
  watch: {
    'form.startTime': {
      handler() {
        this.calculateLeaveDays()
      },
      immediate: false
    },
    'form.endTime': {
      handler() {
        this.calculateLeaveDays()
      },
      immediate: false
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询员工请假申请列表 */
    getList() {
      this.loading = true;
      listLeaveRequest(this.queryParams).then(response => {
        this.leaveRequestList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      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();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.leaveId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加员工请假申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const leaveId = row.leaveId || this.ids
      getLeaveRequest(leaveId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改员工请假申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.leaveId != null) {
            updateLeaveRequest(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addLeaveRequest(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const leaveIds = row.leaveId || this.ids;
      this.$modal.confirm('是否确认删除员工请假申请编号为"' + leaveIds + '"的数据项？').then(() => {
        this.loading = true;
        return delLeaveRequest(leaveIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/leaveRequest/export', {
        ...this.queryParams
      }, `leaveRequest_${new Date().getTime()}.xlsx`)
    },
    // 核心新增：自动计算请假天数的方法
    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>