<template>
  <div class="app-container">
    <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-row>

    <el-table v-loading="loading" :data="attendanceGroups">
      <el-table-column label="序号" type="index" />
      <el-table-column label="考勤组名称" prop="name" width="180">
      </el-table-column>
      <el-table-column label="规则">
        <template slot-scope="scope">
          <p>
            每周工作{{ scope.row.workDays.length }}天，上班：{{
              scope.row.workStartTime
            }}
            下班{{ scope.row.workEndTime }}，午休：{{ scope.row.lunchTime }}
            小时
          </p>
          <p>时区：{{ scope.row.timeZone || "未设置" }}</p>
          <p>关联员工：{{ scope.row.members.length }}人</p>
          <p>打卡地点：{{ areaName(scope.row.areaId) || "Loading" }}</p>
        </template>
      </el-table-column>
      <el-table-column label="描述" prop="description" width="150">
      </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="editArea(scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="text" @click="deleteArea(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="960px" append-to-body>
      <el-form
        :model="attendanceGroup"
        :rules="rules"
        ref="groupForm"
        label-position="top"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="考勤组名称" prop="name">
              <el-input
                v-model="attendanceGroup.name"
                placeholder="请输入考勤组名称"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 打卡配置 -->
            <el-form-item label="打卡区域" prop="areaId">
              <el-select
                v-model="attendanceGroup.areaId"
                placeholder="请选择打卡区域"
                style="width: 100%"
              >
                <el-option
                  v-for="area in checkInAreas"
                  :key="area.id"
                  :label="area.name"
                  :value="area.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="考勤时区" prop="">
              <el-select
                v-model="attendanceGroup.timeZone"
                placeholder="请选择考勤时区"
              >
                <el-option
                  v-for="item in timeZones"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="上班时间" prop="workStartTime">
              <el-time-picker
                v-model="attendanceGroup.workStartTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择上班时间"
              ></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="下班时间" prop="workEndTime">
              <el-time-picker
                v-model="attendanceGroup.workEndTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择下班时间"
              ></el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="午休开始时间" prop="lunchStartTime">
              <el-time-picker
                v-model="attendanceGroup.lunchStartTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择午休开始时间"
                @change="calculatelunchTime"
              ></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="午休结束时间" prop="lunchEndTime">
              <el-time-picker
                v-model="attendanceGroup.lunchEndTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择午休结束时间"
                @change="calculatelunchTime"
              ></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="午休时间" prop="lunchTime">
              <el-input
                v-model="lunchTimeDisplay"
                placeholder="午休时间（小时）"
                readonly
              >
                <template slot="append">小时</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 基本信息 -->

        <!-- 考勤时间设置 -->
        <el-form-item label="工作日设置">
          <el-checkbox-group v-model="attendanceGroup.workDays">
            <el-checkbox
              v-for="day in workDays"
              :key="day.value"
              :label="day.value"
              >{{ day.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>

        <!-- <el-form-item label="迟到浮动" prop="lateRange">
          <el-col :span="12">
            <el-switch
              v-model="attendanceGroup.allowLate"
              active-text="允许"
              inactive-text="不允许"
              @change="handleLateChange"
            ></el-switch>
          </el-col>
          <el-col :span="12" v-if="attendanceGroup.allowLate">
            <el-slider
              v-model="attendanceGroup.lateRange"
              :min="1"
              :max="30"
              :step="1"
              show-tooltip
              @change="validateLateRange"
            ></el-slider>
            <div class="slider-value">{{ attendanceGroup.lateRange }}分钟</div>
          </el-col>
        </el-form-item> -->

        <!-- 午休时间设置 -->

        <!-- <el-form-item label="早退浮动" prop="earlyRange">
          <el-col :span="12">
            <el-switch
              v-model="attendanceGroup.allowEarly"
              active-text="允许"
              inactive-text="不允许"
              @change="handleEarlyChange"
            ></el-switch>
          </el-col>
          <el-col :span="12" v-if="attendanceGroup.allowEarly">
            <el-slider
              v-model="attendanceGroup.earlyRange"
              :min="1"
              :max="30"
              :step="1"
              show-tooltip
              @change="validateEarlyRange"
            ></el-slider>
            <div class="slider-value">{{ attendanceGroup.earlyRange }}分钟</div>
          </el-col>
        </el-form-item> -->

        <!-- 关联员工 -->
        <el-form-item label="关联员工">
          <el-button
            type="primary"
            size="small"
            @click="openUserSelectionDialog"
          >
            选择员工 ({{ attendanceGroup.members.length }})
          </el-button>

          <el-table
            :data="attendanceGroup.members"
            style="width: 100%; margin-top: 20px"
            empty-text="暂无关联员工"
            height="300px"
            size="mini"
          >
            <el-table-column type="index" label="序号"></el-table-column>
            <el-table-column prop="userName" label="员工编号"></el-table-column>
            <el-table-column prop="nickName" label="姓名"></el-table-column>
            <el-table-column prop="deptName" label="部门"></el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  type="text"
                  @click="deleteRow(scope.$index, attendanceGroup.members)"
                >
                  取消关联
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="buttonLoading"
          type="primary"
          @click="createNewGroup"
          >保 存</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <sys-dept-user
      :propUserList="copyUserList"
      ref="userCopyRef"
      @confirmUser="confirmCopyUser"
    />
  </div>
</template>

<script>
import { add, queryList, queryArea, del } from "@/api/oa/attendance/group";
import SysDeptUser from "@/views/components/user/sys-dept-user";
export default {
  name: "AttendanceGroup",
  components: { SysDeptUser },
  data() {
    return {
      copyUserList: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},

      // 区域列表
      areaList: [],

      // 模态框状态
      showDeleteModal: false,
      currentDeletingArea: null,
      // 考勤组列表
      attendanceGroups: [],
      // 当前选中的考勤组ID
      selectedGroupId: null,
      // 考勤组表单数据
      attendanceGroup: {
        id: null,
        name: "",
        description: "",
        workDays: ["mon", "tue", "wed", "thu", "fri"],
        workStartTime: "09:00",
        workEndTime: "18:00",
        lunchStartTime: "12:00",
        lunchEndTime: "13:00",
        lunchTime: 1,
        allowLate: false,
        lateRange: 15,
        allowEarly: false,
        earlyRange: 15,
        areaId: null,
        checkInType: "location",
        members: [],
        areaName: "",
        timeZone: "",
      },
      attendanceGroupModel: {
        id: null,
        name: "",
        description: "",
        workDays: ["mon", "tue", "wed", "thu", "fri"],
        workStartTime: "09:00",
        workEndTime: "18:00",
        lunchStartTime: "12:00",
        lunchEndTime: "13:00",
        lunchTime: 1,
        allowLate: false,
        lateRange: 15,
        allowEarly: false,
        earlyRange: 15,
        areaId: null,
        checkInType: "location",
        members: [],
        areaName: "",
        timeZone: "",
      },
      // 工作日选项
      workDays: [
        { value: "mon", label: "周一" },
        { value: "tue", label: "周二" },
        { value: "wed", label: "周三" },
        { value: "thu", label: "周四" },
        { value: "fri", label: "周五" },
        { value: "sat", label: "周六" },
        { value: "sun", label: "周日" },
      ],
      // 员工列表
      users: [],
      // 打卡区域列表
      checkInAreas: [],
      // 新建考勤组表单
      newGroup: {
        name: "",
        description: "",
      },
      // 新建考勤组表单规则
      newGroupRules: {
        name: [
          { required: true, message: "请输入考勤组名称", trigger: "blur" },
        ],
      },
      // 搜索关键词
      userSearchKeyword: "",
      // 选中的用户
      selectedUsers: [],
      // 对话框状态
      userSelectionDialogVisible: false,
      showAddGroupModal: false,
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: "请输入考勤组名称", trigger: "blur" },
        ],
        workStartTime: [
          { required: true, message: "请选择上班时间", trigger: "change" },
        ],
        workEndTime: [
          { required: true, message: "请选择下班时间", trigger: "change" },
        ],
        lunchStartTime: [
          { required: true, message: "请选择午休开始时间", trigger: "change" },
        ],
        lunchEndTime: [
          { required: true, message: "请选择午休结束时间", trigger: "change" },
        ],
        areaId: [
          { required: true, message: "请选择打卡区域", trigger: "change" },
        ],
        timeZone: [
          { required: true, message: "请选择考勤时区", trigger: "change" },
        ],
      },
      // 编辑模式
      isEditMode: false,
      // 提示信息
      successMessage: "",
      successMessageVisible: false,
      // 考勤时区
      timeZones: [
        { value: "Asia/Shanghai", label: "东八区(Asia/Shanghai)" },
        { value: "Asia/Tokyo", label: "东九区(Asia/Tokyo)" },
      ],
    };
  },
  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)
      );
    },
    // 午休时间显示
    lunchTimeDisplay() {
      // 实时计算午休时间
      if (
        !this.attendanceGroup.lunchStartTime ||
        !this.attendanceGroup.lunchEndTime
      ) {
        return "0";
      }

      const startTime = this.parseTimeToMinutes(
        this.attendanceGroup.lunchStartTime
      );
      const endTime = this.parseTimeToMinutes(
        this.attendanceGroup.lunchEndTime
      );

      if (endTime <= startTime) {
        return "0";
      }

      const diffMinutes = endTime - startTime;
      const hours = diffMinutes / 60;

      // 以0.5为基准进行向下取整计算
      const result = Math.floor(hours * 2) / 2;
      return result.toString();
    },
  },
  mounted() {
    this.getList();
  },
  watch: {
    // 监听午休时间变化，自动计算午休小时数
    "attendanceGroup.lunchStartTime": {
      handler: function (newVal, oldVal) {
        if (newVal && this.attendanceGroup.lunchEndTime) {
          this.$nextTick(() => {
            this.calculatelunchTime();
          });
        }
      },
      immediate: true,
    },
    "attendanceGroup.lunchEndTime": {
      handler: function (newVal, oldVal) {
        console.log("午休结束时间变化:", newVal);
        if (newVal && this.attendanceGroup.lunchStartTime) {
          this.$nextTick(() => {
            this.calculatelunchTime();
          });
        }
      },
      immediate: true,
    },
  },
  methods: {
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    confirmCopyUser(data) {
      console.log(data);

      this.attendanceGroup.members = data.map((item) => ({
        ...item,
        deptName: item.dept && item.dept.deptName,
      }));

      this.$refs.userCopyRef.visible = false;
    },
    areaName(id) {
      const selected = this.checkInAreas.filter((item) => item.id === id);
      return selected.length > 0 && selected[0].name;
    },
    // 解析时间字符串为分钟数
    parseTimeToMinutes(timeStr) {
      if (!timeStr) return 0;
      const [hours, minutes] = timeStr.split(":").map(Number);
      return hours * 60 + minutes;
    },

    // 计算午休时间
    calculatelunchTime() {
      if (
        !this.attendanceGroup.lunchStartTime ||
        !this.attendanceGroup.lunchEndTime
      ) {
        this.attendanceGroup.lunchTime = 0;
        return;
      }

      const startTime = this.parseTimeToMinutes(
        this.attendanceGroup.lunchStartTime
      );
      const endTime = this.parseTimeToMinutes(
        this.attendanceGroup.lunchEndTime
      );

      if (endTime <= startTime) {
        this.attendanceGroup.lunchTime = 0;
        return;
      }

      const diffMinutes = endTime - startTime;
      const hours = diffMinutes / 60;

      // 以0.5为基准进行向下取整计算
      // 例如：0.7按0.5算，1.7按1.5算
      this.attendanceGroup.lunchTime = Math.floor(hours * 2) / 2;

      // 调试输出
      console.log(
        `午休时间计算: ${this.attendanceGroup.lunchStartTime} - ${this.attendanceGroup.lunchEndTime} = ${hours}小时，计算结果: ${this.attendanceGroup.lunchTime}小时`
      );
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.attendanceGroup = { ...this.attendanceGroupModel };
      // 确保午休时间正确初始化
      this.calculatelunchTime();
      this.open = true;
      this.reset();
    },

    // 编辑区域
    editArea(area) {
      this.open = true;
      // 复制对象，避免直接修改原始数据
      this.attendanceGroup = { ...area };

      // 确保午休时间字段存在
      if (!this.attendanceGroup.lunchStartTime) {
        this.attendanceGroup.lunchStartTime = "12:00";
      }
      if (!this.attendanceGroup.lunchEndTime) {
        this.attendanceGroup.lunchEndTime = "13:00";
      }
      if (this.attendanceGroup.lunchTime === undefined) {
        this.attendanceGroup.lunchTime = 1;
      }

      // 重新计算午休时间
      this.calculatelunchTime();

      this.selectGroup(area.id);
    },

    // 删除
    deleteArea(area) {
      this.$modal
        .confirm('是否确认删除名称为"' + area.name + '"的数据项？')
        .then(function () {
          return del(area.id);
        })
        .then(() => {
          this.getList();
        })
        .catch(() => {});
    },

    // 验证早退浮动范围
    validateEarlyRange(value) {
      if (value > 30) {
        this.attendanceGroup.earlyRange = 30;
        this.$message.warning("早退浮动范围最大为30分钟");
      }
    },

    // 打开员工选择对话框
    openUserSelectionDialog() {
      this.$refs.userCopyRef.visible = true;
      if (this.attendanceGroup.members.length === 0) {
        this.copyUserList = [];
      } else {
        this.copyUserList = this.attendanceGroup.members.map(
          (item) => item.userId
        );
      }
    },

    // 创建新考勤组
    createNewGroup() {
      this.$refs.groupForm.validate((valid) => {
        if (valid) {
          // 计算午休时间
          this.calculatelunchTime();
          // 实际项目中调用API创建
          const newGroup = {
            id: this.attendanceGroup.id,
            name: this.attendanceGroup.name,
            description: this.attendanceGroup.description,
            workDays: this.attendanceGroup.workDays,
            workStartTime: this.attendanceGroup.workStartTime,
            workEndTime: this.attendanceGroup.workEndTime,
            lunchStartTime: this.attendanceGroup.lunchStartTime,
            lunchEndTime: this.attendanceGroup.lunchEndTime,
            lunchTime: this.attendanceGroup.lunchTime,
            allowLate: this.attendanceGroup.allowLate,
            lateRange: this.attendanceGroup.lateRange,
            allowEarly: this.attendanceGroup.allowEarly,
            earlyRange: this.attendanceGroup.earlyRange,
            areaId: this.attendanceGroup.areaId,
            areaName: "",
            members: this.attendanceGroup.members,
            timeZone: this.attendanceGroup.timeZone,
          };
          add(newGroup).then((res) => {
            this.getList();
            this.open = false;
          });
        }
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 处理关闭员工对话框
    handleCloseUserDialog(done) {
      if (this.selectedUsers.length > 0) {
        this.$confirm("确定要取消选择吗？", "提示", {
          type: "warning",
        })
          .then(() => {
            done();
          })
          .catch(() => {
            // 取消关闭
          });
      } else {
        done();
      }
    },

    // 处理员工选择变化
    handleUserSelectionChange(selection) {
      console.log(selection);
      const newList = selection.map((item) => ({
        ...item, // 保留原始字段
        deptName: item.dept.deptName, // 新增字段，
      }));
      this.selectedUsers = newList;
    },

    // 确认选择员工
    confirmUserSelection() {
      if (this.selectedUsers.length === 0) {
        this.$message.warning("请选择员工");
        return;
      }
      const mergedArray = [
        ...this.attendanceGroup.members,
        ...this.selectedUsers.filter(
          (item) =>
            !this.attendanceGroup.members.some(
              (a1) => a1.userId === item.userId
            )
        ),
      ];
      this.attendanceGroup.members = mergedArray;
      this.userSelectionDialogVisible = false;
    },

    getList() {
      queryList(this.queryParams).then((response) => {
        this.attendanceGroups = response.rows;
        this.total = response.total;
        this.loading = false;
        queryArea({ enabled: true }).then((res) => {
          this.checkInAreas = res;
        });
      });
    },

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

      this.isEditMode = false;
      this.selectedGroupId = null;
    },

    // 打开新建考勤组对话框
    openAddGroupDialog() {
      this.resetForm();
      this.showAddGroupModal = true;
    },

    // 保存考勤组
    saveGroup() {
      this.$refs.groupForm.validate((valid) => {
        if (valid) {
          // 查找打卡区域名称
          const area = this.checkInAreas.find(
            (a) => a.id === this.attendanceGroup.areaId
          );
          if (area) {
            this.attendanceGroup.areaName = area.name;
          }

          if (this.isEditMode) {
            // 更新现有考勤组
            const index = this.attendanceGroups.findIndex(
              (g) => g.id === this.attendanceGroup.id
            );
            if (index !== -1) {
              this.attendanceGroups.splice(index, 1, this.attendanceGroup);
            }
            this.$message.success("考勤组更新成功");
          } else {
            // 添加新考勤组
            this.attendanceGroups.push(this.attendanceGroup);
            this.selectedGroupId = this.attendanceGroup.id;
            this.$message.success("考勤组创建成功");
          }

          add(newGroup).then((res) => {
            // console.log(res)
          });

          // 重置表单
          // this.resetForm();
        } else {
          // console.log('表单验证失败');
          return false;
        }
      });
    },

    // 处理迟到开关变化
    handleLateChange(value) {
      if (!value) {
        this.attendanceGroup.lateRange = 0;
      }
    },

    // 处理早退开关变化
    handleEarlyChange(value) {
      if (!value) {
        this.attendanceGroup.earlyRange = 0;
      }
    },

    // 验证迟到浮动范围
    validateLateRange(value) {
      if (value > 30) {
        this.attendanceGroup.lateRange = 30;
        this.$message.warning("迟到浮动范围最大为30分钟");
      }
    },

    // 选择考勤组
    selectGroup(id) {
      this.selectedGroupId = id;
      const group = this.attendanceGroups.find((g) => g.id === id);
      if (group) {
        // 复制考勤组数据
        this.attendanceGroup = { ...group };
        this.isEditMode = true;
      }
    },

    reset() {
      this.attendanceGroup = { ...this.attendanceGroupModel };
      this.isEditMode = false;
      this.selectedGroupId = null;
      this.$nextTick(() => {
        this.$refs.groupForm.resetFields();
      });
    },
  },
  beforeDestroy() {},
};
</script>
