<template>
  <div class="score-management-container">
    <el-card shadow="hover">
      <div class="page-header">
        <h2 class="page-title">评分管理</h2>
      </div>

      <!-- 查询栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="所属赛事">
          <el-select
            v-model="searchForm.competitionId"
            placeholder="请选择赛事"
            clearable
            filterable
            size="small"
            style="width: 200px"
            @change="handleCompetitionChange"
          >
            <el-option
              v-for="item in competitionOptions"
              :key="item.id"
              :label="item.competitionName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="比赛项目">
          <el-select
            v-model="searchForm.projectId"
            placeholder="请选择比赛项目"
            clearable
            filterable
            size="small"
            style="width: 200px"
            @change="handleSearch"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="比赛人员">
          <el-input
            v-model="searchForm.playerName"
            placeholder="搜索选手姓名"
            clearable
            size="small"
            style="width: 180px"
          >
            <template #prefix>
              <i class="el-input__icon el-icon-search"></i>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
          <el-button size="small" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        size="small"
        style="width: 100%"
        :max-height="600"
      >
        <el-table-column type="index" label="序号" width="60" align="center" fixed></el-table-column>
        <el-table-column prop="projectName" label="比赛项目" min-width="180" show-overflow-tooltip fixed></el-table-column>
        <el-table-column prop="venueName" label="场地" width="120" align="center" fixed></el-table-column>
        <el-table-column prop="playerName" label="比赛人员" width="120" align="center" fixed></el-table-column>

        <!-- 动态裁判评分列 -->
        <el-table-column
          v-for="(judge, index) in judgeColumns"
          :key="'judge-' + index"
          :label="'裁判' + (index + 1) + '分数'"
          width="110"
          align="center"
        >
          <template #default="scope">
            <span :class="getScoreClass(scope.row.judgeScores[index])">
              {{ formatScore(scope.row.judgeScores[index]) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="总裁判分数" width="120" align="center" fixed="right">
          <template #default="scope">
            <span class="total-score">{{ formatScore(scope.row.totalScore) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.size"
        layout="total, sizes, prev, pager, next"
        :total="pagination.total"
        small
      ></el-pagination>
    </el-card>

    <!-- 评分详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="评分详情"
      width="700px"
      :close-on-click-modal="false"
    >
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="比赛项目">{{ currentDetail.projectName }}</el-descriptions-item>
          <el-descriptions-item label="场地">{{ currentDetail.venueName }}</el-descriptions-item>
          <el-descriptions-item label="选手姓名">{{ currentDetail.playerName }}</el-descriptions-item>
          <el-descriptions-item label="队伍">{{ currentDetail.teamName }}</el-descriptions-item>
          <el-descriptions-item label="身份证">{{ currentDetail.idCard }}</el-descriptions-item>
          <el-descriptions-item label="编号">{{ currentDetail.playerNo }}</el-descriptions-item>
        </el-descriptions>

        <div class="score-section">
          <h4>裁判评分明细</h4>
          <el-table :data="currentDetail.scoreDetails" border size="small" style="margin-top: 10px">
            <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
            <el-table-column prop="judgeName" label="裁判姓名" align="center"></el-table-column>
            <el-table-column prop="score" label="评分" align="center" width="100">
              <template #default="scope">
                <span class="score-value">{{ formatScore(scope.row.score) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="deductions" label="扣分项" show-overflow-tooltip></el-table-column>
            <el-table-column prop="note" label="备注" show-overflow-tooltip></el-table-column>
            <el-table-column prop="scoreTime" label="评分时间" width="150"></el-table-column>
          </el-table>

          <div class="total-score-display">
            <span class="label">总分：</span>
            <span class="value">{{ formatScore(currentDetail.totalScore) }}</span>
            <div class="calculation-note">
              <span v-if="currentDetail.judgeScores.length > 2">
                (去掉最高分和最低分后的平均分)
              </span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getScoreList, getAthleteScores } from '@/api/martial/score'
import { getProjectList } from '@/api/martial/project'
import { getCompetitionList } from '@/api/martial/competition'
import { getParticipantDetail } from '@/api/martial/participant'

export default {
  name: 'ScoreManagement',
  data() {
    return {
      loading: false,
      searchForm: {
        competitionId: null,
        projectId: null,
        venueId: null,
        playerName: ''
      },
      competitionOptions: [],
      projectOptions: [],
      venueOptions: [],
      scoreList: [],
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      judgeColumns: Array(5).fill(null), // 5个裁判
      detailDialogVisible: false,
      currentDetail: null
    }
  },
  mounted() {
    this.loadCompetitions()
    this.loadScoreList()
  },
  methods: {
    // 加载赛事列表
    loadCompetitions() {
      getCompetitionList(1, 100, {})
        .then(res => {
          const responseData = res.data?.data
          if (responseData && responseData.records) {
            this.competitionOptions = responseData.records.map(item => ({
              id: item.id,
              competitionName: item.competitionName
            }))
          }
        })
        .catch(err => {
          console.error('加载赛事列表失败', err)
        })
    },

    // 加载项目列表
    loadProjects() {
      if (!this.searchForm.competitionId) {
        this.projectOptions = []
        return
      }

      getProjectList(1, 100, { competitionId: this.searchForm.competitionId })
        .then(res => {
          const responseData = res.data?.data
          if (responseData && responseData.records) {
            this.projectOptions = responseData.records.map(item => ({
              id: item.id,
              projectName: item.projectName
            }))
          }
        })
        .catch(err => {
          console.error('加载项目列表失败', err)
        })
    },

    // 加载评分列表
    async loadScoreList() {
      this.loading = true
      const params = {}

      if (this.searchForm.competitionId) {
        params.competitionId = this.searchForm.competitionId
      }
      if (this.searchForm.projectId) {
        params.projectId = this.searchForm.projectId
      }
      if (this.searchForm.venueId) {
        params.venueId = this.searchForm.venueId
      }

      try {
        const res = await getScoreList(this.pagination.current, this.pagination.size, params)
        console.log('评分列表返回数据:', res)
        
        const responseData = res.data?.data
        if (responseData && responseData.records) {
          // 过滤掉 projectId 为 null 的无效记录
          const validScores = responseData.records.filter(score => {
            if (!score.projectId) {
              console.warn('发现无效评分记录（projectId为空）:', score)
              return false
            }
            return true
          })
          
          this.scoreList = validScores

          // 补充关联数据（项目名称、场地名称、选手名称）
          await this.enrichScoreData(validScores)

          // 按选手分组评分数据
          this.processScoreData(this.scoreList)

          this.pagination.total = this.tableData.length
        }
      } catch (err) {
        console.error('加载评分列表失败', err)
        this.$message.error('加载评分列表失败')
      } finally {
        this.loading = false
      }
    },

    // 补充评分数据中缺失的关联字段
    async enrichScoreData(scores) {
      if (!scores || scores.length === 0) return

      // 收集所有唯一的 ID
      const projectIds = new Set()
      const athleteIds = new Set()

      scores.forEach(score => {
        if (score.projectId) projectIds.add(score.projectId)
        if (score.athleteId) athleteIds.add(score.athleteId)
      })

      // 批量查询项目信息
      const projectMap = new Map()
      if (projectIds.size > 0) {
        try {
          // 获取所有项目
          const projectRes = await getProjectList(1, 1000, {})
          const projectData = projectRes.data?.data
          if (projectData && projectData.records) {
            projectData.records.forEach(project => {
              projectMap.set(project.id, project.projectName)
            })
          }
        } catch (err) {
          console.error('加载项目列表失败', err)
        }
      }

      // 批量查询选手信息
      const athleteMap = new Map()
      if (athleteIds.size > 0) {
        try {
          // 逐个查询选手详情（因为没有批量接口）
          const athletePromises = Array.from(athleteIds).map(id =>
            getParticipantDetail(id).catch(err => {
              console.error(`查询选手 ${id} 失败:`, err)
              return null
            })
          )
          const athleteResults = await Promise.all(athletePromises)
          athleteResults.forEach(res => {
            if (res && res.data?.data) {
              const athlete = res.data.data
              athleteMap.set(athlete.id, {
                playerName: athlete.playerName,
                teamName: athlete.teamName || athlete.organization,
                idCard: athlete.idCard,
                playerNo: athlete.orderNum ? `NO-${athlete.orderNum}` : ''
              })
            }
          })
        } catch (err) {
          console.error('加载选手信息失败', err)
        }
      }

      // 为每条评分记录补充关联字段
      scores.forEach(score => {
        // 补充项目名称
        if (score.projectId && projectMap.has(score.projectId)) {
          score.projectName = projectMap.get(score.projectId)
        }

        // 补充选手信息
        if (score.athleteId && athleteMap.has(score.athleteId)) {
          const athleteInfo = athleteMap.get(score.athleteId)
          score.playerName = athleteInfo.playerName
          score.teamName = athleteInfo.teamName
          score.idCard = athleteInfo.idCard
          score.playerNo = athleteInfo.playerNo
        }

        // 场地名称暂时使用场地ID显示（因为没有场地API）
        if (score.venueId) {
          score.venueName = `场地${score.venueId}`
        }
      })

      console.log('数据补充完成，示例记录:', scores[0])
    },

    // 处理评分数据，按选手分组
    processScoreData(scores) {
      const athleteMap = new Map()

      scores.forEach(score => {
        // 确保 projectId 存在
        if (!score.projectId) {
          console.warn('跳过无效评分记录:', score)
          return
        }
        
        const key = `${score.athleteId}-${score.projectId}`
        if (!athleteMap.has(key)) {
          athleteMap.set(key, {
            id: score.athleteId,
            athleteId: score.athleteId,
            projectId: score.projectId,
            projectName: score.projectName || '',
            venueName: score.venueName || '',
            playerName: score.playerName || '',
            teamName: score.teamName || '',
            idCard: score.idCard || '',
            playerNo: score.playerNo || '',
            judgeScores: [],
            scoreDetails: [],
            totalScore: 0
          })
        }

        const athlete = athleteMap.get(key)
        athlete.judgeScores.push(parseFloat(score.score) || 0)
        athlete.scoreDetails.push({
          judgeName: score.judgeName || '未知裁判',
          score: parseFloat(score.score) || 0,
          deductions: score.deductionItemsText || '无',
          note: score.note || '',
          scoreTime: score.scoreTime || score.createTime || ''
        })
      })

      // 计算总分（去掉最高最低分后的平均分）
      this.tableData = Array.from(athleteMap.values()).map(athlete => {
        if (athlete.judgeScores.length > 0) {
          athlete.totalScore = this.calculateFinalScore(athlete.judgeScores)
        }
        return athlete
      })

      // 根据选手姓名过滤
      if (this.searchForm.playerName) {
        this.tableData = this.tableData.filter(item =>
          item.playerName.includes(this.searchForm.playerName)
        )
      }

      // 更新裁判列数
      const maxJudges = Math.max(...this.tableData.map(item => item.judgeScores.length), 0)
      this.judgeColumns = Array(maxJudges).fill(null)
    },

    /**
     * 计算最终得分
     * 规则：
     * - 如果裁判数 <= 2，直接取平均值
     * - 如果裁判数 > 2，去掉最高分和最低分后取平均值
     */
    calculateFinalScore(scores) {
      if (!scores || scores.length === 0) {
        return 0
      }

      // 如果只有1-2个裁判，直接取平均值
      if (scores.length <= 2) {
        const sum = scores.reduce((a, b) => a + b, 0)
        return sum / scores.length
      }

      // 3个及以上裁判，去掉最高分和最低分
      const sortedScores = [...scores].sort((a, b) => a - b)
      
      // 去掉第一个（最低分）和最后一个（最高分）
      const validScores = sortedScores.slice(1, -1)
      
      // 计算平均值
      const sum = validScores.reduce((a, b) => a + b, 0)
      return sum / validScores.length
    },

    // 查询
    handleSearch() {
      this.pagination.current = 1
      this.loadScoreList()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        competitionId: null,
        projectId: null,
        venueId: null,
        playerName: ''
      }
      this.projectOptions = []
      this.handleSearch()
    },

    // 赛事变化
    handleCompetitionChange() {
      this.searchForm.projectId = null
      this.projectOptions = []
      this.loadProjects()
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadScoreList()
    },

    // 当前页变化
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadScoreList()
    },

    // 查看详情
    handleViewDetail(row) {
      this.currentDetail = { ...row }
      this.detailDialogVisible = true
    },

    // 格式化分数
    formatScore(score) {
      if (score === null || score === undefined) {
        return '-'
      }
      return Number(score).toFixed(3)
    },

    // 分数样式
    getScoreClass(score) {
      if (!score) return ''
      if (score >= 9.0) return 'high-score'
      if (score >= 8.5) return 'medium-score'
      return 'low-score'
    }
  }
}
</script>

<style lang="scss" scoped>
.score-management-container {
  min-height: 100%;
  padding: 15px;
  background: #fff;

  .page-header {
    margin-bottom: 15px;

    .page-title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
    }
  }

  .search-form {
    margin-bottom: 15px;

    ::v-deep(.el-form-item__label) {
      font-weight: 500;
    }
  }

  .high-score {
    color: #67c23a;
    font-weight: 600;
  }

  .medium-score {
    color: #e6a23c;
    font-weight: 600;
  }

  .low-score {
    color: #f56c6c;
    font-weight: 600;
  }

  .total-score {
    color: #1b7c5e;
    font-weight: 700;
    font-size: 14px;
  }

  .pagination {
    margin-top: 15px;
    text-align: right;
  }

  .detail-content {
    .score-section {
      margin-top: 20px;

      h4 {
        margin: 0 0 10px;
        font-size: 14px;
        color: #333;
      }

      .score-value {
        color: #1b7c5e;
        font-weight: 600;
      }

      .total-score-display {
        margin-top: 15px;
        padding: 15px;
        background: linear-gradient(135deg, #e8f5f2 0%, #f0f9f6 100%);
        border-radius: 8px;
        text-align: center;

        .label {
          font-size: 16px;
          color: #666;
          margin-right: 10px;
        }

        .value {
          font-size: 28px;
          font-weight: 700;
          color: #1b7c5e;
        }

        .calculation-note {
          margin-top: 8px;
          font-size: 12px;
          color: #999;
        }
      }
    }
  }
}
</style>
