<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" @click="saveBonusChanges" :loading="saveLoading">
              <el-icon><Check /></el-icon> 保存修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" @click="exportBonusData" :loading="exportLoading">
              <el-icon><Download /></el-icon> 导出Excel
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button @click="refreshBonusData">
              <el-icon><Refresh /></el-icon> 刷新数据
            </el-button>
          </el-col>
          <!-- 组别筛选 -->
          <el-col :span="4">
            <el-select 
              v-model="selectedRankGroupId" 
              placeholder="按组别筛选" 
              clearable 
              filterable
              style="width: 100%"
              @change="loadBonusData"
            >
              <el-option
                v-for="item in rankGroupOptions"
                :key="item.rgId"
                :label="item.rgName"
                :value="item.rgId"
              />
            </el-select>
          </el-col>
          <!-- 倒计时显示区域 -->
          <el-col :span="4">
            <div class="countdown-info">
              <el-button size="default" type="primary" style="width: 100%">
                {{ countdownSeconds }}秒后刷新
              </el-button>
            </div>
          </el-col>
          <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="loadBonusData" ></right-toolbar> -->
        </el-row>
      </template>
      
      <el-table 
        v-loading="bonusLoading" 
        border 
        :data="bonusDataList" 
        :key="bonusDataList.length + '_' + bonusProjectList.length"
        max-height="calc(100vh - 200px)"
        show-summary
        :summary-method="getSummaries"
        @selection-change="handleBonusSelectionChange">
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" align="center" width="80" fixed="left">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="代表队名称" align="center" prop="teamName" width="150" fixed="left" />
        <el-table-column label="排名" align="center" prop="rank" width="80" fixed="left" />
        <el-table-column label="总分" align="center" prop="totalScore" width="100" fixed="left" />
        
        <!-- 动态项目列 -->
        <el-table-column 
          v-for="project in bonusProjectList" 
          :key="project.projectId" 
          :prop="project.projectId + ''"
          align="center" 
          width="120">
          <template #header>
            <div class="project-header-container">
              <el-button 
                link 
                type="primary" 
                @click="goToProjectDetail(project)"
                class="project-header-link">
                {{ project.projectName }}
              </el-button>
              <div class="project-total-score">总分: {{ getProjectTotal(project.scoreValue) }}</div>
            </div>
          </template>
          <template #default="scope">
            {{ scope.row.projectScores[project.projectName] || 0 }}
          </template>
        </el-table-column>
        
        <!-- 领导加分列 - 可编辑 -->
        <el-table-column label="领导加分" align="center" width="120">
          <template #default="scope">
            <el-input 
              v-model="scope.row.leaderPoint" 
              type="number" 
              :min="0"
              step="1"
              size="small"
              @input="calculateTotalScore(scope.row)"
              @blur="calculateTotalScore(scope.row)" />
          </template>
        </el-table-column>
        
        <!-- 额外加分列 - 可编辑 -->
        <el-table-column label="额外加分" align="center" width="120">
          <template #default="scope">
            <el-input 
              v-model="scope.row.extraPoint" 
              type="number" 
              :min="0"
              step="1"
              size="small"
              @input="calculateTotalScore(scope.row)"
              @blur="calculateTotalScore(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup name="GameScoreBonus" lang="ts">
import { ref, onMounted, onUnmounted, getCurrentInstance, toRefs } from 'vue';
import { useRouter } from 'vue-router';
import { getBonusData, updateBonusData, exportBonusExcel } from '@/api/system/gameScore';
import { useGameEventStore } from '@/store/modules/gameEvent';
import type { ComponentInternalInstance } from 'vue';
import { listRankGroup } from '@/api/system/rankGroup';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();

// 默认赛事信息
const gameEventStore = useGameEventStore();

const bonusLoading = ref(false);
const saveLoading = ref(false);
const exportLoading = ref(false);
const showSearch = ref(true);

const bonusDataList = ref<any[]>([]);
const bonusProjectList = ref<any[]>([]);
const selectedBonusRows = ref<any[]>([]);

// 分组筛选相关
const rankGroupOptions = ref<any[]>([]);
const selectedRankGroupId = ref<string | number | null>(null);

// 列显隐数据
const columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true },
  { key: 1, label: '代表队名称', visible: true },
  { key: 2, label: '排名', visible: true },
  { key: 3, label: '总分', visible: true },
  { key: 4, label: '领导加分', visible: true },
  { key: 5, label: '额外加分', visible: true },
]);

// 自动刷新相关状态
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) {
      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(() => {
    loadBonusData(); // 自动刷新数据
  }, autoRefreshSeconds.value * 1000);
  
  startCountdown();
};

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

