<template>
  <div class="p-2">
    <!-- 右上角倒计时显示 -->
    <!-- <div class="countdown-display" v-if="countdownSeconds > 0">
      <el-card shadow="never" class="countdown-card">
        <div class="countdown-content">
          <el-icon class="countdown-icon"><Timer /></el-icon>
          <span class="countdown-text">{{ countdownSeconds }}s</span>
        </div>
      </el-card>
    </div> -->
    <!-- 顶部搜索框 -->
    <div class="flex items-center mb-4">
      <el-button type="primary" @click="refreshData"><el-icon><Refresh /></el-icon> 刷新</el-button>
      <div class="countdown-button" v-if="countdownSeconds > 0">
        <el-button size="default" type="primary">
          <!-- <el-icon class="countdown-icon"><Timer /></el-icon> -->
          {{ countdownSeconds }}秒后刷新
        </el-button>
      </div>
      <el-button type="success" @click="calculateRankings" :loading="rankingLoading">
        <el-icon><Trophy /></el-icon> 计算排名
      </el-button>
      <el-button type="warning" @click="handleExport">
        <el-icon><Download /></el-icon> 导出
      </el-button>
      <el-button type="info" plain @click="handleImport">
        <el-icon><Upload /></el-icon> 导入
      </el-button>
      <el-input 
        v-model="searchValue" 
        :placeholder="projectClassification === '0' ? '输入运动员姓名搜索' : '输入队伍名称搜索'" 
        style="margin-left: 20px; width: 200px;" 
        clearable 
        @keyup.enter="loadData">
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-tag :type="projectClassification === '0' ? 'success' : 'warning'" class="ml-4 mr-2">
        {{ projectClassification === '0' ? '个人项目' : '团体项目' }}
      </el-tag>
      <div class="stats-container flex items-center space-x-5 text-xs ml-1">
        <div class="stats-item">
          <span class="stats-label">报名人数：</span>
          <span class="stats-value text-blue">{{ stats.registrationCount }}</span>
        </div>
        <div class="stats-item">
          <span class="stats-label">参赛总{{ projectClassification === '0' ? '人数' : '队数' }}：</span>
          <span class="stats-value text-green">{{ stats.participantCount }}</span>
        </div>
        <div class="stats-item">
          <span class="stats-label">完赛总{{ projectClassification === '0' ? '人数' : '队数' }}：</span>
          <span class="stats-value text-orange">{{ stats.finishedCount }}</span>
        </div>
        <div class="stats-item">
          <span class="stats-label">未赛总{{ projectClassification === '0' ? '人数' : '队数' }}：</span>
          <span class="stats-value text-red">{{ stats.unstartedCount }}</span>
        </div>
      </div>
    </div>

    <el-card shadow="never">
      <el-table v-loading="loading" border :data="dataList">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" />
        <el-table-column label="队伍编号" align="center" prop="teamCode" />
        <el-table-column label="队伍名称" align="center" prop="teamName" />
        <el-table-column label="项目类型" align="center" prop="projectType" >
          <template #default="scope">
            <dict-tag :options="game_project_type" :value="scope.row.projectType" />
          </template>
        </el-table-column>
        <el-table-column label="项目" align="center" prop="projectName" />
        
        <!-- 个人项目显示运动员信息 -->
        <template v-if="projectClassification === '0'">
          <el-table-column label="号码" align="center" prop="athleteCode" />
          <el-table-column label="姓名" align="center" prop="name" />
          <el-table-column label="性别" align="center" prop="gender" >
            <template #default="scope">
              <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
            </template>
          </el-table-column>
          <el-table-column label="个人成绩" align="center" prop="individualPerformance">
            <template #default="scope">
              <span>{{ scope.row.individualPerformance }}</span>
              <span v-if="scope.row.individualPerformance !== '--'" style="margin-left: 4px; font-size: 12px; color: #999;">
                {{ 
                  projectInfo.scoreRule === '1' ? '秒' : 
                  (['2', '6', '7'].includes(projectInfo.scoreRule) ? '米' : projectInfo.countUnit) 
                }}
              </span>
            </template>
          </el-table-column>
        </template>
        
        <!-- 团体项目显示队伍信息 -->
        <template v-else>
          <el-table-column label="团队成绩" align="center" prop="teamPerformance">
            <template #default="scope">
              <span>{{ scope.row.teamPerformance }}</span>
              <span v-if="scope.row.teamPerformance !== '--'" style="margin-left: 4px; font-size: 12px; color: #999;">
                {{ 
                  projectInfo.scoreRule === '1' ? '秒' : 
                  (['2', '6', '7'].includes(projectInfo.scoreRule) ? '米' : projectInfo.countUnit) 
                }}
              </span>
            </template>
          </el-table-column>
        </template>
        
        <el-table-column label="积分" align="center" sortable prop="scorePoint" />
        <el-table-column label="排名" align="center" sortable prop="scoreRank" />
        <el-table-column label="更新时间" align="center" sortable prop="updateTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改成绩" placement="top">
              <el-button link type="primary" icon="Edit" @click="editScore(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改裁判对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="400px" append-to-body>
      <el-form ref="scoreFormRef" :model="form" :rules="rules" label-width="100px">
        <!-- 个人项目录入 -->
        <template v-if="projectClassification === '0'">
          <div style="margin-bottom: 15px; background: #f8f9fb; padding: 10px; border-radius: 4px;">
            <p><strong>运动员：</strong>{{ pickAthletes || '--' }}</p>
            <p><strong>队伍：</strong>{{ form.teamName || '--' }}</p>
          </div>

          <!-- 动态明细录入区域 -->
          <div v-if="['2', '4', '6', '7'].includes(projectInfo.scoreRule)" class="detail-section">
            <div v-for="(item, index) in scoreDetails" :key="index" style="margin-bottom: 10px; display: flex; align-items: center;">
              <span style="width: 80px;">第 {{ index + 1 }} 轮：</span>
              <el-input-number v-model="item.performanceValue" :precision="3" :step="0.1" style="flex: 1" />
              <span style="margin-left: 8px; color: #666; width: 30px;">
                {{ 
                  projectInfo.scoreRule === '1' ? '秒' : 
                  (['2', '6', '7'].includes(projectInfo.scoreRule) ? '米' : projectInfo.countUnit) 
                }}
              </span>
            </div>
          </div>

          <!-- 单次计数类额外录入失误 -->
          <template v-else-if="projectInfo.scoreRule === '3'">
            <el-form-item label="单次成绩" prop="individualPerformance">
              <el-input-number v-model="form.individualPerformance" :precision="3" style="width: 100%" />
            </el-form-item>
            <el-form-item v-if="projectInfo.orderType && projectInfo.orderType.includes('2')" label="失误次数A">
              <el-input-number v-model="form.faultA" :min="0" style="width: 100%" />
            </el-form-item>
            <el-form-item v-if="projectInfo.orderType && projectInfo.orderType.includes('3')" label="失误次数B">
              <el-input-number v-model="form.faultB" :min="0" style="width: 100%" />
            </el-form-item>
          </template>

          <!-- 基础成绩录入（计时/排名/默认） -->
          <el-form-item v-else label="个人成绩" prop="individualPerformance">
            <el-input 
              v-model="form.individualPerformance" 
              :placeholder="projectInfo.scoreRule === '1' ? '支持输入秒数或 00:00.00 格式' : '输入成绩'"
            >
              <template #append v-if="projectInfo.scoreRule === '1'">秒</template>
              <template #append v-else-if="['2', '6', '7'].includes(projectInfo.scoreRule)">米</template>
              <template #append v-else-if="projectInfo.countUnit">{{ projectInfo.countUnit }}</template>
            </el-input>
          </el-form-item>
        </template>
        
        <!-- 团体项目录入 -->
        <template v-else>
          <div style="margin-bottom: 15px; background: #f8f9fb; padding: 10px; border-radius: 4px;">
            <p><strong>队伍：</strong>{{ form.teamName || '--' }}</p>
          </div>

          <!-- 动态明细录入区域 (如团体项目也有多轮) -->
          <div v-if="['2', '4', '6', '7'].includes(projectInfo.scoreRule)" class="detail-section">
            <div v-for="(item, index) in scoreDetails" :key="index" style="margin-bottom: 10px; display: flex; align-items: center;">
              <span style="width: 80px;">第 {{ index + 1 }} 轮：</span>
              <el-input-number v-model="item.performanceValue" :precision="3" :step="0.1" style="flex: 1" />
            </div>
          </div>

          <!-- 基础成绩录入（计时类支持字符串，其他数字） -->
          <el-form-item v-else label="团队成绩" prop="teamPerformance">
            <el-input 
              v-if="projectInfo.scoreRule === '1'"
              v-model="form.teamPerformance" 
              placeholder="支持输入 00:00.00 格式"
            >
              <template #append>秒</template>
            </el-input>
            <div v-else style="display: flex; align-items: center;">
              <el-input-number v-model="form.teamPerformance" :precision="3" style="flex: 1" />
              <span style="margin-left: 8px; color: #666;">
                {{ 
                  ['2', '6', '7'].includes(projectInfo.scoreRule) ? '米' : projectInfo.countUnit 
                }}
              </span>
            </div>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">保存成绩</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="handlePagination({page: queryParams.pageNum, limit: queryParams.pageSize})" />

    <!-- 导出设置对话框 -->
    <el-dialog title="导出成绩详情" v-model="exportDialog.visible" width="400px" append-to-body>
      <el-form label-width="120px">
        <el-form-item label="导出前几名：">
          <el-input-number v-model="exportDialog.topN" :min="0" :precision="0" placeholder="不输入导出所有" style="width: 100%" />
          <div class="help-block" style="color: #999; font-size: 12px; margin-top: 5px;">提示：输入 0 或不输入表示导出所有成绩</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="doExport" :loading="exportLoading">确 定</el-button>
          <el-button @click="exportDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 成绩导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :data="upload.data"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplateFile">下载模板 </el-link>
          </div>
        </template>
      </el-upload>
      <div style="margin-top: 10px; text-align: center;">
        <el-checkbox v-model="upload.updateSupport" :true-label="1" :false-label="0"> 存在是否覆盖成绩</el-checkbox>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GameScoreEdit" lang="ts">
