<template>
  <div class="ranking-board-page">
    <!-- 右上角倒计时显示 -->
    <div class="countdown-display">
      <!-- <el-card shadow="never" class="countdown-card"> -->
      <el-button size="default" type="primary">
        <div class="countdown-content">
          <!-- <el-icon class="countdown-icon"><Timer /></el-icon> -->
          <span>{{ countdownSeconds }}秒后刷新</span>
        </div>
      </el-button>
        
      <!-- </el-card> -->
    </div>
    <!-- 赛事名称标题 -->
    <div class="event-title">
      <h2>{{defaultEventInfo ? defaultEventInfo.eventName : '赛事排行榜'}}</h2>
      <p>随时掌握运动会情况</p>
    </div>
    <el-row :gutter="20" class="ranking-row">
      <el-col :span="12">
        <el-card shadow="hover" class="ranking-card">
          <template #header>
            <div class="card-header header-one">
              <div class="personal-ranking-header">
                <!-- 标题单独一行，居中对齐 -->
                <div class="header-title">
                  <span>个人项目排行榜</span>
                </div>
                <!-- 控件在一行，均匀分布 -->
                <div class="header-controls">
                  <el-select
                    v-model="selectedProjectId"
                    placeholder="选择项目"
                    size="small"
                    @change="handleProjectChange"
                    class="project-select"
                    filterable
                    style="width: 150px;"
                  >
                    <el-option
                      v-for="project in personalProjectOptions"
                      :key="project.projectId"
                      :label="project.projectName"
                      :value="project.projectId"
                    />
                  </el-select>
                  <div class="display-count-control">
                    <span class="control-label">前</span>
                    <el-input-number
                      v-model="personalDisplayCount"
                      :min="1"
                      :max="100"
                      size="small"
                      controls-position="right"
                      style="width: 80px; margin: 0 5px;"
                      @change="handlePersonalCountChange"
                    />
                    <span class="control-label">名</span>
                  </div>
                  <el-button
                    type="success"
                    size="small"
                    :icon="Download"
                    @click="exportPersonalRanking"
                    class="export-btn"
                  >
                    导出
                  </el-button>
                  <el-button
                    type="warning"
                    size="small"
                    :icon="Printer"
                    @click="printPersonalRanking"
                    class="print-btn"
                  >
                    打印
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    :icon="Refresh"
                    :loading="personalRefreshing"
                    @click="refreshPersonalRanking"
                    class="refresh-btn"
                  >
                    刷新
                  </el-button>
                </div>
              </div>
            </div>
          </template>
          <div class="ranking-list ranking-list-full">
            <!-- 添加标题行 -->
            <div class="ranking-header">
              <div class="header-content">
                <span class="header-rank">名次</span>
                <span class="header-name">姓名</span>
                <span class="header-team">队伍名称</span>
                <span class="header-project">项目</span>
                <span class="header-score">成绩</span>
              </div>
            </div>
            <div v-for="(item, index) in displayedAthleteList" :key="index" class="ranking-item">
              <div class="item-content">
                <span class="item-rank">{{ getRankDisplay(item, index, athleteScoreList) }}</span>
                <span class="item-name">{{ item.name || item.athleteName }}</span>
                <span class="item-team">{{ item.teamName }}</span>
                <span class="item-project-name">{{ selectedProjectName }}</span>
                <span class="item-score">
                  {{ item.score || '-' }}
                  <span v-if="item.score && item.score !== '-' && item.score !== '无成绩'" class="score-unit">{{ personalUnit }}</span>
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="ranking-card">
          <template #header>
            <div class="card-header header-three">
              <div class="team-ranking-header">
                <!-- 标题单独一行，居中对齐 -->
                <div class="header-title">
                  <span>团队项目排行榜</span>
                </div>
                <!-- 控件在一行，均匀分布 -->
                <div class="header-controls">
                  <el-select
                    v-model="selectedTeamProjectId"
                    placeholder="选择项目"
                    size="small"
                    @change="handleTeamProjectChange"
                    filterable
                    class="project-select"
                    style="width: 150px;"
                  >
                    <el-option
                      v-for="project in teamProjectOptions"
                      :key="project.projectId"
                      :label="project.projectName"
                      :value="project.projectId"
                    />
                  </el-select>
                  <el-select 
                    v-model="selectedRankGroupId" 
                    placeholder="选择分组" 
                    clearable 
                    filterable
                    size="small" 
                    @change="handleRankGroupChange"
                    class="group-select"
                  >
                    <el-option label="全部队伍" :value="ALL_GROUPS_VALUE"></el-option>
                    <el-option
                      v-for="group in rankGroupOptions"
                      :key="group.rgId"
                      :label="group.rgName"
                      :value="group.rgId"
                    />
                  </el-select>
                  <div class="display-count-control">
                    <span class="control-label">前</span>
                    <el-input-number
                      v-model="teamDisplayCount"
                      :min="1"
                      :max="100"
                      size="small"
                      controls-position="right"
                      style="width: 80px; margin: 0 5px;"
                      @change="handleTeamCountChange"
                    />
                    <span class="control-label">名</span>
                  </div>
                  <el-button
                    type="success"
                    size="small"
                    :icon="Download"
                    @click="exportTeamRanking"
                    class="export-btn"
                  >
                    导出
                  </el-button>
                  <el-button
                    type="warning"
                    size="small"
                    :icon="Printer"
                    @click="printTeamRanking"
                    class="print-btn"
                  >
                    打印
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    :icon="Refresh"
                    :loading="teamRefreshing"
                    @click="refreshTeamRanking"
                    class="refresh-btn"
                  >
                    刷新
                  </el-button>
                </div>
              </div>
            </div>
          </template>
          <div class="ranking-list ranking-list-full">
            <!-- 添加标题行 -->
            <div class="ranking-header">
              <div class="header-content">
                <span class="header-rank">名次</span>
                <span class="header-project">项目</span>
                <span class="header-team-name">队伍名称</span>
                <span class="header-group">组别</span>
                <span class="header-score">成绩</span>
              </div>
            </div>
            <div v-for="(item, index) in displayedTeamList" :key="index" class="ranking-item">
              <div class="item-content">
                <span class="item-rank">{{ getRankDisplay(item, index, filteredTeamScores) }}</span>
                <span class="item-project-name">{{ selectedTeamProjectName }}</span>
                <span class="item-team-name">{{ item.name || item.teamName }}</span>
                <span class="item-group">{{ item.rgName || '-' }}</span>
                <span class="item-score">
                  {{ item.score || '-' }}
                  <span v-if="item.score && item.score !== '-' && item.score !== '无成绩'" class="score-unit">{{ teamUnit }}</span>
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, getCurrentInstance, toRefs } from 'vue';
import { getProjectScoreData, getRankingBoardData, updateBonusData, exportBonusExcel } from '@/api/system/gameScore';
import { listGameEventProject } from '@/api/system/gameEventProject';
import { getProjectProgress } from '@/api/system/gameEvent/projectProgress';
import { ProjectProgressVo, GroupProgressVo } from '@/api/system/gameEvent/types';
import { useGameEventStore } from '@/store/modules/gameEvent';
import { storeToRefs } from 'pinia';
import { listRankGroup } from '@/api/system/rankGroup'; 
import { RankGroupVO } from '@/api/system/rankGroup/types'; 
import { Refresh, Download, Printer } from '@element-plus/icons-vue';
import { saveAs } from 'file-saver';