// 加载加分数据
const loadBonusData = async () => {
  bonusLoading.value = true;
  try {
    const event = gameEventStore.defaultEventInfo;
    const eventId = event?.eventId;
    
    if (!eventId) {
      proxy?.$modal.msgWarning('未指定赛事，无法加载加分数据');
      return;
    }
    
    const response = await getBonusData({
      eventId: eventId,
      rgId: selectedRankGroupId.value || undefined
    });
    
    bonusDataList.value = response.data.rows || [];
    bonusProjectList.value = response.data.projects || [];
    
    // 初始化加分字段
    bonusDataList.value.forEach((row: any) => {
      if (!row.leaderPoint) row.leaderPoint = 0;
      if (!row.extraPoint) row.extraPoint = 0;
      calculateTotalScore(row);
    });
  } catch (error) {
    console.error("加载加分数据失败:", error);
    proxy?.$modal.msgError("加载加分数据失败");
  } finally {
    bonusLoading.value = false;
  }
};

// 计算总分
const calculateTotalScore = (row: any) => {
  // 强制修正负数为0
  if (row.leaderPoint < 0) row.leaderPoint = 0;
  if (row.extraPoint < 0) row.extraPoint = 0;
  
  let totalScore = 0;
  
  // 累加各项目积分
  Object.values(row.projectScores || {}).forEach((score: any) => {
    totalScore += Number(score) || 0;
  });
  
  // 加上领导加分和额外加分
  totalScore += Number(row.leaderPoint) || 0;
  totalScore += Number(row.extraPoint) || 0;
  
  row.totalScore = totalScore;
  
  // 重新计算排名
  calculateBonusRankings();
};

// 计算excel表排名
const calculateBonusRankings = () => {
  // 按总分排序
  const sortedData = [...bonusDataList.value].sort((a, b) => b.totalScore - a.totalScore);
  
  // 更新排名
  sortedData.forEach((row, index) => {
    row.rank = index + 1;
  });
  
  // 更新原数组
  bonusDataList.value = sortedData;
};

// 选择变化处理
const handleBonusSelectionChange = (selection: any[]) => {
  selectedBonusRows.value = selection;
};

// 保存加分修改
const saveBonusChanges = async () => {
  try {
    saveLoading.value = true;
    
    const event = gameEventStore.defaultEventInfo;
    const eventId = event?.eventId;
    
    if (!eventId) {
      proxy?.$modal.msgWarning('未指定赛事，无法保存');
      return;
    }
    
    const updateData = bonusDataList.value.map(row => ({
      teamId: row.teamId,
      leaderPoint: Number(row.leaderPoint) || 0,
      extraPoint: Number(row.extraPoint) || 0,
      totalScore: row.totalScore,
      rank: row.rank
    }));
    
    await updateBonusData({
      eventId: eventId,
      data: updateData
    });
    
    proxy?.$modal.msgSuccess("保存成功");
  } catch (error) {
    console.error("保存失败:", error);
    proxy?.$modal.msgError("保存失败，请稍后再试");
  } finally {
    saveLoading.value = false;
  }
};

// 导出加分数据方法
const exportBonusData = async () => {
  try {
    exportLoading.value = true;
    
    const event = gameEventStore.defaultEventInfo;
    const eventId = event?.eventId;
    
    if (!eventId) {
      proxy?.$modal.msgWarning('未指定默认赛事，无法导出');
      return;
    }
    
    // 使用 proxy?.download 方法，传递JSON字符串参数
    proxy?.download(
      '/system/gameScore/exportBonusExcel',
      {
        eventId: eventId,
        data: JSON.stringify(bonusDataList.value),
        projects: JSON.stringify(bonusProjectList.value)
      },
      `${gameEventStore.defaultEventInfo?.eventCode || ''}_总成绩排名表.xlsx`
    );
    
    proxy?.$modal.msgSuccess("导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    proxy?.$modal.msgError("导出失败，请稍后再试");
  } finally {
    exportLoading.value = false;
  }
};

// 刷新加分数据
const refreshBonusData = async () => {
  await loadBonusData();
  // 手动刷新时重置倒计时
  startCountdown();
};

// 获取项目总分（积分分值之和）
const getProjectTotal = (scoreValue: string | null | undefined) => {
  if (!scoreValue) return 0;
  // 兼容逗号、中文逗号和空格分隔
  const values = scoreValue.split(/[,，\s]+/);
  return values.reduce((sum, val) => sum + (Number(val) || 0), 0);
};

// 表格汇总行计算逻辑
const getSummaries = (param: any) => {
  const { columns, data } = param;
  const sums: string[] = [];
  
  columns.forEach((column: any, index: number) => {
    // 根据图片，合计应该显示在第一个单元格（index 1，因为 index 0 是勾选框）
    if (index === 1) {
       sums[index] = '合计';
       return;
    }
    
    // 查找当前列对应的项目
    const identifier = column.property;
    if (!identifier) {
      sums[index] = '';
      return;
    }
    
    const project = bonusProjectList.value.find(p => String(p.projectId) === identifier || p.projectName === identifier);
    if (project) {
      const values = data.map((item: any) => Number(item.projectScores[project.projectName] || 0));
      const total = values.reduce((prev: number, curr: number) => prev + curr, 0);
      const target = getProjectTotal(project.scoreValue);
      const isFinished = total >= target;
      
      sums[index] = total.toString();

      // 暴力美学：异步修改 DOM 样式，绕过 Element Plus 汇总行渲染限制
      nextTick(() => {
        const columnId = column.id;
        const footerCells = document.querySelectorAll(`.el-table__footer-wrapper .${columnId}, .el-table__fixed-footer-wrapper .${columnId}`);
        footerCells.forEach((cell: any) => {
          if (cell) {
            cell.style.color = isFinished ? '#67C23A' : '#F56C6C';
            cell.style.fontWeight = 'bold';
            cell.style.fontSize = '14px';
          }
        });
      });
    } else {
      sums[index] = '';
    }
  });
  
  return sums;
};

// 跳转到项目详情页
const goToProjectDetail = (project: any) => {
  const event = gameEventStore.defaultEventInfo;
  const eventId = event?.eventId;
  
  if (!eventId) {
    proxy?.$modal.msgWarning('未指定赛事，无法跳转');
    return;
  }
  
  if (!project.projectId) {
    proxy?.$modal.msgWarning('项目信息不完整，无法跳转');
    return;
  }
  
  // 构建路由参数
  const routeParams = {
    projectId: project.projectId,
    projectName: project.projectName || '未知项目',
    projectType: project.projectType || '0',
    eventId: eventId,
    classification: project.projectClassification || '0' // 默认为个人项目
  };
  
  // 跳转到项目详情页
  router.push({
    path: `/system/gameScore/edit/${routeParams.projectId}/${routeParams.projectName}/${routeParams.projectType}/${routeParams.eventId}/${routeParams.classification}`
  });
};

onUnmounted(() => {
  if (autoRefreshInterval.value) {
    clearInterval(autoRefreshInterval.value);
  }
  stopCountdown();
});

onMounted(async () => {
  // 先加载默认赛事信息
  await gameEventStore.fetchDefaultEvent();
  // 加载分组信息
  loadRankGroupOptions();
  // 然后加载加分数据
  await loadBonusData();
  // 开启自动刷新
  startAutoRefresh();
});
</script>

<style scoped lang="scss">

/* 倒计时信息区域样式 */
.countdown-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.countdown-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  background-color: #f0f9ff;
  border-color: #409eff;
  color: #409eff;
}

