<template>
  <div class="print-container">
    <!-- 打印按钮 -->
    <div class="print-actions" v-if="!isPrinting">
      <el-button type="primary" @click="printPage">打印</el-button>
      <el-button @click="goBack">返回</el-button>
    </div>

    <!-- 打印内容 -->
    <div class="print-content" ref="printContent">
      <div class="print-header">
        <h1>赛事管理系统 - 成绩打印（前{{ topCount }}名）</h1>
        <p>打印时间: {{ printTime }}</p>
      </div>

      <!-- 项目成绩表格 -->
      <div v-for="project in projectScores" :key="project.projectId" class="project-section">
        <div class="project-title">
          <span class="title-label">{{ project.projectId }} </span> 
          <span class="title-label">{{ project.projectTypeName }}-{{ 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>
            <tr v-for="(score, index) in project.scores.slice(0, topCount)" :key="score.scoreId" >
              <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>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="GameScorePrint">
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getProjectScoreData } from '@/api/system/gameScore'
import { getGameEventProject } from '@/api/system/gameEventProject'
import { GameScoreVO } from '@/api/system/gameScore/types'
import { GameEventProjectVO } from '@/api/system/gameEventProject/types'
import { ElMessage } from 'element-plus'

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

const route = useRoute()
const router = useRouter()

// 响应式数据
const isPrinting = ref(false)
const printContent = ref<HTMLElement>()
const projectScores = ref<any[]>([])
const loading = ref(false)
const topCount = ref(3) // 默认值为3

// 计算属性
const printTime = computed(() => {
  return new Date().toLocaleString('zh-CN')
})

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

// 获取项目成绩数据
const loadProjectScores = async () => {
  try {
    loading.value = true
    
    // 从路由参数获取项目ID和topCount
    const projectId = route.params.projectId as string
    const topCountParam = route.params.topCount as string
    
    // 如果有topCount参数，则使用它，否则保持默认值
    if (topCountParam) {
      const count = parseInt(topCountParam)
      if (count > 0) {
        topCount.value = count
      }
    }
    
    if (!projectId) {
      ElMessage.error('项目ID不能为空')
      return
    }

    // 获取项目信息
    const projectRes = await getGameEventProject(projectId)
    const project = projectRes.data

    // 获取项目成绩数据
    const scoreRes = await getProjectScoreData({
      eventId: project.eventId,
      projectId: project.projectId,
      classification: project.classification,
      pageNum: 1,
      pageSize: 1000 // 获取所有成绩
    })
    // 处理数据格式
    const scores = scoreRes.rows || []
    const sortedScores = scores.sort((a: GameScoreVO, b: GameScoreVO) => {
      return (a.scoreRank || 0) - (b.scoreRank || 0)
    })

    // 构建项目成绩数据结构
    projectScores.value = [{
      projectId: project.projectId,
      projectName: project.projectName,
      projectTypeName: getProjectTypeName(project.projectType),
      // groupTypeName: getGroupTypeName(project.groupType),
      classification: project.classification,
      scores: sortedScores.map(score => ({
        ...score,
        teamName: score.teamId,
        athleteName: score.name,
        athleteCode: score.athleteCode,
      }))
    }]

  } catch (error) {
    console.error('加载项目成绩失败:', error)
    ElMessage.error('加载项目成绩失败')
  } finally {
    loading.value = false
  }
}

// 获取项目类型名称
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 printPage = () => {
  isPrinting.value = true
  
  // 等待DOM更新后执行打印
  nextTick(() => {
    window.print()
    isPrinting.value = false
  })
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 页面加载时获取数据
onMounted(() => {
  loadProjectScores()
})
</script>

<style scoped>
.print-container {
  padding: 20px;
  background: white;
}

.print-actions {
  margin-bottom: 20px;
  text-align: center;
}

.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;
  color: #333;
}

.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 {
  /* color: #f56c6c; */
  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;
  color: #333;
}

.score-table td {
  color: #333;
}

.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;
  }
  
  .print-actions {
    display: none !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;
  }
  
  .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;
  }
  
  /* 确保排名样式在打印中正确显示 */
  .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;
  }
  
  /* 确保表格不被截断 */
  .score-table {
    page-break-inside: avoid !important;
  }
  
  .score-table thead {
    display: table-header-group !important; /* 确保表头在每页重复 */
  }
  
  .score-table tbody {
    display: table-row-group !important;
  }
  
  /* 隐藏可能干扰打印的元素 */
  .no-print {
    display: none !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;
  }
  
  /* 确保在IE浏览器中也能正常打印 */
  @media print and (-ms-high-contrast: none), print and (-ms-high-contrast: active) {
    * {
      color-adjust: exact !important;
    }
  }
}
</style> 