// 定义队伍积分排行榜的数据结构
interface TeamScore {
  rgId: string | number;
  teamId: string | number;
  teamName: string;
  score: number;
  rank: number;
  rgName?: string;
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { game_project_type } = toRefs<any>(proxy?.useDict('game_project_type'));

// const route = useRoute();
// const eventId = route.params.eventId as string;

//从pinia中获取默认赛事信息
const gameEventStore = useGameEventStore();
const { defaultEventInfo } = storeToRefs(gameEventStore);

const athleteScoreList = ref([]);

const completedTasks = ref(0);
const totalTasks = ref(0);
const progressPercentage = computed(() => totalTasks.value > 0 ? Math.round((completedTasks.value / totalTasks.value) * 100) : 0);

const projectProgress = ref<ProjectProgressVo[]>([]);

const teamScores = ref<TeamScore[]>([]);
const filteredTeamScores = ref<any[]>([]); // 用于显示筛选后的队伍积分

// 获取当前项目的单位
const getProjectUnit = (project: any) => {
  if (!project) return '';
  if (project.countUnit) return project.countUnit;
  
  // 自动兜底逻辑
  const rule = String(project.scoreRule);
  if (rule === '1') return '秒'; // 计时类
  if (rule === '2' || rule === '3' || rule === '6') return '米'; // 距离/远度/高度类
  
  // 备选方案：按项目名称关键字识别
  if (project.projectName?.includes('计时')) return '秒';
  if (project.projectName?.includes('米') || project.projectName?.includes('远') || project.projectName?.includes('高')) return '米';
  
  return '';
};

const personalUnit = computed(() => {
  const project = personalProjectOptions.value.find(p => p.projectId == selectedProjectId.value);
  return getProjectUnit(project);
});

const teamUnit = computed(() => {
  const project = teamProjectOptions.value.find(p => p.projectId == selectedTeamProjectId.value);
  return getProjectUnit(project);
});

const ALL_GROUPS_VALUE = 'all';
// 分组相关数据
const rankGroupOptions = ref<RankGroupVO[]>([]);
const selectedRankGroupId = ref<string | number | null>(null);

const personalProjectOptions = ref<any[]>([]);
const selectedProjectId = ref<string | number | null>(null);

const selectedProjectName = computed(() => {
  const project = personalProjectOptions.value.find(p => p.projectId === selectedProjectId.value);
  return project ? project.projectName : '-';
});

// 团队项目选择相关
const teamProjectOptions = ref<any[]>([]);
const selectedTeamProjectId = ref<string | number | null>(null);

const selectedTeamProjectName = computed(() => {
  const project = teamProjectOptions.value.find(p => p.projectId === selectedTeamProjectId.value);
  return project ? project.projectName : '-';
});

// 显示数量控制
const personalDisplayCount = ref(10); // 个人排行榜显示数量，默认10
const teamDisplayCount = ref(10); // 团队排行榜显示数量，默认10

// 添加刷新状态控制
const personalRefreshing = ref(false); // 个人排行榜刷新状态
const teamRefreshing = ref(false); // 团队排行榜刷新状态

// 自动刷新相关
const autoRefreshInterval = ref<NodeJS.Timeout | null>(null);
const autoRefreshSeconds = ref(300); // 默认300秒自动刷新
// 添加倒计时相关状态
const countdownSeconds = ref(0); // 倒计时秒数
const countdownInterval = ref<NodeJS.Timeout | null>(null); // 倒计时定时器

// 启动倒计时
const startCountdown = () => {
  stopCountdown();
  countdownSeconds.value = autoRefreshSeconds.value;
  
  countdownInterval.value = setInterval(() => {
    countdownSeconds.value--;
    
    if (countdownSeconds.value <= 0) {
      refreshAllData();
      countdownSeconds.value = autoRefreshSeconds.value;
    }
  }, 1000);
};

// 停止倒计时
const stopCountdown = () => {
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value);
    countdownInterval.value = null;
  }
  countdownSeconds.value = 0;
};

