<template>
  <div class="attendance-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <el-icon><Calendar /></el-icon>
        考勤记录管理
      </h2>
<!--      <div class="header-actions">
        <el-button type="primary" :icon="Download" @click="handleExport">导出报表</el-button>
        <el-button :icon="Refresh" circle @click="handleRefresh" />
      </div>-->
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card">
          <div class="stat-icon blue">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.totalEmployees }}</div>
            <div class="stat-label">总人数</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card">
          <div class="stat-icon green">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.presentCount }}</div>
            <div class="stat-label">今日出勤</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card">
          <div class="stat-icon red">
            <el-icon><Close /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.absentCount }}</div>
            <div class="stat-label">今日缺勤</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stat-card">
          <div class="stat-icon orange">
            <el-icon><DataLine /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.attendanceRate }}%</div>
            <div class="stat-label">出勤率</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索栏 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="员工姓名" prop="name">
              <el-input
                  v-model="queryParams.name"
                  placeholder="请输入员工姓名"
                  clearable
                  :prefix-icon="Search"
                  @keyup.enter="handleQuery"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="部门" prop="department">
              <el-select
                  v-model="queryParams.department"
                  placeholder="请选择部门"
                  clearable
                  style="width: 100%"
              >
                <el-option label="全部部门" value="" />
                <el-option v-for="dept in departments" :key="dept" :label="dept" :value="dept" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="考勤状态" prop="attendanceStatus">
              <el-select
                  v-model="queryParams.attendanceStatus"
                  placeholder="请选择状态"
                  clearable
                  style="width: 100%"
              >
                <el-option label="全部状态" value="" />
                <el-option label="出勤" value="Present">
                  <span style="display: flex; align-items: center;">
                    <el-tag type="success" size="small" style="margin-right: 8px">出勤</el-tag>
                  </span>
                </el-option>
                <el-option label="缺勤" value="Absent">
                  <span style="display: flex; align-items: center;">
                    <el-tag type="danger" size="small" style="margin-right: 8px">缺勤</el-tag>
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="日期范围" prop="dateRange">
              <el-date-picker
                  v-model="queryParams.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :shortcuts="dateShortcuts"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right;">
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
              <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