import { onMounted, onUnmounted, ref, reactive, getCurrentInstance, toRefs } from 'vue';
import { useRoute } from 'vue-router';
import { getProjectScoreData, updateScoreAndRecalculate, exportProjectScore, importTemplate } from '@/api/system/gameScore/index';
import { globalHeaders } from '@/utils/request';
import { getGameEventProject } from '@/api/system/gameEventProject';
import { listScoreDetail } from '@/api/system/scoreDetail';
import { GameScoreForm } from '@/api/system/gameScore/types';
import Pagination from '@/components/Pagination/index.vue';
import type { ComponentInternalInstance } from 'vue';

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

const route = useRoute();
const buttonLoading = ref(false);
const rankingLoading = ref(false);
const projectInfo = ref<any>({}); // 存储项目规则信息

// 成绩明细列表
const scoreDetails = ref<any[]>([]);

const dataList = ref<any[]>([]);
const loading = ref(true);
const total = ref(0);
const pickAthletes = ref('');
const exportLoading = ref(false);

const exportDialog = reactive({
  visible: false,
  topN: undefined as number | undefined
});

/*** 成绩导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（成绩导入）
  open: false,
  // 弹出层标题（成绩导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/system/gameScore/import',
  eventId: '',
  projectId: '',
  classification: '',
  updateSupport: 1,
  data: {}
});
const uploadRef = ref<ElUploadInstance>();

// 统计数据
const stats = reactive({
  registrationCount: 0,
  participantCount: 0,
  finishedCount: 0,
  unstartedCount: 0
});

// 定义搜索框状态变量
const searchValue = ref('');

const eventId = route.params.eventId as string;
const projectId = route.params.projectId as string;
const projectName = route.params.projectName as string;
const projectType = route.params.projectType as string;
const projectClassification = route.params.classification as string || '0'; // 默认为个人项目

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  eventId: eventId,
  projectId: projectId,
  projectName: projectName,
  projectType: projectType,
  classification: projectClassification,
});

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

//刷新数据方法
const refreshData = () => {
  searchValue.value = '';
  loadData(false); // 刷新时不自动计算排名，需要手动点击计算排名按钮
  // 手动刷新时重置倒计时
  startCountdown();
};

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

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

// 开启自动刷新（页面加载时自动调用）
const startAutoRefresh = () => {
  if (autoRefreshInterval.value) {
    clearInterval(autoRefreshInterval.value);
  }
  
  autoRefreshInterval.value = setInterval(() => {
    loadData(false); // 自动刷新时不自动计算排名
  }, autoRefreshSeconds.value * 1000);
  
  startCountdown();
};

// 计算排名方法
const calculateRankings = async () => {
  try {
    rankingLoading.value = true;
    
    // 调用后端接口重新计算排名和积分
    await updateScoreAndRecalculate({
      eventId: eventId,
      projectId: projectId,
      scoreType: projectClassification === '0' ? 'individual' : 'team',
      statusFlag: '0',
      status: '0',
      remark: '手动触发排名计算'
    } as GameScoreForm);
    
    proxy?.$modal.msgSuccess("排名计算完成");
    
    // 重新加载数据以显示新的排名和积分
    await loadData(false); // 不自动计算排名，避免循环
  } catch (error) {
    // console.error("排名计算失败:", error);
    proxy?.$modal.msgError("排名计算失败，请稍后再试");
  } finally {
    rankingLoading.value = false;
  }
};

const scoreFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const form = reactive({
  scorePoint: null,
  individualPerformance: 0,
  teamPerformance: 0,
  scoreRank: null,
  scoreId: 0,
  athleteId: 0,
  teamId: 0,
  eventId: '',
  projectId: '',
  athleteCode: '',
  userId: 0,
  teamName: '',
  updateTime: '',
  faultA: 0,
  faultB: 0
});

const reset = () => {
  Object.assign(form, {
    scorePoint: null, individualPerformance: 0, teamPerformance: 0, scoreRank: null,
    scoreId: 0, athleteId: 0, teamId: 0, eventId: '', projectId: '',
    athleteCode: '', userId: 0, teamName: '', updateTime: '', faultA: 0, faultB: 0
  });
  scoreDetails.value = [];
};

const rules = {
  individualPerformance: [
    { required: true, message: "个人成绩不能为空", trigger: "blur" },
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (value !== '' && value !== null && value !== undefined) {
          const numValue = parseFloat(value);
          if (isNaN(numValue)) {
            callback(new Error('请输入有效的数字'));
          } else if (numValue < 0) {
            callback(new Error('成绩不能为负数'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      }, 
      trigger: "blur" 
    }
  ],
  teamPerformance: [
    { required: true, message: "团队成绩不能为空", trigger: "blur" },
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (value !== '' && value !== null && value !== undefined) {
          const numValue = parseFloat(value);
          if (isNaN(numValue)) {
            callback(new Error('请输入有效的数字'));
          } else if (numValue < 0) {
            callback(new Error('成绩不能为负数'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      }, 
      trigger: "blur" 
    }
  ],
}

/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
}

/** 修改成绩 */
const editScore = async (row: any) => {
  reset();
  
  // 强制重新加载项目规则信息，确保获取到最新的 scoreCount 和 countUnit
  await loadProjectInfo();
  
  Object.assign(form, { ...row });
  pickAthletes.value = row.name;
  
  // 如果是需要明细的项目（远度、多次计数等），加载明细
  if (['2', '4', '6', '7'].includes(projectInfo.value.scoreRule)) {
    // 改为按维度查询，不再单纯依赖 scoreId
    const queryParams: any = { 
      projectId: row.projectId 
    };
    if (projectClassification === '0') {
      queryParams.athleteId = row.athleteId;
    } else {
      queryParams.teamId = row.teamId;
    }
    
    const res = await listScoreDetail(queryParams);
    const existingDetails = res.rows || [];
    // 根据项目配置的次数初始化明细数组
    const count = projectInfo.value.scoreCount || 1;
    scoreDetails.value = [];
    for (let i = 1; i <= count; i++) {
      const detail = existingDetails.find((d: any) => d.attemptIndex === i);
      scoreDetails.value.push({
        scoreId: row.scoreId,
        attemptIndex: i,
        performanceValue: detail ? detail.performanceValue : 0,
        faultA: detail ? detail.faultA : 0,
        faultB: detail ? detail.faultB : 0
      });
    }
  }
  
  dialog.visible = true;
  dialog.title = "录入成绩";
};