/* .countdown-description {
  font-size: 12px;
  color: #666;
  margin-left: 4px;
} */

/* 右上角倒计时样式 */
/* .countdown-display {
  position: fixed;
  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;
} */

/* 项目表头链接样式 */
.project-header-link {
  padding: 4px 8px !important;
  height: auto !important;
  font-size: 14px;
  font-weight: 600;
  color: #409eff !important;
  text-decoration: none;
  border: none !important;
  background: none !important;
  box-shadow: none !important;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.project-header-link:hover {
  color: #66b1ff !important;
  background: rgba(64, 158, 255, 0.1) !important;
  transform: translateY(-1px);
}

.project-header-link:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
}

.project-header-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.project-total-score {
  font-size: 11px;
  color: #909399;
  font-weight: normal;
}

// 汇总行样式穿透 (包含固定列部分的汇总行)
:deep(.el-table__footer-wrapper),
:deep(.el-table__fixed-footer-wrapper) {
  .summary-finished {
    color: #67c23a !important;
    font-weight: bold !important;
    .cell {
      color: #67c23a !important;
    }
  }
  .summary-unfinished {
    color: #f56c6c !important;
    font-weight: bold !important;
    .cell {
      color: #f56c6c !important;
    }
  }
}

/* 表头样式增强 */
.el-table .el-table__header .project-header-link {
  font-weight: 600;
  text-align: center;
  display: inline-block;
  min-width: 80px;
}

</style>

<style lang="scss">
/* 全局样式覆盖，确保汇总行显色 */
.el-table {
  .el-table__footer-wrapper,
  .el-table__fixed-footer-wrapper {
    .summary-finished {
      color: #67c23a !important;
      font-weight: bold !important;
      .cell {
        color: #67c23a !important;
      }
    }
    .summary-unfinished {
      color: #f56c6c !important;
      font-weight: bold !important;
      .cell {
        color: #f56c6c !important;
      }
    }
  }
}
</style>

<style scoped lang="scss">
/* 响应式设计 */
@media (max-width: 1200px) {
  .countdown-info {
    align-items: center;
    text-align: center;
  }
  
  /* .countdown-description {
    margin-left: 0;
  } */
}

@media (max-width: 768px) {
  /* .countdown-display {
    top: 10px;
    right: 10px;
  } */
  
  /* .countdown-content {
    padding: 2px 6px;
  } */
  
  /* .countdown-text {
    font-size: 12px;
    min-width: 25px;
  } */
  
  .countdown-info {
    margin-top: 10px;
  }
  
  .countdown-tag {
    font-size: 12px;
  }
  
  /* .countdown-description {
    font-size: 11px;
  } */
}

@media (max-width: 480px) {
  .countdown-info {
    width: 100%;
    text-align: center;
  }
  
  .countdown-tag {
    width: 100%;
    justify-content: center;
  }
}
</style>