<template>
  <div class="app-container">
    <el-row>
      <el-form
        v-show="showSearch"
        ref="queryForm"
        :model="queryParams"
        size="small"
        :inline="true"
        class="app-container--search"
      >
        <el-form-item label="用户id" 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="njBalanceManageData" @selection-change="handleSelectionChange" >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="员工编号" align="center" prop="userName" />
      <el-table-column label="员工姓名" align="center" prop="nickName" /> 
      <el-table-column  label="所属部门" align="center" prop="deptName" /> 
      <el-table-column  label="年假总额" align="center" prop="annualLeave" /> 
      <el-table-column  label="已使用天数" align="center" prop="usedDay" /> 
      <el-table-column  label="剩余天数" align="center" prop="unusedDay" /> 
      <el-table-column  label="上年结转" align="center" prop="lastYearUnusedDay" /> 
      <el-table-column  label="状态" align="center" prop="isEnable">
        <template slot-scope="scope">
          <span
            v-if="scope.row.isEnable == 0"
            style="
              display: inline-flex;
              align-items: center;
              justify-content: center;
              text-align: center;
            "
          >
            清零
          </span>
          <span
            v-if="scope.row.isEnable == 1"
            style="
              display: inline-flex;
              align-items: center;
              justify-content: center;
              text-align: center;
            "
          >
            有效
          </span>
        </template>  
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  add,
  queryList,
  queryArea,
  del,
  delUser,
  test
} from '@/api/nianjiaguanli/yueguanli'

import index from '@/views/components/daka/index';
import { time } from 'echarts';
export default {
  name: 'yueguanli',
  components: { index },
  dicts: [
    'zs_operation_warn_types',
    'zs_operation_status',
    'zs_operation_compare_status',
    'zs_operation_platform',
    'daka_check_in_status'
  ],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      resultList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 图片快照时间范围
      daterangeWarnTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        nickName: undefined,
      },
      // 表单参数
      form: {},
      // 结果
      warnResult: '',
      // 表单校验
      rules: {
        snapshotUrl: [
          { required: true, message: '图片快照不能为空', trigger: 'blur' }
        ]
      },
      daka_check_in_status: [{label: '正常', value: '0'},{label: '迟到', value: '1'},{label: '缺卡', value: '2'}],
      // 地图相关
      map: null,
      marker: null,
      circle: null,
      mapHeight: '400px',
      baiduMapKey: '你的百度地图API Key', // 替换为你的API Key
      
      // 表单数据
      formData: {
        id: null,
        name: '',
        lng: '116.404', // 默认经度（北京天安门）
        lat: '39.915',  // 默认纬度（北京天安门）
        radius: 500,    // 默认半径500米
        enabled: false
      },
      
      // 区域列表
      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',
        allowLate: false,
        lateRange: 15,
        allowEarly: false,
        earlyRange: 15,
        areaId: null,
        checkInType: 'location',
        members: [],
        areaName: ''
      },
      attendanceGroupModel: {
        id: null,
        name: '',
        description: '',
        workDays: ['mon', 'tue', 'wed', 'thu', 'fri'],
        workStartTime: '09:00',
        workEndTime: '18:00',
        allowLate: false,
        lateRange: 15,
        allowEarly: false,
        earlyRange: 15,
        areaId: null,
        checkInType: 'location',
        members: [],
        areaName: ''
      },
      // 工作日选项
      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' }
        ],
        areaId: [
          { required: true, message: '请选择打卡区域', trigger: 'change' }
        ]
      },
      // 编辑模式
      isEditMode: false,
      // 提示信息
      successMessage: '',
      successMessageVisible: false,
      calculationMethods: [{ value: 1, label: '自然年（每年1月1日统一生成）' },{ value: 2, label: '入职周年' }],
      rule: {
        id: undefined,
        ruleName: '',
        calculationMethod: 1,
        annualLeaveTiers: 5,
        validityPeriod: true,
        allowHalfDay: false,
        applicableRange: true,
        generationCycle: true,
        members:[]
      },

      annualLeaveTierss: [
        { value: 5, label: '入职满一年（5天）' },
        { value: 10, label: '入职满10年（10天）' },
        { value: 15, label: '入职满20年（15天）' },
        { value: 0, label: '默认规则（年假天数 = 入职当年剩余日历天数 / 365 × 5）' }
      ],
      njBalanceManageData: [],
      applicableRangeFlag: false
    };
  },
  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)
      );
    }
  },
  mounted() {
    // 加载模拟数据
    // this.getList();
    // 加载模拟数据
    this.getList();
  },
  methods: {

    // 加载数据
    getList() {
      queryList(this.queryParams).then((response) => {
        console.log(response)
        this.njBalanceManageData = response.rows
        this.total = response.total
        this.loading = false
      })
    },

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

    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
      this.rule = {
        id: undefined,
        ruleName: '',
        calculationMethod: 1,
        annualLeaveTiers: 5,
        validityPeriod: true,
        allowHalfDay: false,
        applicableRange: true,
        generationCycle: true,
        members:[]
      }
    },

    // 创建年假规则
    createNewGroup() {
      add(this.rule).then((res) => {
        console.log(res)
        this.open = false
        this.applicableRangeFlag = false
        this.$message.success(res.msg);
        this.getList()
      })
    },

     // 编辑区域
    editRuleConfig(rule) {
      this.open = true
      // 复制对象，避免直接修改原始数据
      this.rule = { ...rule };
      if(!rule.applicableRange){
        this.applicableRangeFlag = true
      }
    },

    // 删除
    deleteRuleConfig(rule) {
      del(rule).then((res) => {
        this.getList()
      })
    },

    // 打开员工选择对话框
    openUserSelectionDialog() {
      this.userSelectionDialogVisible = true;
      this.selectedUsers = [];
    },

    // 处理适用范围
    handleApplicableRange(value) {
      if(!value){
        this.applicableRangeFlag = true
      }else{
        this.applicableRangeFlag = false
        this.selectedUsers = [];
      }
    },

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


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

        // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

   // 移除员工
    removeMember(member) {
      this.$confirm('确定要移除该员工吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.rule.members = this.rule.members.filter(
          m => m.id !== member.id
        );
        // console.log(member)
        delUser(member.id).then((res) => {
          // console.log(res)
          this.$message.success('用户删除成功！');
          this.getList()
        })
      }).catch(() => {
        // 取消操作
      });
    },

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

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


    
    // 重置表单
    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;
    },

    // 是否允许请假半天
    handleLateChange(value) {
      console.log(value)
    }
  }
}
</script>
<style lang="scss" scoped>
.attendance-group-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 10px;
}

