<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="项目" prop="projectId">
              <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable filterable>
                <el-option
                  v-for="project in projectList"
                  :key="project.projectId"
                  :label="project.projectName"
                  :value="project.projectId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="归类" prop="classification">
              <el-select v-model="queryParams.classification" placeholder="请选择项目" clearable filterable>
                <el-option
                  v-for="op in classificationOptions"
                  :key="op.value"
                  :label="op.label"
                  :value="op.value">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="状态" prop="statusFlag">
              <el-input v-model="queryParams.statusFlag" placeholder="请输入成绩状态" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" @click="refreshData">刷新</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="printScores">打印成绩</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="DataAnalysis" @click="handleGameDataDefault" v-hasPermi="['system:gameEvent:gameData']"
              >排行榜
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" @click="exportScoresNames">导出成绩(全部)</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="warning" @click="openBonusDialog" :loading="bonusLoading">
              <el-icon><Edit /></el-icon> 加分
            </el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="loadProjects" :columns="columns"></right-toolbar>
        </el-row>
      </template>
      <!-- <el-dropdown>
        <el-button type="primary">
          导出<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>选项1</el-dropdown-item>
            <el-dropdown-item>选项2</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown> -->

      <el-table v-loading="loading" border :data="projectList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" />
        <el-table-column label="ID" align="center" prop="projectId" v-if="columns[0].visible" />
        <el-table-column label="项目类型" align="center" prop="projectType" v-if="columns[2].visible" >
          <template #default="scope">
            <dict-tag :options="game_project_type" :value="scope.row.projectType" />
          </template>
        </el-table-column>
        <el-table-column label="归类" align="center" sortable prop="classification" v-if="columns[3].visible" >
          <template #default="scope">
            <el-tag :type="scope.row.classification === '0' ? 'success' : 'warning'">
              {{ scope.row.classification === '0' ? '个人项目' : '团体项目' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="项目" align="center" prop="projectName" v-if="columns[1].visible" />

        <el-table-column label="状态" align="center" prop="status" v-if="columns[4].visible">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row)">
              {{ getStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="参赛总人/队数" align="center" sortable prop="totalParticipants" v-if="columns[7].visible">
          <template #default="scope">
            {{ scope.row.totalParticipants || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="完赛人/队数" align="center" sortable prop="completedParticipants" v-if="columns[8].visible">
          <template #default="scope">
            {{ scope.row.completedParticipants || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="未完赛人/队数" align="center" sortable prop="incompleteParticipants" v-if="columns[9].visible">
          <template #default="scope">
            {{ scope.row.incompleteParticipants || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="比赛时间" align="center" sortable prop="startTime" v-if="columns[5].visible" />
        <el-table-column label="更新时间" align="center" sortable prop="updateTime" v-if="columns[6].visible" />
        <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="navigateToEditPage(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="handlePagination" />
    </el-card>

  </div>
</template>

<script setup name="GameScore" lang="ts">
import { listGameScore, getGameScore, delGameScore, addGameScore, updateGameScore, getProjectScoreData, getBonusData, updateBonusData, exportBonusExcel } from '@/api/system/gameScore';
import { listGameEventProject } from '@/api/system/gameEventProject';
import { getGameTeam } from '@/api/system/gameTeam';
import { getGameAthlete } from '@/api/system/gameAthlete';
import { GameScoreVO, GameScoreQuery, GameScoreForm } from '@/api/system/gameScore/types';
import { GameEventProjectVO, GameEventProjectQuery } from '@/api/system/gameEventProject/types';
import { GameEventVO } from '@/api/system/gameEvent/types';
import { useGameEventStore } from '@/store/modules/gameEvent';
import { ElMessageBox, ElLoading } from 'element-plus';

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

// 默认赛事信息
// const defaultEvent = ref<GameEventVO>({} as GameEventVO)
const gameEventStore = useGameEventStore();

const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 列显隐数据
const columns = ref<FieldOption[]>([
  { key: 0, label: 'ID', visible: false },
  { 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 },
  { key: 6, label: '更新时间', visible: true },
  { key: 7, label: '参赛总人数', visible: true },
  { key: 8, label: '完赛人数', visible: true },
  { key: 9, label: '未完赛人数', visible: true },
]);

// 下拉框数据
// const eventList = ref<GameEventVO[]>([]);
const projectList = ref<GameEventProjectVO[]>([]);
const classificationOptions = [
  { label: '个人项目', value: '0' },
  { label: '团体项目', value: '1' }
];

const queryFormRef = ref<ElFormInstance>();

const initFormData: GameScoreForm = {
  eventId: undefined,
  projectId: undefined,
  athleteId: undefined,
  teamId: undefined,
  individualPerformance: undefined,
  teamPerformance: undefined,
  scoreType: undefined,
  scoreRank: undefined,
  scorePoint: undefined,
  award: undefined,
  leaderPoint: undefined,
  extraPoint: undefined,
  statusFlag: undefined,
  status: undefined,
  remark: undefined
}
const data = reactive<PageData<GameScoreForm, GameScoreQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: undefined,
    classification: undefined,
    orderByColumn: '',
    isAsc: ''
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 比赛数据（默认赛事） */
const handleGameDataDefault = async () => {
  const defaultEvent = gameEventStore.defaultEventInfo;
  if (!defaultEvent) {
    proxy?.$modal.msgError('请先设置默认赛事');
    return;
  }
  handleGameData(defaultEvent);
};

// 比赛成绩按钮点击事件
const handleGameData = (row: GameEventVO) => {
  router.push({
    name: 'RankingBoardPage',
    params: { eventId: row.eventId }
  });
};

/**
 * 刷新数据
 */
const refreshData = async () => {
  await loadProjects();
};

// 打印成绩
const printScores = async () => {
  try {
    // 首先让用户输入要打印的前n名
    const { value } = await ElMessageBox.prompt(
      '请输入要打印的数据条数',
      '打印设置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[1-9]\d*$/,
        inputErrorMessage: '请输入有效的数字（大于0的整数）',
        inputPlaceholder: '例如：3',
        inputValue: '3' // 默认值
      }
    );

    const topCount = parseInt(value);
    if (topCount <= 0) {
      proxy?.$modal.msgWarning('请输入大于0的数字');
      return;
    }

    // 显示加载状态
    const loadingInstance = ElLoading.service({
      lock: true,
      text: `正在准备打印前${topCount}名数据...`,
      background: 'rgba(0, 0, 0, 0.7)'
    });

    let projectsToPrint = [];

    // 如果有选择项目，则打印选中的项目
    if (ids.value.length > 0) {
      projectsToPrint = projectList.value.filter(project =>
        ids.value.includes(project.projectId)
      );
    } else {
      // 如果没有选择项目，提示用户是否打印所有项目
      try {
        await proxy?.$modal.confirm('未选择项目，是否打印当前页面所有项目？');
        projectsToPrint = [...projectList.value];
      } catch {
        // 用户取消操作
        loadingInstance.close();
        return;
      }
    }

    if (projectsToPrint.length === 0) {
      proxy?.$modal.msgWarning('没有可打印的项目');
      loadingInstance.close();
      return;
    }

    // 为每个项目获取成绩数据
    const projectsWithScores = await Promise.all(
      projectsToPrint.map(async (project) => {
        try {
          const scoreRes = await getProjectScoreData({
            eventId: project.eventId,
            projectId: project.projectId,
            classification: project.classification,
            pageNum: 1,
            pageSize: 1000
          });

          // 获取成绩数据并补充队伍和运动员信息
          const scores = scoreRes.rows || [];

          // 按积分排序，取前n名（使用用户输入的数量）
          const sortedScores = scores
            // .filter(score => score.scorePoint && score.scorePoint > 0) // 只显示有积分的成绩
            .sort((a: any, b: any) => (b.scorePoint || 0) - (a.scorePoint || 0)) // 按积分降序排列
            .slice(0, topCount); // 使用用户输入的数量

          const scoresWithDetails = await Promise.all(
            sortedScores.map(async (score: any) => {
              let teamName = '-';
              let athleteName = '-';
              let athleteCode = '-';

              try {
                // 获取队伍信息
                if (score.teamId) {
                  const teamRes = await getGameTeam(score.teamId);
                  teamName = teamRes.data.teamName || `队伍${score.teamId}`;
                }

                // 获取运动员信息
                if (score.athleteId) {
                  const athleteRes = await getGameAthlete(score.athleteId);
                  athleteName = athleteRes.data.name || `运动员${score.athleteId}`;
                  athleteCode = athleteRes.data.athleteCode || `无`;
                }
              } catch (error) {
                console.warn('获取队伍或运动员信息失败:', error);
              }

              return {
                ...score,
                teamName,
                athleteName,
                athleteCode
              };
            })
          );

          return {
            ...project,
            scores: scoresWithDetails
          };
        } catch (error) {
          console.error(`获取项目 ${project.projectName} 成绩失败:`, error);
          return {
            ...project,
            scores: []
          };
        }
      })
    );

    // 关闭加载状态
    loadingInstance.close();

    // 构建打印HTML内容，传递topCount参数
    const printHtml = buildPrintHtml(projectsWithScores, topCount);

    // 使用 Blob 和 URL.createObjectURL 来避免弹窗拦截问题
    const blob = new Blob([printHtml], { type: 'text/html' });
    const url = URL.createObjectURL(blob);

    // 创建隐藏的 iframe 来处理打印
    const iframe = document.createElement('iframe');
    iframe.style.position = 'absolute';
    iframe.style.top = '-9999px';
    iframe.style.left = '-9999px';
    document.body.appendChild(iframe);

    iframe.onload = () => {
      try {
        // 打印完成后清理
        setTimeout(() => {
          document.body.removeChild(iframe);
          URL.revokeObjectURL(url);
        }, 1000);
      } catch (error) {
        console.error('清理打印资源失败:', error);
      }
    };

    // 在 iframe 中加载并打印
    const iframeDoc = iframe.contentDocument || iframe.contentWindow?.document;
    if (iframeDoc) {
      iframeDoc.open();
      iframeDoc.write(printHtml);
      iframeDoc.close();

      // 等待内容加载后打印
      setTimeout(() => {
        try {
          iframe.contentWindow?.focus();
          iframe.contentWindow?.print();
        } catch (error) {
          proxy?.$modal.msgError('打印失败，请检查浏览器设置');
          console.error('打印失败:', error);
        }
      }, 500);
    } else {
      proxy?.$modal.msgError('无法创建打印窗口，请检查浏览器设置');
      document.body.removeChild(iframe);
      URL.revokeObjectURL(url);
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消操作
      return;
    }
    console.error('打印失败:', error);
    proxy?.$modal.msgError('打印失败');
  }
};

/**
 * 构建打印HTML内容
 */
const buildPrintHtml = (projects: any[], topCount: number) => {
  return `
    <html>
    <head>
      <meta charset="UTF-8">
      <title>成绩打印（前${topCount}名）</title>
      <style>
        body {
          font-family: SimSun, 'Times New Roman', serif;
          padding: 20px;
          margin: 0;
          color: #333;
        }
        .print-header {
          text-align: center;
          margin-bottom: 30px;
          border-bottom: 2px solid #333;
          padding-bottom: 20px;
        }
        .print-header h1 {
          margin: 0 0 10px 0;
          font-size: 24px;
        }
        .print-header p {
          margin: 0;
          color: #666;
          font-size: 14px;
        }
        .project-section {
          margin-bottom: 40px;
          page-break-inside: avoid;
        }
        .project-title {
          font-size: 18px;
          font-weight: bold;
          margin-bottom: 15px;
          padding: 10px;
          background: #f5f5f5;
          border-left: 4px solid #409eff;
        }
        .title-label {
          font-weight: bold;
        }
        .score-table {
          width: 100%;
          border-collapse: collapse;
          margin-bottom: 20px;
        }
        .score-table th,
        .score-table td {
          border: 1px solid #ddd;
          padding: 8px 12px;
          text-align: center;
        }
        .score-table th {
          background: #f8f9fa;
          font-weight: bold;
        }
        .rank-1 { background-color: #fff7e6; }
        .rank-2 { background-color: #f6ffed; }
        .rank-3 { background-color: #f0f9ff; }
        
        /* 打印样式 - 优化打印预览和实际打印效果一致性 */
        @media print {
          * {
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
            background: transparent !important;
            box-shadow: none !important;
            text-shadow: none !important;
          }
          
          body {
            font-family: SimSun, "Times New Roman", serif !important;
            font-size: 12pt !important;
            line-height: 1.4 !important;
            color: #000 !important;
            padding: 0 !important;
          }
          
          .print-container {
            padding: 0 !important;
            max-width: 100% !important;
          }
          
          .print-content {
            width: 100% !important;
            max-width: 100% !important;
          }
          
          .project-section {
            page-break-inside: avoid !important;
            page-break-after: auto !important;
          }
          
          .score-table {
            width: 100% !important;
            border-collapse: collapse !important;
            font-size: 11pt !important;
            page-break-inside: avoid !important;
          }
          
          .score-table th,
          .score-table td {
            border: 1px solid #000 !important;
            padding: 5pt !important;
            text-align: center !important;
            vertical-align: middle !important;
          }
          
          .score-table th {
            background-color: #f8f9fa !important;
            color: #000 !important;
            font-weight: bold !important;
          }
          
          .score-table thead {
            display: table-header-group !important; /* 确保表头在每页重复 */
          }
          
          .score-table tbody {
            display: table-row-group !important;
          }
          
          /* 确保排名样式在打印中正确显示 */
          .rank-1 {
            background-color: #fff7e6 !important;
            color: #000 !important;
          }
          
          .rank-2 {
            background-color: #f6ffed !important;
            color: #000 !important;
          }
          
          .rank-3 {
            background-color: #f0f9ff !important;
            color: #000 !important;
          }
          
          /* 设置页面边距 */
          @page {
            margin: 20mm !important;
            size: A4 !important;
          }
          
          /* 避免第一页顶部和最后一页底部有太多空白 */
          .print-header {
            page-break-after: avoid !important;
            border-bottom: 2px solid #000 !important;
            margin-bottom: 30pt !important;
            padding-bottom: 20pt !important;
          }
          
          /* 确保字体大小在打印中保持一致 */
          h1 {
            font-size: 18pt !important;
            margin-bottom: 10pt !important;
            color: #000 !important;
          }
          
          .project-title {
            font-size: 14pt !important;
            margin-bottom: 10pt !important;
            padding: 8pt !important;
            border-left: 4px solid #000 !important;
            background-color: #f5f5f5 !important;
            color: #000 !important;
          }
          
          .title-label {
            color: #000 !important;
          }
          
          /* 确保在IE浏览器中也能正常打印 */
          @media print and (-ms-high-contrast: none), print and (-ms-high-contrast: active) {
            * {
              color-adjust: exact !important;
            }
          }
        }
      </style>
    </head>
    <body>
      <div class="print-header">
        <h1>赛事管理系统 - 成绩打印（前${topCount}名）</h1>
        <p>打印时间: ${new Date().toLocaleString('zh-CN')}</p>
      </div>
      
      ${projects.map(project => `
        <div class="project-section">
          <div class="project-title">
            <span class="title-label">${project.projectId} </span> 
            <span class="title-label">${getProjectTypeName(project.projectType)}-${project.projectName}</span> 
          </div>
          <table class="score-table">
            <thead>
              <tr>
                <th class="title-label">类别</th>
                <th class="title-label">名次</th>
                <th class="title-label">队伍</th>
                <th class="title-label">运动员编号</th>
                <th class="title-label">姓名</th>
                <th class="title-label">成绩</th>
                <th class="title-label">积分</th>
              </tr>
            </thead>
            <tbody>
              ${project.scores.slice(0, topCount).map((score: any, index: number) => `
                <tr>
                  <td>${score.classification === '0' ? '个人项目' : '团体项目'}</td>
                  <td>第${Number(index) + 1}名</td>
                  <td>${score.teamName || '-'}</td>
                  <td>${score.athleteCode || '-'}</td>
                  <td>${score.athleteName || '-'}</td>
                  <td >${score.classification === '0' ? formatScore(score.individualPerformance) : formatScore(score.teamPerformance)}</td>
                  <td>${score.scorePoint || 0}</td>
                </tr>
              `).join('')}
            </tbody>
          </table>
        </div>
      `).join('')}
    </body>
    </html>
  `;
};

/**
 * 格式化成绩显示
 */
const formatScore = (score: number | string) => {
  if (score === null || score === undefined || score === '') return '-';
  return score.toString();
};

/**
 * 获取项目类型名称
 */
const getProjectTypeName = (type: string) => {
  if (!game_project_type.value || !type) return '未知';

  const typeItem = game_project_type.value.find((item: any) => item.value === type);
  return typeItem ? typeItem.label : '未知';
};

/**
 * 获取状态文本
 */
const getStatusText = (row: any) => {
  const totalParticipants = row.totalParticipants || 0;
  const completedParticipants = row.completedParticipants || 0;
  
  // 如果完赛人/队数等于参赛总人/队数，显示完赛
  if (totalParticipants > 0 && completedParticipants === totalParticipants) {
    return '完赛';
  }
  
  // 否则显示进行中
  return '进行中';
};

/**
 * 获取状态标签类型
 */
const getStatusType = (row: any) => {
  const totalParticipants = row.totalParticipants || 0;
  const completedParticipants = row.completedParticipants || 0;
  
  // 如果完赛人/队数等于参赛总人/队数，显示成功状态
  if (totalParticipants > 0 && completedParticipants === totalParticipants) {
    return 'success';
  }
  
  // 否则显示警告状态
  return 'warning';
};

const exportScoresNames = async () => {
  // 获取默认赛事ID
  const event = gameEventStore.defaultEventInfo;
  const eventId = event?.eventId;

  if (!eventId) {
    proxy?.$modal.msgWarning('未指定赛事，无法导出');
    return;
  }

  try {
    // 弹出输入框询问名次
    const { value } = await ElMessageBox.prompt(
      '请输入导出各项目的前几名成绩（留空或输入0则导出全部）',
      '导出成绩',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d*$/,
        inputErrorMessage: '请输入有效的数字',
        inputPlaceholder: '导出前N名，例如：3',
      }
    );

    const topN = value ? parseInt(value) : 0;
    
    // 构造请求参数
    const params = {
      eventId: eventId,
      topN: topN > 0 ? topN : undefined,
      projectIds: ids.value.length > 0 ? ids.value.join(',') : undefined
    };

    // 文件名动态调整
    let fileName = `${gameEventStore.defaultEventInfo?.eventCode || ''}_成绩详情表`;
    if (topN > 0) fileName += `_前${topN}名`;
    if (ids.value.length == 0) fileName += `_全部项目`;
    fileName += '.xlsx';

    // 执行导出
    proxy?.download(
      'system/gameScore/exportScoresDetail',
      params,
      fileName
    );
  } catch (error) {
    // 用户点击取消或关闭弹窗，不做处理
  }
};

/**
 * 加载项目列表
 */
const loadProjects = async () => {
  loading.value = true;
  try {
    const res = await listGameEventProject(queryParams.value);
    projectList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    proxy?.$modal.msgError('加载项目列表失败');
  } finally {
    loading.value = false;
  }
};

/**
 * 分页处理
 */
const handlePagination = (paginationData: { page: number, limit: number }) => {
  queryParams.value.pageNum = paginationData.page;
  queryParams.value.pageSize = paginationData.limit;
  loadProjects();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  loadProjects();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 保留默认赛事ID
  // queryParams.value.eventId = defaultEvent.value?.eventId;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: GameScoreVO[]) => {
  ids.value = selection.map(item => item.projectId); // 使用eventId作为标识
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

const navigateToEditPage = (row: GameEventProjectVO) => {
  const projectId = row.projectId;
  const projectName = row.projectName;
  const projectType = row.projectType;
  const eventId = row.eventId;
  const classification = row.classification;
  router.push({
    name: 'GameScoreEdit',
    params: { projectId, projectName, projectType, eventId, classification }
  });
};

onMounted(() => {
  loadProjects();
});
</script>