<!--              <el-button :icon="Filter" @click="showAdvanced = !showAdvanced">
                {{ showAdvanced ? '收起' : '高级筛选' }}
              </el-button>-->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <div class="table-header">
        <span class="table-title">考勤记录列表</span>
        <div class="table-tools">
          <el-tooltip content="刷新数据" placement="top">
            <el-button :icon="Refresh" circle size="small" @click="getList" />
          </el-tooltip>
          <el-tooltip content="列设置" placement="top">
            <el-button :icon="Setting" circle size="small" @click="showColumnSetting = true" />
          </el-tooltip>
        </div>
      </div>

      <el-table
          v-loading="loading"
          :data="attendanceRecords"
          border
          stripe
          highlight-current-row
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" type="index" align="center" width="60">
          <template #default="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="员工信息" align="left" min-width="200">
          <template #default="scope">
            <div class="employee-info">
              <el-avatar :size="32" :src="scope.row.avatar || defaultAvatar">
                {{ scope.row.name.charAt(0) }}
              </el-avatar>
              <div class="employee-details">
                <div class="employee-name">{{ scope.row.name }}</div>
                <div class="employee-dept">{{ scope.row.department }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="访问位置" align="center" prop="accessLocation" min-width="120">
          <template #default="scope">
            <el-tag size="small" type="info">{{ scope.row.accessLocation }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="访问时间" align="center" min-width="180" sortable>
          <template #default="scope">
            <div class="time-info">
              <el-icon><Clock /></el-icon>
              {{ formatDateTime(scope.row.accessTime) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="访问结果" align="center" prop="accessResult" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.accessResult === '成功' ? 'success' : 'warning'" size="small">
              {{ scope.row.accessResult }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="考勤状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.attendanceStatus)" effect="dark">
              <el-icon v-if="scope.row.attendanceStatus === 'Present'"><Check /></el-icon>
              <el-icon v-else><Close /></el-icon>
              {{ scope.row.attendanceStatus === 'Present' ? '出勤' : '缺勤' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="相关事件" align="center" prop="relatedEvent" min-width="150" show-overflow-tooltip />
        <el-table-column label="日访问次数" align="center" prop="dailyAccessCount" width="120">
          <template #default="scope">
            <div class="access-count-wrapper">
              <span class="access-count">{{ scope.row.dailyAccessCount }}</span>
              <span class="access-unit">次</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="scope">
            <el-button link type="primary" :icon="View" @click="handleView(scope.row)">详情</el-button>
            <el-button link type="warning" :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog" title="考勤详情" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="员工姓名">{{ currentRecord.name }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{ currentRecord.department }}</el-descriptions-item>
        <el-descriptions-item label="访问时间">{{ formatDateTime(currentRecord.accessTime) }}</el-descriptions-item>
        <el-descriptions-item label="访问位置">{{ currentRecord.accessLocation }}</el-descriptions-item>
        <el-descriptions-item label="考勤状态">
          <el-tag :type="getStatusType(currentRecord.attendanceStatus)">
            {{ currentRecord.attendanceStatus === 'Present' ? '出勤' : '缺勤' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="访问结果">{{ currentRecord.accessResult }}</el-descriptions-item>
        <el-descriptions-item label="日访问次数" :span="2">{{ currentRecord.dailyAccessCount }}</el-descriptions-item>
        <el-descriptions-item label="相关事件" :span="2">{{ currentRecord.relatedEvent || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup name="AttendanceRecords">
import { ref, reactive, computed, onMounted } from "vue";
import { listAccessControlAttendance } from "@/api/accessControl/accessControl";
import { ElMessage, ElMessageBox } from 'element-plus';
// 导入图标
import {
  Calendar,
  Download,
  Refresh,
  User,
  Check,
  Close,
  DataLine,
  Search,
  Filter,
  Setting,
  Clock,
  View,
  Edit
} from '@element-plus/icons-vue';

// 响应式变量
const queryRef = ref(null);
const attendanceRecords = ref([]);
const loading = ref(false);
const showSearch = ref(true);
const showAdvanced = ref(false);
const total = ref(0);
const selectedRows = ref([]);
const detailDialog = ref(false);
const currentRecord = ref({});
const showColumnSetting = ref(false);
const defaultAvatar = ref('/default-avatar.png');

// 部门列表（实际应从后端获取）
const departments = ref(['技术部', '市场部', '人事部', '财务部', '运营部']);

// 统计数据
const statistics = reactive({
  totalEmployees: 0,
  presentCount: 0,
  absentCount: 0,
  attendanceRate: 0
});

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  department: '',
  attendanceStatus: '',
  dateRange: [],
  interfaceName: "考勤记录"
});

// 日期快捷选项
const dateShortcuts = [
  {
    text: '今天',
    value: () => {
      const end = new Date();
      const start = new Date();
      return [start, end];
    },
  },
  {
    text: '昨天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 1);
      end.setDate(end.getDate() - 1);
      return [start, end];
    },
  },
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    },
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    },
  }
];

// 获取考勤记录列表
const getList = async () => {
  try {
    loading.value = true;
    const params = { ...queryParams };
    if (params.dateRange && params.dateRange.length === 2) {
      params.startDate = params.dateRange[0];
      params.endDate = params.dateRange[1];
    }
    const response = await listAccessControlAttendance(params);
    attendanceRecords.value = response.data.list || [];
    total.value = response.data.total || 0;
    updateStatistics();
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取考勤记录失败');
  } finally {
    loading.value = false;
  }
};

// 更新统计数据
const updateStatistics = () => {
  const records = attendanceRecords.value;
  statistics.totalEmployees = new Set(records.map(r => r.name)).size;
  statistics.presentCount = records.filter(r => r.attendanceStatus === 'Present').length;
  statistics.absentCount = records.filter(r => r.attendanceStatus === 'Absent').length;
  statistics.attendanceRate = statistics.totalEmployees > 0
      ? Math.round((statistics.presentCount / statistics.totalEmployees) * 100)
      : 0;
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryRef.value?.resetFields();
  queryParams.dateRange = [];
  queryParams.department = '';
  handleQuery();
};

// 刷新数据
const handleRefresh = () => {
  getList();
  ElMessage.success('数据已刷新');
};

// 导出报表
const handleExport = async () => {
  try {
    await ElMessageBox.confirm('确定要导出当前筛选条件下的考勤记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    });

    loading.value = true;
    // 这里调用导出API
    // await exportAttendanceRecords(queryParams);
    ElMessage.success('导出成功');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('导出失败');
    }
  } finally {
    loading.value = false;
  }
};

// 查看详情
const handleView = (row) => {
  currentRecord.value = { ...row };
  detailDialog.value = true;
};

// 编辑记录
const handleEdit = (row) => {
  ElMessage.info('编辑功能开发中...');
  // 实现编辑逻辑
};

// 多选处理
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-';
  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    'Present': 'success',
    'Absent': 'danger'
  };
  return statusMap[status] || 'info';
};

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  if (row.attendanceStatus === 'Absent') {
    return 'absent-row';
  }
  return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.attendance-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin: 0;
      display: flex;
      align-items: center;

      .el-icon {
        margin-right: 8px;
        color: #409eff;
      }
    }

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

  // 统计卡片样式
  .statistics-cards {
    margin-bottom: 20px;

    .stat-card {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      display: flex;
      align-items: center;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      transition: all 0.3s;
      margin-bottom: 10px;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
      }

      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;

        .el-icon {
          font-size: 28px;
        }

        &.blue {
          background: #e6f2ff;
          color: #409eff;
        }

        &.green {
          background: #e8f5e9;
          color: #67c23a;
        }

        &.red {
          background: #fef0f0;
          color: #f56c6c;
        }

        &.orange {
          background: #fdf6ec;
          color: #e6a23c;
        }
      }

      .stat-content {
        flex: 1;

        .stat-value {
          font-size: 28px;
          font-weight: 600;
          color: #303133;
          line-height: 1;
          margin-bottom: 8px;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }

  // 搜索卡片样式
  .search-card {
    margin-bottom: 20px;

    :deep(.el-card__body) {
      padding: 20px 20px 0;
    }

    .el-form-item {
      margin-bottom: 20px;
      width: 100%;
    }
  }

  // 表格卡片样式
  .table-card {
    :deep(.el-card__body) {
      padding: 0;
    }

    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      border-bottom: 1px solid #ebeef5;

      .table-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }

      .table-tools {
        display: flex;
        gap: 8px;
      }
    }

    .el-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #303133;
          font-weight: 600;
        }
      }

      :deep(.even-row) {
        background-color: #fafafa;
      }

      :deep(.absent-row) {
        background-color: #fef0f0;
      }
    }

    .employee-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .employee-details {
        text-align: left;

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

        .employee-dept {
          font-size: 12px;
          color: #909399;
        }
      }
    }

    .time-info {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;
      color: #606266;

      .el-icon {
        color: #909399;
      }
    }

    // 日访问次数样式
    .access-count-wrapper {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;

      .access-count {
        font-weight: 600;
        color: #409eff;
        font-size: 16px;
      }

      .access-unit {
        color: #909399;
        font-size: 12px;
      }
    }
  }

  // 分页器样式
  :deep(.pagination-container) {
    padding: 20px;
    background: #fff;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .attendance-container {
    padding: 10px;

    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;

      .header-actions {
        width: 100%;
        justify-content: flex-end;
      }
    }

    .statistics-cards {
      .el-col {
        margin-bottom: 10px;
      }
    }

    .search-card {
      :deep(.el-form) {
        .el-form-item {
          display: block;
          margin-bottom: 16px;
        }
      }
    }
  }
}

// 动画效果
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.stat-card {
  animation: fadeIn 0.5s ease-out;

  &:nth-child(1) { animation-delay: 0.1s; }
  &:nth-child(2) { animation-delay: 0.2s; }
  &:nth-child(3) { animation-delay: 0.3s; }
  &:nth-child(4) { animation-delay: 0.4s; }
}

// 标签内图标样式
:deep(.el-tag) {
  .el-icon {
    margin-right: 4px;
  }
}
</style>
