<template>
  <div class="app-container">
    <el-row>
      <el-form
        ref="queryForm"
        :model="queryParams"
        size="small"
        :inline="true"
        class="app-container--search"
      >
        <el-form-item label="员工编号" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入员工编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="员工姓名" prop="nickName">
          <el-input
            v-model="queryParams.nickName"
            placeholder="请输入员工姓名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </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>

    <el-table v-loading="loading" :data="tableData" highlight-current-row>
      <el-table-column type="index" label="序号" />
      <el-table-column
        label="员工编号"
        align="center"
        prop="userName"
        sortable
      />
      <el-table-column
        label="员工姓名"
        align="center"
        prop="nickName"
        sortable
      />
      <el-table-column
        label="所属部门"
        align="center"
        prop="deptName"
        sortable
      />
      <el-table-column
        label="年假总额"
        align="center"
        prop="annualLeave"
        sortable
      >
        <template slot-scope="scope">
          <span>{{ parseInt(scope.row.annualLeave) || 0 }} 天</span>
        </template>
      </el-table-column>
      <el-table-column
        label="已使用天数"
        align="center"
        prop="usedDay"
        sortable
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleDetail(scope.row)"
            >{{ parseInt(scope.row.usedDay) || 0 }} 天</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="剩余天数"
        align="center"
        prop="unusedDay"
        sortable
      >
        <template slot-scope="scope">
          <span>{{ parseInt(scope.row.unusedDay) || 0 }} 天</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="isEnable" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.isEnable == 0"> 清零 </span>
          <span v-if="scope.row.isEnable == 1"> 有效 </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="220"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleApply(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="休假明细" :visible.sync="detailDialogVisible" width="50%">
      <el-descriptions :column="3" border style="margin-bottom: 20px">
        <el-descriptions-item label="员工编号">
          {{ detailRow.userName }}
        </el-descriptions-item>
        <el-descriptions-item label="员工姓名">
          {{ detailRow.nickName }}
        </el-descriptions-item>
        <el-descriptions-item label="所属部门">
          {{ detailRow.deptName }}
        </el-descriptions-item>
        <el-descriptions-item label="年假总额">
          {{ detailRow.annualLeave }}
        </el-descriptions-item>
        <el-descriptions-item label="已使用天数">
          {{ detailRow.usedDay }}
        </el-descriptions-item>
        <el-descriptions-item label="剩余天数">
          {{ detailRow.unusedDay }}
        </el-descriptions-item>
      </el-descriptions>
      <el-table :data="detailRows" style="width: 100%">
        <el-table-column label="申请日期" prop="createTime" />
        <el-table-column label="休假天数" prop="usedDay" />
        <el-table-column label="休假时间" prop="applyDates">
          <template slot-scope="scope">
            <p
              v-for="date in scope.row.applyDates.split(',')"
              :key="date"
              style="margin: 0"
            >
              {{ date }}
            </p>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status">
          <template slot-scope="scope">
            <span v-if="scope.row.status == '0'" style="color: #409eff">
              待提交
            </span>
            <span v-else-if="scope.row.status == '1'" style="color: #e6a23c">
              待审批
            </span>
            <span v-else-if="scope.row.status == '2'" style="color: #67c23a">
              审批通过
            </span>
            <span v-else-if="scope.row.status == '3'" style="color: #f56c6c">
              驳回
            </span>
            <span v-else-if="scope.row.status == '4'" style="color: #909399">
              已作废
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              v-if="['0', '1', '2', '3'].includes(scope.row.status)"
              type="text"
              @click="handleDelete(scope.row)"
              >作废</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="申请休假" :visible.sync="applyDialogVisible" width="50%">
      <el-descriptions :column="3" border style="margin-bottom: 20px">
        <el-descriptions-item label="员工编号">
          {{ detailRow.userName }}
        </el-descriptions-item>
        <el-descriptions-item label="员工姓名">
          {{ detailRow.nickName }}
        </el-descriptions-item>
        <el-descriptions-item label="所属部门">
          {{ detailRow.deptName }}
        </el-descriptions-item>
        <el-descriptions-item label="年假总额">
          {{ detailRow.annualLeave }}
        </el-descriptions-item>
        <el-descriptions-item label="已使用天数">
          {{ detailRow.usedDay }}
        </el-descriptions-item>
        <el-descriptions-item label="剩余天数">
          {{ detailRow.unusedDay }}
        </el-descriptions-item>
      </el-descriptions>
      <h3>申请信息</h3>
      <el-form
        :model="applyForm"
        :rules="applyRules"
        ref="applyFormRef"
        label-width="100px"
        size="small"
        label-suffix="："
        style="margin-right: 40px"
      >
        <el-form-item label="休假天数" prop="days">
          <span>{{ applyForm.usedDay }} 天</span>
        </el-form-item>
        <el-form-item
          v-for="(item, index) in applyForm.applyDates"
          :prop="`applyDates[${index}]`"
          :key="index"
          :label="`休假时间`"
        >
          <div style="display: flex; gap: 10px">
            <el-date-picker
              v-model="applyForm.applyDates[index]"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
              @change="handleDateChange"
            >
            </el-date-picker>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              plain
              v-if="applyForm.applyDates.length > 1"
              @click="handleDeleteDay(index)"
            ></el-button>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-plus"
              plain
              style="margin-left: 0"
              v-if="index === applyForm.applyDates.length - 1"
              @click="handleAddDay(index)"
            ></el-button>
          </div>
        </el-form-item>
      </el-form>
      <h3>休假记录</h3>
      <el-table
        :data="detailRows"
        size="mini"
        height="180px"
        style="width: 100%"
      >
        <el-table-column label="申请日期" prop="createTime" />
        <el-table-column label="休假天数" prop="usedDay" width="100" />
        <el-table-column label="休假时间" prop="applyDates"> </el-table-column>
        <el-table-column label="状态" prop="status" width="100" >
          <template slot-scope="scope">
            <span v-if="scope.row.status == '0'" style="color: #409eff">
              待提交
            </span>
            <span v-else-if="scope.row.status == '1'" style="color: #e6a23c">
              待审批
            </span>
            <span v-else-if="scope.row.status == '2'" style="color: #67c23a">
              审批通过
            </span>
            <span v-else-if="scope.row.status == '3'" style="color: #f56c6c">
              驳回
            </span>
            <span v-else-if="scope.row.status == '4'" style="color: #909399">
              已作废
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              v-if="['0', '1', '2', '3'].includes(scope.row.status)"
              type="text"
              @click="handleDelete(scope.row)"
              >作废</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="applyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleApplySubmit">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  balanceList,
  detailList,
  detailApply,
  delDetail,
} from "@/api/oa/leave/annual";