/** 提交表单 */
const submitForm = () => {
  scoreFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 使用 any 避开 TS 对 details 的类型检查
        const postData: any = { ...form };
        
        // 计时类单位转换 (统一处理两个字段，确保不携带时间格式字符串)
        if (projectInfo.value.scoreRule === '1') {
          if (typeof postData.individualPerformance === 'string') {
            postData.individualPerformance = timeToSeconds(postData.individualPerformance);
          }
          if (typeof postData.teamPerformance === 'string') {
            postData.teamPerformance = timeToSeconds(postData.teamPerformance);
          }
        } else {
          // 非计时类，也确保是数值，防止占位符干扰
          if (isNaN(parseFloat(postData.individualPerformance))) postData.individualPerformance = 0;
          if (isNaN(parseFloat(postData.teamPerformance))) postData.teamPerformance = 0;
        }

        // 挂载成绩明细
        postData.details = scoreDetails.value;
        
        // 调用后端接口更新成绩（后端已支持 recalculate）
        await updateScoreAndRecalculate(postData);
        
        proxy?.$modal.msgSuccess("保存成功，排名已重新计算");
        dialog.visible = false;
        loadData(false);
      } catch (err) {
        console.error("提交失败:", err);
        proxy?.$modal.msgError("保存失败，请检查网络或数据格式");
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 导出按钮操作 */
const handleExport = () => {
  exportDialog.topN = undefined;
  exportDialog.visible = true;
};

/** 执行导出 */
const doExport = async () => {
  try {
    exportLoading.value = true;
    const response = await exportProjectScore(eventId, projectId, exportDialog.topN || 0);
    
    // 生成文件名
    const classificationStr = projectClassification === '0' ? '个人' : '团体';
    const fileName = `${classificationStr}_${projectName}_成绩详情.xlsx`;
    
    // 下载文件
    const blob = new Blob([response as any]);
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(link.href);
    
    proxy?.$modal.msgSuccess("导出成功");
    exportDialog.visible = false;
  } catch (error) {
    // console.error("导出失败:", error);
    proxy?.$modal.msgError("导出失败，请稍后再试");
  } finally {
    exportLoading.value = false;
  }
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '成绩导入';
  upload.eventId = eventId;
  upload.projectId = projectId;
  upload.classification = projectClassification;
  upload.updateSupport = 1;
  upload.data = {
    eventId: eventId,
    projectId: projectId,
    classification: projectClassification,
    updateSupport: upload.updateSupport
  };
  upload.open = true;
};

/** 下载模板操作 */
const importTemplateFile = async () => {
  try {
    const response = await importTemplate(eventId, projectId, projectClassification);
    const fileName = `成绩导入模板_${projectName}.xlsx`;
    const blob = new Blob([response as any]);
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(link.href);
  } catch (error) {
    proxy?.$modal.msgError("下载模板失败");
  }
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: any) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {
    dangerouslyUseHTMLString: true
  });
  loadData(false);
};