.page-header p {
  color: #606266;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
}

.group-list-card, .group-form-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.slider-value {
  text-align: center;
  margin-top: 10px;
  color: #606266;
}

/* 表单验证错误提示样式 */
.el-form-item__error {
  padding-top: 4px;
}

/* 表格样式优化 */
.el-table {
  border-radius: 4px;
}

.el-table th {
  background-color: #f5f7fa;
}

/* 按钮样式优化 */
.el-button {
  transition: all 0.2s;
}

.el-button:hover {
  transform: translateY(-1px);
}

/* 消息提示样式 */
.el-message {
  top: 80px;
}

/* 考勤组列表样式 */
.group-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px 0;
}

.group-item {
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 4px;
  cursor: pointer;
  background-color: #fff;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
}

.group-item:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.group-item.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.group-name {
  font-weight: 500;
  margin-bottom: 5px;
  color: #303133;
}

.group-desc {
  font-size: 13px;
  color: #606266;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.group-meta {
  font-size: 12px;
  color: #909399;
}

.empty-state {
  text-align: center;
  padding: 30px 0;
  color: #909399;
}

.empty-state i {
  font-size: 36px;
  margin-bottom: 10px;
  display: block;
  color: #dcdfe6;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .group-list-card, .group-form-card {
    width: 100%;
  }
}
.warn-result table {
  width: 100% !important;
}
.warn-result table td a {
  display: none;
}
.warn-result table img {
  width: 100% !important;
}
.warn-result-message {
  .warn-result-text {
    font-size: 14px;
    color: #303133;
    a {
      color: #409eff;
      text-decoration: underline;
    }
  }
  .warn-result-tips {
    font-size: 12px;
    color: #999;
    margin-top: 10px;
  }
}
</style>
<style lang="scss" scoped>
.goods--info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: left;
  .el-link {
    font-size: 14px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  em {
    font-size: 12px;
    color: #999;
    font-style: normal;
  }
}