export default {
  name: "AnnualBalance",
  components: {},
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,

      // 总条数
      total: 0,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        userName: undefined,
        nickName: undefined,
      },

      // 休假明细
      detailDialogVisible: false,
      detailRows: [],
      detailRow: {},

      // 申请休假
      applyDialogVisible: false,
      applyForm: {
        userId: "",
        usedDay: 1,
        applyDate: "",
        applyDates: [""],
      },
      applyRules: {},

      // 表单参数
      tableData: [],
    };
  },
  computed: {
    // 表单验证
    isFormValid() {
      return (
        this.formData.name.trim() !== "" &&
        !isNaN(parseFloat(this.formData.lng)) &&
        !isNaN(parseFloat(this.formData.lat)) &&
        this.formData.radius >= 10 &&
        this.formData.radius <= 5000
      );
    },
    // 过滤后的用户列表
    filteredUsers() {
      // 获取不在当前考勤组中的用户
      const groupMemberIds = this.attendanceGroup.members.map(
        (member) => member.id
      );
      const availableUsers = this.users.filter(
        (user) => !groupMemberIds.includes(user.id)
      );

      // 应用搜索过滤
      if (!this.userSearchKeyword) return availableUsers;

      const keyword = this.userSearchKeyword.toLowerCase();
      return availableUsers.filter(
        (user) =>
          user.name.toLowerCase().includes(keyword) ||
          user.employeeId.toLowerCase().includes(keyword) ||
          user.department.toLowerCase().includes(keyword) ||
          user.position.toLowerCase().includes(keyword)
      );
    },
    // 日期选择器配置
    pickerOptions() {
      return {
        disabledDate: this.disabledDate,
      };
    },
  },
  mounted() {
    this.getList();
  },
  methods: {
    /**
     * 禁用日期 - 只允许选择本年的未来日期（包括今天）
     * @param {Date} date - 要检查的日期
     * @returns {boolean} 是否禁用该日期
     */
    disabledDate(date) {
      if (!date) return false;

      const currentYear = new Date().getFullYear();
      const selectedYear = date.getFullYear();

      // 获取今天的日期（不包含时间）
      const today = new Date();
      today.setHours(0, 0, 0, 0);

      // 设置传入日期的时间为0，便于比较
      const compareDate = new Date(date);
      compareDate.setHours(0, 0, 0, 0);

      // 禁用非本年的日期
      if (selectedYear !== currentYear) {
        return true;
      }

      return false;
    },
    handleDelete(row) {
      this.$confirm("确定作废该明细吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delDetail(row.id).then((res) => {
            this.getList();

            detailList({
              userName: row.userName,
            }).then((response) => {
              this.detailRows = response.rows;
              this.detailDialogVisible = false;
              this.applyDialogVisible = false;
            });
          });
        })
        .catch(() => {});
    },
    /**
     * 格式化日期为 YYYY-MM-DD 格式
     * @param {Date} date - 日期对象
     * @returns {string} 格式化后的日期字符串
     */
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    /**
     * 提交申请
     * 验证日期有效性和天数限制
     */
    handleApplySubmit() {
      // 先验证所有日期项都不为空
      const hasEmptyDate = this.applyForm.applyDates.some((date) => !date);
      if (hasEmptyDate) {
        this.$message.error("请选择所有休假时间");
        return;
      }

      // 验证日期不重复
      const hasDuplicateDate = this.checkDuplicateDates();
      if (hasDuplicateDate) {
        this.$message.error("休假时间不能重复");
        return;
      }

      // 验证申请天数不超过剩余天数
      const remainingDay = parseInt(this.detailRow.unusedDay) || 0;
      const requestedDay = this.applyForm.applyDates.filter(
        (date) => date
      ).length;
      if (requestedDay > remainingDay) {
        this.$message.error(`申请天数不能超过剩余天数 ${remainingDay} 天`);
        return;
      }

      this.$refs.applyFormRef.validate((valid) => {
        if (valid) {
          // 将日期数组转换为 YYYY-MM-DD 格式的字符串
          const formattedDates = this.applyForm.applyDates
            .filter((date) => date) // 过滤掉空值
            .map((date) => {
              if (date instanceof Date) {
                return this.formatDate(date);
              }
              return date;
            })
            .join(",");

          const params = {
            userId: this.applyForm.userId,
            usedDay: this.applyForm.usedDay,
            applyDates: formattedDates,
          };
          detailApply(params).then((response) => {
            this.$message.success("申请成功");
            this.applyDialogVisible = false;
            this.getList();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 删除休假时间
    handleDeleteDay(index) {
      this.applyForm.applyDates.splice(index, 1);
      this.applyForm.usedDay = this.applyForm.applyDates.length;
    },
    /**
     * 添加休假时间
     * 检查不能超过剩余天数
     */
    handleAddDay() {
      const currentUsedDay = this.applyForm.applyDates.length;
      const remainingDay = parseInt(this.detailRow.unusedDay) || 0;

      if (currentUsedDay >= remainingDay) {
        this.$message.warning(
          `最多只能申请 ${remainingDay} 天，不能超过剩余天数`
        );
        return;
      }

      this.applyForm.applyDates.push("");
      this.applyForm.usedDay = this.applyForm.applyDates.length;
    },
    /**
     * 检查日期是否重复
     * @returns {boolean} 是否有重复日期
     */
    checkDuplicateDates() {
      const dateStrings = this.applyForm.applyDates
        .filter((date) => date) // 过滤空值
        .map((date) => {
          if (date instanceof Date) {
            return this.formatDate(date);
          }
          return date;
        });

      const uniqueDates = new Set(dateStrings);
      return uniqueDates.size !== dateStrings.length;
    },
    /**
     * 日期选择变化时的处理
     */
    handleDateChange() {
      // 检查是否有重复日期
      if (this.checkDuplicateDates()) {
        this.$message.warning("休假时间不能重复，请重新选择");
      }
    },
    handleApply(row) {
      this.detailRow = row;
      this.applyDialogVisible = true;
      this.applyForm.userId = this.detailRow.userId;
      this.applyForm.userName = this.detailRow.userName;
      this.applyForm.nickName = this.detailRow.nickName;
      this.applyForm.deptName = this.detailRow.deptName;
      this.applyForm.applyDates = [""];
      this.applyForm.usedDay = 1;

      detailList({
        userName: row.userName,
      }).then((response) => {
        this.detailRows = response.rows;
      });
    },
    handleDetail(row) {
      this.detailRow = row;
      detailList({
        userName: row.userName,
      }).then((response) => {
        this.detailRows = response.rows;
        this.detailDialogVisible = true;
      });
    },
    // 加载数据
    getList() {
      this.loading = true;
      balanceList(this.queryParams).then((response) => {
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.userName = undefined;
      this.queryParams.nickName = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 重置表单
    resetForm() {
      this.attendanceGroup = {
        id: null,
        name: "",
        description: "",
        workDays: ["mon", "tue", "wed", "thu", "fri"],
        workStartTime: "09:00",
        workEndTime: "18:00",
        allowLate: true,
        lateRange: 15,
        allowEarly: true,
        earlyRange: 15,
        areaId: null,
        checkInType: "location",
        members: [],
        areaName: "",
      };

      this.isEditMode = false;
      this.selectedGroupId = null;
    },
  },
};
</script>