// 根据显示数量过滤数据
const displayedAthleteList = computed(() => {
  return athleteScoreList.value.slice(0, personalDisplayCount.value);
});

const displayedTeamList = computed(() => {
  return filteredTeamScores.value.slice(0, teamDisplayCount.value);
});

// 处理个人排行榜显示数量变化
const handlePersonalCountChange = (value: number) => {
  personalDisplayCount.value = value;
};

// 处理团队排行榜显示数量变化
const handleTeamCountChange = (value: number) => {
  teamDisplayCount.value = value;
};

// 获取团队项目排行榜数据
const loadTeamProjectScores = async () => {
  if (!selectedTeamProjectId.value) return;
  const res = await getRankingBoardData({
    eventId: defaultEventInfo.value.eventId,
    projectId: selectedTeamProjectId.value,
    classification: '1',
    rgId: selectedRankGroupId.value || undefined
  });
  
  // 直接使用后端返回的有序且带排名的列表
  const teamScoreList = res.data || [];

  teamScores.value = teamScoreList.map(item => ({
    ...item,
    classification: '1'
  }));
  
  // 更新过滤后的显示列表（由于后端已按分组过滤，这里直接同步）
  filteredTeamScores.value = teamScores.value;
};

// 处理分组筛选变化
const handleRankGroupChange = (rgId: string | number | null | undefined) => {
  // 分组筛选直接触发后端查询，不再在前端过滤
  loadTeamProjectScores();
};

