<template>
  <div class="result-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="赛事">
          <el-select
            v-model="queryParams.competitionId"
            placeholder="请选择赛事"
            clearable
            filterable
            style="width: 200px"
            @change="handleCompetitionChange"
          >
            <el-option
              v-for="item in competitionList"
              :key="item.id"
              :label="item.competitionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目">
          <el-select
            v-model="queryParams.projectId"
            placeholder="请选择项目"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="item in projectList"
              :key="item.id"
              :label="item.projectName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选手姓名">
          <el-input
            v-model="queryParams.athleteName"
            placeholder="请输入选手姓名"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="团队名称">
          <el-input
            v-model="queryParams.teamName"
            placeholder="请输入团队名称"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="是否最终成绩">
          <el-select
            v-model="queryParams.isFinal"
            placeholder="请选择"
            clearable
            style="width: 130px"
          >
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
              <el-icon :size="30"><User /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ statistics.totalCount || 0 }}</div>
              <div class="stats-label">总参赛人数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%)">
              <el-icon :size="30"><Finished /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ statistics.calculatedCount || 0 }}</div>
              <div class="stats-label">已计算成绩</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)">
              <el-icon :size="30"><Trophy /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ statistics.medalCount || 0 }}</div>
              <div class="stats-label">已分配奖牌</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%)">
              <el-icon :size="30"><Document /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ statistics.publishedCount || 0 }}</div>
              <div class="stats-label">已发布成绩</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 工具栏 -->
    <el-card shadow="never" class="toolbar-card">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button
            type="primary"
            :icon="Operation"
            :disabled="!selection.length"
            @click="handleBatchCalculate"
          >
            批量计算成绩
          </el-button>
          <el-button
            type="success"
            :icon="Sort"
            :disabled="!queryParams.projectId"
            @click="handleAutoRanking"
          >
            自动排名
          </el-button>
          <el-button
            type="warning"
            :icon="Medal"
            :disabled="!queryParams.projectId"
            @click="handleAllocateMedals"
          >
            分配奖牌
          </el-button>
          <el-button
            type="info"
            :icon="Promotion"
            :disabled="!selection.length"
            @click="handlePublish"
          >
            发布成绩
          </el-button>
          <el-button
            :icon="Remove"
            :disabled="!selection.length"
            @click="handleUnpublish"
          >
            撤销发布
          </el-button>
          <el-button
            type="danger"
            :icon="Download"
            @click="handleExport"
          >
            导出成绩单
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-tooltip content="刷新" placement="top">
            <el-button circle :icon="Refresh" @click="fetchData" />
          </el-tooltip>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="ranking" label="排名" width="80" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.ranking === 1" type="danger" effect="dark">🥇 {{ row.ranking }}</el-tag>
            <el-tag v-else-if="row.ranking === 2" type="warning" effect="dark">🥈 {{ row.ranking }}</el-tag>
            <el-tag v-else-if="row.ranking === 3" type="success" effect="dark">🥉 {{ row.ranking }}</el-tag>
            <span v-else>{{ row.ranking || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="athleteName" label="选手姓名" width="120" />
        <el-table-column prop="teamName" label="团队名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="projectName" label="项目" min-width="150" show-overflow-tooltip />
        <el-table-column prop="totalScore" label="总分" width="100" align="center">
          <template #default="{ row }">
            {{ row.totalScore !== null ? row.totalScore.toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="highestScore" label="最高分" width="100" align="center">
          <template #default="{ row }">
            <span style="color: #f56c6c">{{ row.highestScore !== null ? row.highestScore.toFixed(2) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lowestScore" label="最低分" width="100" align="center">
          <template #default="{ row }">
            <span style="color: #909399">{{ row.lowestScore !== null ? row.lowestScore.toFixed(2) : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="validScoreCount" label="有效评分数" width="110" align="center" />
        <el-table-column prop="difficultyCoefficient" label="难度系数" width="100" align="center">
          <template #default="{ row }">
            ×{{ row.difficultyCoefficient || 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="finalScore" label="最终成绩" width="110" align="center">
          <template #default="{ row }">
            <span v-if="row.finalScore !== null" style="color: #409eff; font-weight: bold; font-size: 16px">
              {{ row.finalScore.toFixed(2) }}
            </span>
            <span v-else style="color: #909399">未计算</span>
          </template>
        </el-table-column>
        <el-table-column prop="medal" label="奖牌" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.medal === 'gold'" type="danger" effect="dark">🏅 金牌</el-tag>
            <el-tag v-else-if="row.medal === 'silver'" type="warning" effect="dark">🥈 银牌</el-tag>
            <el-tag v-else-if="row.medal === 'bronze'" type="success" effect="dark">🥉 铜牌</el-tag>
            <span v-else style="color: #909399">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="isPublished" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.isPublished === 1" type="success">已发布</el-tag>
            <el-tag v-else type="info">未发布</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="160" align="center">
          <template #default="{ row }">
            {{ row.publishTime ? formatDate(row.publishTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" :icon="View" @click="handleView(row)">
              查看详情
            </el-button>
            <el-button link type="success" :icon="Edit" @click="handleCalculate(row)">
              重新计算
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchData"
          @current-change="fetchData"
        />
      </div>
    </el-card>

    <!-- 成绩详情弹窗 -->
    <el-dialog v-model="detailVisible" title="成绩详情" width="900px">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="选手姓名">{{ detailData.athleteName }}</el-descriptions-item>
        <el-descriptions-item label="团队名称">{{ detailData.teamName }}</el-descriptions-item>
        <el-descriptions-item label="项目">{{ detailData.projectName }}</el-descriptions-item>
        <el-descriptions-item label="排名">
          <el-tag v-if="detailData.ranking === 1" type="danger" effect="dark">🥇 第1名</el-tag>
          <el-tag v-else-if="detailData.ranking === 2" type="warning" effect="dark">🥈 第2名</el-tag>
          <el-tag v-else-if="detailData.ranking === 3" type="success" effect="dark">🥉 第3名</el-tag>
          <span v-else>第{{ detailData.ranking }}名</span>
        </el-descriptions-item>
        <el-descriptions-item label="总分">{{ detailData.totalScore?.toFixed(2) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="最终成绩">
          <span style="color: #409eff; font-weight: bold; font-size: 18px">
            {{ detailData.finalScore?.toFixed(2) || '-' }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="最高分">
          <span style="color: #f56c6c">{{ detailData.highestScore?.toFixed(2) || '-' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="最低分">
          <span style="color: #909399">{{ detailData.lowestScore?.toFixed(2) || '-' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="有效评分数">{{ detailData.validScoreCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="难度系数">×{{ detailData.difficultyCoefficient || 1 }}</el-descriptions-item>
        <el-descriptions-item label="奖牌">
          <el-tag v-if="detailData.medal === 'gold'" type="danger" effect="dark">🏅 金牌</el-tag>
          <el-tag v-else-if="detailData.medal === 'silver'" type="warning" effect="dark">🥈 银牌</el-tag>
          <el-tag v-else-if="detailData.medal === 'bronze'" type="success" effect="dark">🥉 铜牌</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="发布状态">
          <el-tag v-if="detailData.isPublished === 1" type="success">已发布</el-tag>
          <el-tag v-else type="info">未发布</el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider />

      <h4>评分明细</h4>
      <el-table :data="detailData.scoreList" border size="small">
        <el-table-column prop="judgeName" label="裁判" width="120" />
        <el-table-column prop="score" label="评分" width="100" align="center">
          <template #default="{ row }">
            {{ row.score?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="deductionPoints" label="扣分" width="100" align="center">
          <template #default="{ row }">
            <span style="color: #f56c6c">-{{ row.deductionPoints?.toFixed(2) || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isExcluded" label="是否去除" width="100" align="center">
          <template #default="{ row }">
            <el-tag v-if="row.isExcluded" type="info" size="small">已去除</el-tag>
            <el-tag v-else type="success" size="small">有效</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="scoreTime" label="评分时间" width="160" align="center">
          <template #default="{ row }">
            {{ formatDate(row.scoreTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
      </el-table>
    </el-dialog>

    <!-- 奖牌分配弹窗 -->
    <el-dialog v-model="medalDialogVisible" title="奖牌分配" width="500px">
      <el-form :model="medalForm" label-width="100px">
        <el-form-item label="金牌数量">
          <el-input-number v-model="medalForm.goldCount" :min="0" :max="20" />
        </el-form-item>
        <el-form-item label="银牌数量">
          <el-input-number v-model="medalForm.silverCount" :min="0" :max="20" />
        </el-form-item>
        <el-form-item label="铜牌数量">
          <el-input-number v-model="medalForm.bronzeCount" :min="0" :max="20" />
        </el-form-item>
        <el-alert type="info" :closable="false" show-icon>
          <template #title>
            将根据当前项目的排名自动分配奖牌
          </template>
        </el-alert>
      </el-form>
      <template #footer>
        <el-button @click="medalDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="medalLoading" @click="handleMedalSubmit">
          确认分配
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  View,
  Edit,
  Operation,
  Sort,
  Medal,
  Promotion,
  Remove,
  Download,
  User,
  Finished,
  Trophy,
  Document
} from '@element-plus/icons-vue'
import {
  getResultList,
  calculateResult,
  batchCalculateResults,
  autoRanking,
  allocateMedals,
  publishResult,
  unpublishResult,
  getResultDetail,
  getResultStatistics,
  exportResults
} from '@/api/martial/result'
import { getCompetitionList } from '@/api/martial/competition'
import { getProjectsByCompetition } from '@/api/martial/project'
import dayjs from 'dayjs'

// 数据定义
const loading = ref(false)
const medalLoading = ref(false)
const tableData = ref([])
const total = ref(0)
const selection = ref([])
const competitionList = ref([])
const projectList = ref([])
const detailVisible = ref(false)
const medalDialogVisible = ref(false)
const detailData = ref({})
const statistics = ref({
  totalCount: 0,
  calculatedCount: 0,
  medalCount: 0,
  publishedCount: 0
})

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  competitionId: '',
  projectId: '',
  athleteName: '',
  teamName: '',
  isFinal: ''
})

// 奖牌分配表单
const medalForm = reactive({
  goldCount: 1,
  silverCount: 2,
  bronzeCount: 3
})

// 加载赛事列表
const loadCompetitionList = async () => {
  try {
    const res = await getCompetitionList(1, 1000, { status: 1 })
    if (res.data && res.data.records) {
      competitionList.value = res.data.records
    }
  } catch (error) {
    console.error('加载赛事列表失败:', error)
  }
}

// 赛事变化
const handleCompetitionChange = async (competitionId) => {
  queryParams.projectId = ''
  projectList.value = []

  if (competitionId) {
    try {
      const res = await getProjectsByCompetition(competitionId)
      if (res.data) {
        projectList.value = res.data
      }
    } catch (error) {
      console.error('加载项目列表失败:', error)
    }
  }
}

// 加载统计数据
const loadStatistics = async () => {
  if (!queryParams.projectId && !queryParams.competitionId) return

  try {
    const res = await getResultStatistics({
      projectId: queryParams.projectId,
      competitionId: queryParams.competitionId
    })
    if (res.data) {
      statistics.value = res.data
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 查询数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getResultList(
      queryParams.current,
      queryParams.size,
      queryParams
    )
    if (res.data) {
      tableData.value = res.data.records || []
      total.value = res.data.total || 0
    }
    await loadStatistics()
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.current = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(queryParams, {
    current: 1,
    size: 10,
    competitionId: '',
    projectId: '',
    athleteName: '',
    teamName: '',
    isFinal: ''
  })
  projectList.value = []
  fetchData()
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getResultDetail(row.id)
    if (res.data) {
      detailData.value = res.data
      detailVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

// 计算单个成绩
const handleCalculate = async (row) => {
  try {
    await calculateResult({ resultId: row.id })
    ElMessage.success('计算成功')
    fetchData()
  } catch (error) {
    ElMessage.error('计算失败')
  }
}

// 批量计算成绩
const handleBatchCalculate = () => {
  ElMessageBox.confirm(`确定要计算选中的 ${selection.value.length} 个选手的成绩吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const ids = selection.value.map((item) => item.id)
        await batchCalculateResults({ resultIds: ids })
        ElMessage.success('批量计算成功')
        fetchData()
      } catch (error) {
        ElMessage.error('批量计算失败')
      }
    })
    .catch(() => {})
}

// 自动排名
const handleAutoRanking = () => {
  if (!queryParams.projectId) {
    ElMessage.warning('请先选择项目')
    return
  }

  ElMessageBox.confirm('确定要对当前项目的所有选手自动排名吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await autoRanking({ projectId: queryParams.projectId })
        ElMessage.success('自动排名成功')
        fetchData()
      } catch (error) {
        ElMessage.error('自动排名失败')
      }
    })
    .catch(() => {})
}

// 分配奖牌
const handleAllocateMedals = () => {
  if (!queryParams.projectId) {
    ElMessage.warning('请先选择项目')
    return
  }
  medalDialogVisible.value = true
}

// 提交奖牌分配
const handleMedalSubmit = async () => {
  medalLoading.value = true
  try {
    await allocateMedals({
      projectId: queryParams.projectId,
      ...medalForm
    })
    ElMessage.success('奖牌分配成功')
    medalDialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('奖牌分配失败')
  } finally {
    medalLoading.value = false
  }
}

// 发布成绩
const handlePublish = () => {
  ElMessageBox.confirm(`确定要发布选中的 ${selection.value.length} 个选手的成绩吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const ids = selection.value.map((item) => item.id)
        await publishResult({ resultIds: ids })
        ElMessage.success('发布成功')
        fetchData()
      } catch (error) {
        ElMessage.error('发布失败')
      }
    })
    .catch(() => {})
}

// 撤销发布
const handleUnpublish = () => {
  ElMessageBox.confirm(`确定要撤销选中的 ${selection.value.length} 个选手的成绩发布吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const ids = selection.value.map((item) => item.id)
        await unpublishResult({ resultIds: ids })
        ElMessage.success('撤销成功')
        fetchData()
      } catch (error) {
        ElMessage.error('撤销失败')
      }
    })
    .catch(() => {})
}

// 导出成绩单
const handleExport = async () => {
  try {
    const res = await exportResults(queryParams)
    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `成绩单_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 选择变化
const handleSelectionChange = (val) => {
  selection.value = val
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 生命周期
onMounted(() => {
  loadCompetitionList()
  fetchData()
})
</script>

<style scoped lang="scss">
.result-container {
  padding: 20px;

  .search-card,
  .toolbar-card,
  .table-card {
    margin-bottom: 20px;
  }

  .search-form {
    .el-form-item {
      margin-bottom: 0;
    }
  }

  .stats-row {
    margin-bottom: 20px;

    .stats-card {
      .stats-content {
        display: flex;
        align-items: center;
        padding: 10px 0;

        .stats-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          margin-right: 20px;
        }

        .stats-info {
          flex: 1;

          .stats-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            line-height: 1;
            margin-bottom: 8px;
          }

          .stats-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }

  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .toolbar-left {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