/** 提交上传文件 */
function submitFileForm() {
  upload.data.updateSupport = upload.updateSupport;
  uploadRef.value?.submit();
}

// 加载数据方法，支持搜索
const loadData = async (autoCalculateRanking = false) => {
  loading.value = true;
  
  try {
    // 调用后端接口获取综合数据
    const response: any = await getProjectScoreData({
      eventId: eventId,
      projectId: projectId,
      classification: projectClassification,
      searchValue: searchValue.value,
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    });
    
    // 适配后端包装结构
    const tableData = response.data.tableData || { rows: [], total: 0 };
    const statsData = response.data.stats || {};
    
    // 更新统计信息
    Object.assign(stats, statsData);
    dataList.value = tableData.rows || [];
    total.value = tableData.total || 0;
    
    // 只有在自动计算排名的情况下才进行排名计算
    if (autoCalculateRanking) {
      await calculateRankings();
    }
  } catch (error) {
    // console.error("加载数据失败:", error);
    proxy?.$modal.msgError("数据加载失败");
    dataList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 分页组件事件处理
const handlePagination = (paginationData: { page: number, limit: number }) => {
  queryParams.pageNum = paginationData.page;
  queryParams.pageSize = paginationData.limit;
  loadData(false); // 分页加载不自动计算排名
};

/** 时间字符串转秒 (00:00.00 -> 60.00) */
const timeToSeconds = (timeStr: string) => {
  if (!timeStr || !timeStr.includes(':')) return parseFloat(timeStr) || 0;
  const parts = timeStr.split(':');
  let seconds = 0;
  if (parts.length === 3) { // 00:00:00.000
    seconds = parseInt(parts[0]) * 3600 + parseInt(parts[1]) * 60 + parseFloat(parts[2]);
  } else if (parts.length === 2) { // 00:00.00
    seconds = parseInt(parts[0]) * 60 + parseFloat(parts[1]);
  }
  return seconds;
};

/** 加载项目规则信息 */
const loadProjectInfo = async () => {
  const res = await getGameEventProject(projectId);
  projectInfo.value = res.data;
};

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

onMounted(() => {
  loadProjectInfo(); // 加载规则
  loadData(false); // 页面初始化时不自动计算排名，需要手动点击计算排名按钮
  // 开启自动刷新
  startAutoRefresh();
});
</script>

<style scoped>
/* 页面基础样式 */
.p-2 {
  padding: 0.5rem;
  position: relative;
}

/* Flex 布局样式 */
.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.mb-4 {
  margin-bottom: 1rem;
}

.ml-4 {
  margin-left: 1rem;
}

.mr-2 {
  margin-right: 0.5rem;
}

/* 统计展示样式 */
.stats-container {
  display: flex;
  align-items: center;
  background-color: #f8f9fa;
  padding: 4px 12px;
  border-radius: 4px;
  border: 1px solid #e9ecef;
  flex-wrap: nowrap; /* 不允许换行 */
}

.stats-item {
  display: flex;
  align-items: center;
  margin-right: 16px;
  font-size: 14px;
}

.stats-item:last-child {
  margin-right: 0;
}

.stats-label {
  color: #606266;
  font-weight: 500;
}

.stats-value {
  font-weight: bold;
  font-family: 'Courier New', Courier, monospace;
}

.text-blue { color: #409eff; }
.text-green { color: #67c23a; }
.text-orange { color: #e6a23c; }
.text-red { color: #f56c6c; }

/* 表格样式 */
.el-table {
  width: 100%;
}

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

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

/* 表格列样式 */
.small-padding {
  padding: 8px;
}

.fixed-width {
  width: 120px;
}

/* 按钮样式 */
.el-button {
  margin-right: 8px;
}

.el-button:last-child {
  margin-right: 0;
}

/* 输入框样式 */
.el-input {
  width: 100%;
}

/* 标签样式 */
.el-tag {
  margin-right: 8px;
}

/* 对话框样式 */
.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 8px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  text-align: center;
}

/* 加载状态样式 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
}

/* 表单样式 */
.el-form-item {
  margin-bottom: 18px;
}

.el-form-item__label {
  font-weight: 500;
}

/* 数字输入框样式 */
.el-input-number {
  width: 100%;
}

.el-input-number .el-input__inner {
  text-align: left;
}

/* 搜索框样式 */
.el-input__prefix {
  color: #c0c4cc;
}

.el-input__suffix {
  color: #c0c4cc;
}

/* 图标样式 */
.el-icon {
  font-size: 16px;
}

/* 工具提示样式 */
.el-tooltip {
  display: inline-block;
}

/* 卡片样式 */
.el-card {
  border-radius: 4px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-card__header {
  padding: 18px 20px;
  border-bottom: 1px solid #ebeef5;
  box-sizing: border-box;
}

.el-card__body {
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .flex {
    flex-wrap: wrap;
  }
  
  .ml-4 {
    margin-left: 0;
    margin-top: 10px;
  }
}

@media (max-width: 768px) {
  .p-2 {
    padding: 0.25rem;
  }
  
  .mb-4 {
    margin-bottom: 0.5rem;
  }
  
  .el-button {
    margin-bottom: 8px;
  }
  
  .el-input {
    width: 100%;
    margin-left: 0 !important;
    margin-top: 10px;
  }
  
  .text-gray-600 {
    margin-top: 10px;
    text-align: center;
  }
}

@media (max-width: 480px) {
  .el-table {
    font-size: 12px;
  }
  
  .el-button {
    padding: 8px 12px;
    font-size: 12px;
  }
  
  .el-input {
    font-size: 12px;
  }
}

/* 动画效果 */
.el-button {
  transition: all 0.3s;
}

.el-input {
  transition: all 0.3s;
}

.el-table__row {
  transition: background-color 0.3s;
}

/* 焦点状态 */
.el-input:focus-within {
  border-color: #409eff;
}

.el-button:focus {
  outline: none;
}

/* 禁用状态 */
.el-button.is-disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 加载状态 */
.el-button.is-loading {
  pointer-events: none;
}

/* 表格选择列样式 */
.el-table__selection {
  text-align: center;
}

/* 表格操作列样式 */
.el-table__fixed-right {
  background-color: #fff;
}

/* 对话框动画 */
.el-dialog {
  border-radius: 4px;
}

.el-dialog__header {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  padding: 10px 20px 20px;
  text-align: right;
}

/* 表单验证样式 */
.el-form-item.is-error .el-input__inner {
  border-color: #f56c6c;
}

.el-form-item.is-success .el-input__inner {
  border-color: #67c23a;
}

/* 消息提示样式 */
.el-message {
  border-radius: 4px;
}

/* 工具提示样式 */
.el-tooltip__popper {
  border-radius: 4px;
}

/* 标签样式 */
.el-tag {
  border-radius: 4px;
  border: 1px solid;
}

.el-tag--success {
  background-color: #f0f9ff;
  border-color: #67c23a;
  color: #67c23a;
}

.el-tag--warning {
  background-color: #fdf6ec;
  border-color: #e6a23c;
  color: #e6a23c;
}

/* 分页组件样式 */
.pagination-container .el-pagination {
  text-align: center;
  margin-top: 20px;
}

/* 右上角倒计时样式 */
.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;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.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;
}

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