// 从扁平列表中获取某个节点下的所有子孙ID（用于前端筛选）
const getFlatIds = (rgId: string | number) => {
  const ids: (string | number)[] = [rgId];
  const targetIdStr = String(rgId);
  // 遍历扁平列表，通过 ancestors 祖级路径识别所有子孙节点
  rankGroupOptions.value.forEach(item => {
    if (item.ancestors && item.ancestors.split(',').includes(targetIdStr)) {
      ids.push(item.rgId);
    }
  });
  return ids;
};

// 获取分组选项
const loadRankGroupOptions = async () => {
  try {
    const res = await listRankGroup({
      eventId: defaultEventInfo.value.eventId,
      status: '0'
    });
    rankGroupOptions.value = res.rows;
  } catch (error) {
    console.error('获取分组列表失败:', error);
  }
};

// 获取项目选项（个人和团队）
const loadProjectOptions = async () => {
  try {
    const res = await listGameEventProject({
      eventId: defaultEventInfo.value.eventId,
      orderByColumn: 'createTime',
      isAsc: 'desc',
      pageNum: 1,
      pageSize: 1000
    });
    const allProjects = res.rows || [];
    
    // 个人项目过滤
    personalProjectOptions.value = allProjects.filter(p => p.classification === '0');
    if (personalProjectOptions.value.length > 0 && !selectedProjectId.value) {
      selectedProjectId.value = personalProjectOptions.value[0].projectId;
    }
    
    // 团队项目过滤
    teamProjectOptions.value = allProjects.filter(p => p.classification === '1');
    if (teamProjectOptions.value.length > 0 && !selectedTeamProjectId.value) {
      selectedTeamProjectId.value = teamProjectOptions.value[0].projectId;
    }
  } catch (error) {
    console.error('获取项目列表失败:', error);
  }
};

// 处理项目切换
const handleProjectChange = (projectId: string | number) => {
  selectedProjectId.value = projectId;
  refreshPersonalRanking();
};

// 处理团队项目切换
const handleTeamProjectChange = (projectId: string | number) => {
  selectedTeamProjectId.value = projectId;
  refreshTeamRanking();
};

// 加载项目进度信息
const loadProjectProgress = async () => {
  try {
    const res = await getProjectProgress(defaultEventInfo.value.eventId);
    projectProgress.value = res.data || [];
    
    // 计算已完成和总任务数
    let completed = 0;
    let total = 0;
    
    projectProgress.value.forEach(project => {
      if (project.groups && project.groups.length > 0) {
        // 有组别的项目，统计组别
        project.groups.forEach(group => {
          total++;
          if (group.status === '2') { // 已完成
            completed++;
          }
        });
      } else {
        // 没有组别的项目，直接统计项目
        total++;
        if (project.status === '2') { // 已完成
          completed++;
        }
      }
    });
    
    completedTasks.value = completed;
    totalTasks.value = total;
    
    // 前端也可以做一次排序确保，虽然后端已经排序了
    // 按完整时间排序（项目时间或最早组别时间）
    projectProgress.value.sort((a, b) => {
      const getEarliestTime = (project: ProjectProgressVo) => {
        if (project.groups && project.groups.length > 0) {
          // 有组别，找到最早的组别时间
          const groupTimes = project.groups
            .map(g => g.beginTime ? new Date(g.beginTime).getTime() : 0)
            .filter(time => time > 0);
          if (groupTimes.length > 0) {
            return Math.min(...groupTimes);
          }
        }
        // 没有组别或组别时间无效，使用项目时间
        return project.startTime ? new Date(project.startTime).getTime() : 0;
      };
      
      const aTime = getEarliestTime(a);
      const bTime = getEarliestTime(b);
      
      return aTime - bTime;
    });
  } catch (error) {
    console.error('加载项目进度失败:', error);
  }
};