.attendance-area-config {
  padding: 20px;
  font-family: Arial, sans-serif;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  color: #333;
  margin-bottom: 10px;
}

.page-header p {
  color: #666;
}

.content-wrapper {
  display: flex;
  gap: 20px;
}

.area-list {
  flex: 1;
  min-width: 400px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.list-header h2 {
  margin: 0;
  color: #333;
}

.btn-add {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-add:hover {
  background-color: #3a8ee6;
}

.area-table {
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.area-table table {
  width: 100%;
  border-collapse: collapse;
}

.area-table th,
.area-table td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.area-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

.area-table tr:last-child td {
  border-bottom: none;
}

.area-table tr:hover {
  background-color: #fafafa;
}

.status-enabled {
  display: inline-block;
  padding: 2px 6px;
  background-color: #e6f7ff;
  color: #1890ff;
  border-radius: 3px;
  font-size: 12px;
}

.status-disabled {
  display: inline-block;
  padding: 2px 6px;
  background-color: #f5f5f5;
  color: #999;
  border-radius: 3px;
  font-size: 12px;
}

.btn-edit,
.btn-status,
.btn-delete {
  padding: 5px 10px;
  margin-right: 5px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 12px;
}

.btn-edit {
  background-color: #e6f7ff;
  color: #1890ff;
}

.btn-edit:hover {
  background-color: #d6efff;
}

.btn-status {
  background-color: #f6ffed;
  color: #52c41a;
}

.btn-status:hover {
  background-color: #e8ffd9;
}

.btn-status:disabled {
  background-color: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}

.btn-delete {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.btn-delete:hover {
  background-color: #ffe5e3;
}

.btn-delete:disabled {
  background-color: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}

.empty-state {
  text-align: center;
  padding: 50px 20px;
  color: #999;
}

.empty-state i {
  font-size: 40px;
  margin-bottom: 10px;
  display: block;
}

.map-section {
  flex: 1;
}

.map-section h2 {
  margin-top: 0;
  color: #333;
}

.map-controls {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 15px;
}

.control-group {
  display: flex;
  align-items: center;
  gap: 5px;
  min-width: 220px;
}

.control-group label {
  font-weight: bold;
  min-width: 80px;
}

.control-group input {
  flex: 1;
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.radius-slider {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 10px;
}

.radius-slider input[type="range"] {
  flex: 1;
}

.map {
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 15px;
}

.map-actions {
  display: flex;
  gap: 10px;
}

.btn-clear,
.btn-save {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
  gap: 5px;
}

.btn-clear {
  background-color: #f5f5f5;
  color: #666;
}

.btn-clear:hover {
  background-color: #eee;
}

.btn-save {
  background-color: #409eff;
  color: white;
}

.btn-save:hover {
  background-color: #3a8ee6;
}

.btn-save:disabled {
  background-color: #e6e6e6;
  color: #999;
  cursor: not-allowed;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 4px;
  padding: 20px;
  width: 300px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.modal-content h3 {
  margin-top: 0;
  color: #333;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.btn-cancel,
.btn-confirm {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-cancel {
  background-color: #f5f5f5;
  color: #666;
}

.btn-cancel:hover {
  background-color: #eee;
}

.btn-confirm {
  background-color: #409eff;
  color: white;
}

.btn-confirm:hover {
  background-color: #3a8ee6;
}

/* 响应式设计 */
@media (max-width: 900px) {
  .content-wrapper {
    flex-direction: column;
  }
  
  .area-list,
  .map-section {
    min-width: auto;
  }
}

@media (max-width: 500px) {
  .control-group {
    min-width: 100%;
  }
  
  .area-table th,
  .area-table td {
    padding: 8px 5px;
    font-size: 14px;
  }
  
  .btn-edit,
  .btn-status,
  .btn-delete {
    padding: 4px 6px;
    margin-right: 2px;
  }
}
</style>