// 获取排名显示文本
const getRankDisplay = (item: any, index: number, list: any[]) => {
  if (item.rank === '-' || item.rank === undefined || item.rank === null || item.rank === 0 || item.rank === '0') {
    return '';
  }
  return `第${item.rank}名`;
};

// 刷新个人排行榜数据
const refreshPersonalRanking = async () => {
  if (!selectedProjectId.value) return;
  personalRefreshing.value = true;
  try {
    const res = await getRankingBoardData({
      eventId: defaultEventInfo.value.eventId,
      projectId: selectedProjectId.value,
      classification: '0'
    });
    
    // 直接使用后端返回的成品数据
    athleteScoreList.value = (res.data || []).map(item => ({ ...item, classification: '0' }));
    
    // 手动刷新时重置倒计时
    startCountdown();
    // 显示成功消息
    ElMessage.success('个人排行榜数据已刷新');
  } catch (error) {
    ElMessage.error('刷新个人排行榜失败');
  } finally {
    personalRefreshing.value = false;
  }
};

// 导出个人排行榜
const exportPersonalRanking = async () => {
  if (athleteScoreList.value.length === 0) {
    ElMessage.warning('没有可导出的数据');
    return;
  }

  try {
    const { value } = await ElMessageBox.prompt('请输入导出前几名（不输入则导出全部）', '导出确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^\d*$/,
      inputErrorMessage: '请输入数字'
    });

    const count = value ? parseInt(value) : athleteScoreList.value.length;
    const exportData = athleteScoreList.value.slice(0, count);

    const columns = ['排名', '姓名', '队伍名称', '项目', '成绩'];
    const csvContent = exportData.map((item, index) => {
      const rank = getRankDisplay(item, index, athleteScoreList.value);
      const name = item.name || item.athleteName || '';
      const team = item.teamName || '';
      const project = selectedProjectName.value;
      // 在成绩前加 \t 防止 Excel 自动转换格式
      const scoreValue = item.individualPerformance || item.score || item.totalScore || '';
      const score = `\t${scoreValue}`;
      return [rank, name, team, project, score].join(',');
    });

    const blob = new Blob(['\ufeff' + columns.join(',') + '\n' + csvContent.join('\n')], { type: 'text/csv;charset=utf-8;' });
    saveAs(blob, `${selectedProjectName.value}_个人排行榜.csv`);
  } catch (e) {
    // 点击取消不执行
  }
};

// 打印个人排行榜
const printPersonalRanking = async () => {
  if (athleteScoreList.value.length === 0) {
    ElMessage.warning('没有可打印的数据');
    return;
  }

  try {
    const { value } = await ElMessageBox.prompt('请输入打印前几名（不输入则打印全部）', '打印确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^\d*$/,
      inputErrorMessage: '请输入数字'
    });

    const count = value ? parseInt(value) : athleteScoreList.value.length;
    const printData = athleteScoreList.value.slice(0, count);

    const title = `${selectedProjectName.value} - 个人排行榜`;
    const columns = ['排名', '姓名', '队伍名称', '项目', '成绩'];
    const rows = printData.map((item, index) => {
      const rank = getRankDisplay(item, index, athleteScoreList.value);
      const name = item.name || item.athleteName || '';
      const team = item.teamName || '';
      const project = selectedProjectName.value;
      const score = item.individualPerformance || item.score || item.totalScore || '';
      return [rank, name, team, project, score];
    });

    generatePrintPage(title, columns, rows);
  } catch (e) {
    // 取消
  }
};

// 导出团队排行榜
const exportTeamRanking = async () => {
  if (filteredTeamScores.value.length === 0) {
    ElMessage.warning('没有可导出的数据');
    return;
  }

  try {
    const { value } = await ElMessageBox.prompt('请输入导出前几名（不输入则导出全部）', '导出确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^\d*$/,
      inputErrorMessage: '请输入数字'
    });

    const count = value ? parseInt(value) : filteredTeamScores.value.length;
    const exportData = filteredTeamScores.value.slice(0, count);

    const columns = ['排名', '项目', '队伍名称', '组别', '成绩'];
    const csvContent = exportData.map((item, index) => {
      const rank = getRankDisplay(item, index, filteredTeamScores.value);
      const project = selectedTeamProjectName.value;
      const teamName = item.name || item.teamName || '';
      const groupName = item.rgName || '-';
      const scoreValue = item.teamPerformance || item.score || item.totalScore || '';
      const score = `\t${scoreValue}`;
      return [rank, project, teamName, groupName, score].join(',');
    });

    const blob = new Blob(['\ufeff' + columns.join(',') + '\n' + csvContent.join('\n')], { type: 'text/csv;charset=utf-8;' });
    saveAs(blob, `${selectedTeamProjectName.value}_团队排行榜.csv`);
  } catch (e) {
    // 取消
  }
};

// 打印团队排行榜
const printTeamRanking = async () => {
  if (filteredTeamScores.value.length === 0) {
    ElMessage.warning('没有可打印的数据');
    return;
  }

  try {
    const { value } = await ElMessageBox.prompt('请输入打印前几名（不输入则打印全部）', '打印确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^\d*$/,
      inputErrorMessage: '请输入数字'
    });

    const count = value ? parseInt(value) : filteredTeamScores.value.length;
    const printData = filteredTeamScores.value.slice(0, count);

    const title = `${selectedTeamProjectName.value} - 团队排行榜`;
    const columns = ['排名', '项目', '队伍名称', '组别', '成绩'];
    const rows = printData.map((item, index) => {
      const rank = getRankDisplay(item, index, filteredTeamScores.value);
      const project = selectedTeamProjectName.value;
      const teamName = item.name || item.teamName || '';
      const groupName = item.rgName || '-';
      const score = item.teamPerformance || item.score || item.totalScore || '';
      return [rank, project, teamName, groupName, score];
    });

    generatePrintPage(title, columns, rows);
  } catch (e) {
    // 取消
  }
};

// 通用打印页面生成函数
const generatePrintPage = (title, columns, rows) => {
  const printWindow = window.open('', '_blank');
  if (!printWindow) return;

  const tableHtml = `
    <table border="1" style="width:100%; border-collapse: collapse; margin-top: 20px;">
      <thead>
        <tr style="background-color: #f5f7fa;">
          ${columns.map(col => `<th style="padding: 10px; border: 1px solid #ddd;">${col}</th>`).join('')}
        </tr>
      </thead>
      <tbody>
        ${rows.map(row => `
          <tr>
            ${row.map(cell => `<td style="padding: 10px; border: 1px solid #ddd; text-align: center;">${cell}</td>`).join('')}
          </tr>
        `).join('')}
      </tbody>
    </table>
  `;

  printWindow.document.write(`
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>${title}</title>
        <style>
          body { font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif; color: #333; padding: 20px; }
          h1 { text-align: center; color: #303133; margin-bottom: 30px; }
          .print-time { text-align: right; color: #909399; font-size: 14px; margin-bottom: 10px; }
          @media print {
            @page { margin: 1cm; }
            button { display: none; }
          }
        </style>
      </head>
      <body>
        <h1>${title}</h1>
        <div class="print-time">打印时间：${new Date().toLocaleString()}</div>
        ${tableHtml}
        <script>
          window.onload = function() {
            setTimeout(function() {
              window.print();
              // window.close(); // 打印完自动关闭可选
            }, 500);
          };
        <\/script>
      </body>
    </html>
  `);
  printWindow.document.close();
};

// 刷新团队排行榜数据
const refreshTeamRanking = async () => {
  teamRefreshing.value = true;
  try {
    // 重新加载团队项目排行榜
    await loadTeamProjectScores();
    // 手动刷新时重置倒计时
    startCountdown();
    
    // 显示成功消息
    ElMessage.success('团队排行榜数据已刷新');
  } catch (error) {
    console.error('刷新团队排行榜失败:', error);
    ElMessage.error('刷新团队排行榜失败');
  } finally {
    teamRefreshing.value = false;
  }
};

// 刷新所有数据
const refreshAllData = async () => {
  personalRefreshing.value = true;
  teamRefreshing.value = true;
  
  try {
    // 并行刷新所有数据
    await Promise.all([
      refreshPersonalRanking(),
      refreshTeamRanking()
    ]);
    // ElMessage.success('所有数据已刷新');
  } catch (error) {
    ElMessage.error('刷新数据失败');
  } finally {
    personalRefreshing.value = false;
    teamRefreshing.value = false;
  }
};

// 开启自动刷新
const startAutoRefresh = () => {
  // 开启倒计时，倒计时结束会自动触发刷新
  startCountdown();
};

// 组件卸载时清理定时器
onUnmounted(() => {
  if (autoRefreshInterval.value) {
    clearInterval(autoRefreshInterval.value);
  }
  // 停止倒计时
  stopCountdown();
});

onMounted(async () => {
  try{
    startAutoRefresh();
    // await gameEventStore.fetchDefaultEvent();
    // 并行加载其他数据
    await Promise.all([
      // 加载所有项目选项并进行前端分类
      loadProjectOptions(),
      // 加载分组选项
      loadRankGroupOptions(),
    ]);

    // 在获取到项目列表并设置默认项目后，加载对应项目的排名
    if (selectedProjectId.value || selectedTeamProjectId.value) {
      await Promise.all([
        refreshPersonalRanking(),
        refreshTeamRanking()
      ]);
    }
  } catch (error) {
    console.error('加载数据失败:', error);
  }
});
</script>

<style scoped>
.ranking-board-page {
  padding: 20px;
  height: calc(100vh - 120px);
  position: relative;
}
/* 赛事名称标题样式 */
.event-title {
  margin-bottom: 20px;
  text-align: center;
}

.event-title h2 {
  font-size: 24px;
  margin: 0;
}

.event-title p {
  font-size: 16px;
  color: #666;
  margin: 5px 0 0;
}

.ranking-row {
  height: calc(100% - 70px); /* 调整高度以适应新增标题区域 */
}

.ranking-card {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
  color: black;
  text-align: center;
}

/* 团队排行榜头部样式 */
.team-ranking-header {
  display: flex;
  justify-content: center;
  align-items: center;
}

.progress-info {
  margin-bottom: 15px;
}

.ranking-list {
  max-height: 800px;
  overflow-y: auto;
}

.ranking-list-full {
  flex: 1;
  overflow-y: auto;
}

.ranking-item {
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.ranking-item:last-child {
  border-bottom: none;
}

.item-content {
  display: flex;
  justify-content: space-between;
}

.item-name {
  flex: 2;
  text-align: left;
}

.item-team,
.item-time,
.item-type,
.item-rank,
.item-team-name,
.item-group,
.item-score {
  flex: 1;
  text-align: center;
}

/* 组别详情样式 */
.group-details {
  margin-top: 8px;
  padding-left: 20px;
  border-left: 2px solid #e0e0e0;
}

.group-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
  font-size: 12px;
  color: #666;
}

.group-name {
  flex: 3;
  text-align: left;
}

.group-time {
  flex: 2;
  text-align: center;
}

.group-status {
  flex: 1;
  text-align: center;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 10px;
}

.status-0 {
  background-color: #f0f0f0;
  color: #999;
}

.status-1 {
  background-color: #e6f7ff;
  color: #1890ff;
}

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

/* 标题行样式 */
.ranking-header {
  padding: 12px 0;
  border-bottom: 2px solid #e0e0e0;
  background-color: #f8f9fa;
  font-weight: bold;
  color: #333;
  position: sticky;
  top: 0;
  z-index: 10;
}

.header-content {
  display: flex;
  justify-content: space-between;
}

/* 个人积分排行榜标题样式 */
.header-rank,
.header-team,
.header-score {
  flex: 1;
  text-align: center;
  font-size: 14px;
}

.header-project {
  flex: 1.5;
  text-align: center;
  font-size: 14px;
}

.header-name {
  flex: 2;
  text-align: left;
  font-size: 14px;
}

/* 团队积分排行榜标题样式 */
.header-team-name {
  flex: 2;
  text-align: left;
  font-size: 14px;
}

.header-group {
  flex: 1;
  text-align: center;
  font-size: 14px;
}

/* 数据行样式 */
.item-content {
  display: flex;
  justify-content: space-between;
}

/* 个人积分排行榜数据样式 */
.item-name {
  flex: 2;
  text-align: left;
}

.item-team,
.item-time,
.item-type,
.item-rank {
  flex: 1;
  text-align: center;
}

.item-project-name {
  flex: 1.5;
  text-align: center;
}

/* 团队积分排行榜数据样式 */
.item-team-name {
  flex: 2;
  text-align: left;
}

.item-rank,
.item-group,
.item-score {
  flex: 1;
  text-align: center;
}

/* 团队积分排行榜特殊样式优化 */
.ranking-item {
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.ranking-item:hover {
  background-color: #f8f9fa;
}

.ranking-item:last-child {
  border-bottom: none;
}

/* 组别列样式优化 */
.item-group {
  color: #666;
  font-size: 13px;
}

/* 总分列样式优化 */
.item-score {
  font-weight: 500;
  /* color: #1890ff; */
}

/* 个人排行榜头部样式 */
.personal-ranking-header {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 8px 0;
}

/* 团队排行榜头部样式 */
.team-ranking-header {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 8px 0;
}

/* 标题样式 */
.item-score {
  width: 120px;
  /* text-align: right; */
  font-weight: bold;
  color: green;
  font-family: 'Digital-7', 'Courier New', Courier, monospace;
}

.score-unit {
  font-size: 0.8em;
  /* margin-left: 4px; */
  color: green;
  font-family: 'Inter', sans-serif;
}

.header-title {
  text-align: center;
  font-weight: bold;
  font-size: 16px;
  color: black;
  margin-bottom: 4px;
}

/* 控件区域样式 */
.header-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
  min-height: 32px;
}

/* 显示数量控制样式 */
.display-count-control {
  display: flex;
  align-items: center;
  white-space: nowrap;
  background-color: #f8f9fa;
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

/* 分组选择框样式 */
.group-select {
  width: 120px;
}

/* 刷新按钮样式 */
.refresh-btn {
  min-width: 60px;
  height: 28px;
}

.refresh-btn .el-icon {
  margin-right: 4px;
}

.control-label {
  font-size: 12px;
  color: #666;
  margin: 0 2px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .header-controls {
    flex-direction: column;
    gap: 10px;
    align-items: center;
  }
  
  .display-count-control {
    order: 1;
  }
  
  .group-select {
    order: 2;
  }
  
  .refresh-btn {
    order: 3;
  }
}

@media (max-width: 768px) {
  .header-title {
    font-size: 14px;
  }
  
  .header-controls {
    gap: 8px;
  }
  
  .group-select {
    width: 100%;
    max-width: 200px;
  }
}

/* 输入框样式优化 */
.display-count-control .el-input-number {
  --el-input-number-controls-width: 20px;
}

.display-count-control .el-input-number .el-input__inner {
  text-align: center;
  padding: 0 5px;
}

/* 右上角倒计时样式 */
.countdown-display {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
}

.countdown-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid #e4e7ed;
}

.countdown-content {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
}

.countdown-icon {
  color: #409eff;
  font-size: 16px;
}

.countdown-text {
  font-weight: bold;
  color: #409eff;
  font-size: 14px;
  min-width: 30px;
  text-align: center;
}

/* .stop-btn {
  padding: 2px;
  color: #f56c6c;
}

.stop-btn:hover {
  background-color: #fef0f0;
} */

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .countdown-display {
    top: 10px;
    right: 10px;
  }
  
  .countdown-content {
    padding: 2px 6px;
  }
  
  .countdown-text {
    font-size: 12px;
    min-width: 25px;
  }
}
</style>