<template>
  <div class="results-detail-page">
    <!-- 顶部导航 -->
    <div class="page-header">
      <div class="header-left">
        <a-button type="text" @click="handleBack">
          <template #icon><arrow-left-outlined /></template>
        </a-button>
        <span class="page-title">{{ contestInfo?.contestName || '成果发布' }}</span>
        <a-tag v-if="contestInfo?.resultState === 'published'" color="green">已发布</a-tag>
        <a-tag v-else color="default">未发布</a-tag>
      </div>
      <div v-if="!isSuperAdmin" class="header-right">
        <a-button type="primary" :loading="publishLoading" @click="handlePublish" :disabled="!canPublish">
          {{ contestInfo?.resultState === 'published' ? '撤回发布' : '发布成果' }}
        </a-button>
      </div>
    </div>

    <!-- 统计摘要 -->
    <div class="stats-row">
      <div class="stat-card">
        <div class="stat-icon" style="background: rgba(99,102,241,0.1)"><file-text-outlined style="color: #6366f1" /></div>
        <div class="stat-info"><span class="stat-count">{{ summary.totalWorks }}</span><span class="stat-label">总作品</span></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background: rgba(59,130,246,0.1)"><check-circle-outlined style="color: #3b82f6" /></div>
        <div class="stat-info"><span class="stat-count">{{ summary.scoredWorks }}</span><span class="stat-label">已评分</span></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background: rgba(16,185,129,0.1)"><ordered-list-outlined style="color: #10b981" /></div>
        <div class="stat-info"><span class="stat-count">{{ summary.rankedWorks }}</span><span class="stat-label">已排名</span></div>
      </div>
      <div class="stat-card">
        <div class="stat-icon" style="background: rgba(245,158,11,0.1)"><trophy-outlined style="color: #f59e0b" /></div>
        <div class="stat-info"><span class="stat-count">{{ summary.awardedWorks }}</span><span class="stat-label">已设奖</span></div>
      </div>
      <div class="stat-card" v-if="summary.avgScore">
        <div class="stat-icon" style="background: rgba(139,92,246,0.1)"><fund-outlined style="color: #8b5cf6" /></div>
        <div class="stat-info"><span class="stat-count">{{ summary.avgScore }}</span><span class="stat-label">平均分</span></div>
      </div>
    </div>

    <!-- 操作步骤（未发布时显示） -->
    <div v-if="!isSuperAdmin && contestInfo?.resultState !== 'published'" class="action-bar">
      <a-space>
        <a-button @click="handleCalculateScores" :loading="calcScoreLoading">
          <template #icon><calculator-outlined /></template>
          第一步：计算得分
        </a-button>
        <a-button @click="handleCalculateRankings" :loading="calcRankLoading" :disabled="summary.scoredWorks === 0">
          <template #icon><ordered-list-outlined /></template>
          第二步：计算排名
        </a-button>
        <a-button @click="autoAwardVisible = true" :disabled="summary.rankedWorks === 0">
          <template #icon><trophy-outlined /></template>
          第三步：设置奖项
        </a-button>
      </a-space>
    </div>

    <!-- 搜索 -->
    <div class="filter-bar">
      <a-form :model="searchParams" layout="inline" @finish="handleSearch">
        <a-form-item label="作品编号">
          <a-input v-model:value="searchParams.workNo" placeholder="请输入作品编号" allow-clear style="width: 150px" />
        </a-form-item>
        <a-form-item label="报名账号">
          <a-input v-model:value="searchParams.accountNo" placeholder="请输入报名账号" allow-clear style="width: 150px" />
        </a-form-item>
        <a-form-item label="奖项">
          <a-select v-model:value="searchParams.awardLevel" placeholder="全部" allow-clear style="width: 120px" @change="handleSearch">
            <a-select-option v-for="opt in awardFilterOptions" :key="opt" :value="opt">{{ opt }}</a-select-option>
            <a-select-option value="_none">无奖项</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit"><template #icon><search-outlined /></template> 搜索</a-button>
          <a-button style="margin-left: 8px" @click="handleReset"><template #icon><reload-outlined /></template> 重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <a-table :columns="columns" :data-source="dataSource" :loading="loading" :pagination="pagination" row-key="id" @change="handleTableChange" class="data-table">
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'index'">
          {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
        </template>
        <template v-else-if="column.key === 'rank'">
          <span v-if="record.rank" class="rank-badge" :class="getRankClass(record.rank)">{{ record.rank }}</span>
          <span v-else class="text-muted">-</span>
        </template>
        <template v-else-if="column.key === 'workNo'">
          <a @click="handleViewWorkDetail(record)">{{ record.workNo || '-' }}</a>
        </template>
        <template v-else-if="column.key === 'finalScore'">
          <span v-if="record.finalScore != null" class="score">{{ Number(record.finalScore).toFixed(2) }}</span>
          <span v-else class="text-muted">-</span>
        </template>
        <template v-else-if="column.key === 'awardLevel'">
          <a-tag v-if="record.awardName" :color="getAwardColor(record.awardName)">
            {{ record.awardName }}
          </a-tag>
          <span v-else class="text-muted">-</span>
        </template>
        <template v-else-if="column.key === 'nickname'">
          <template v-if="contestInfo?.contestType === 'team'">
            {{ record.registration?.team?.teamName || record.registration?.user?.nickname || '-' }}
          </template>
          <template v-else>
            {{ record.registration?.user?.nickname || record.registration?.team?.teamName || '-' }}
          </template>
        </template>
        <template v-else-if="column.key === 'username'">
          {{ record.submitterAccountNo || record.registration?.user?.username || '-' }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-button v-if="!isSuperAdmin && contestInfo?.resultState !== 'published'" type="link" size="small" @click="openSetAward(record)">设奖</a-button>
          <a-button type="link" size="small" @click="handleViewWorkDetail(record)">查看</a-button>
        </template>
      </template>
    </a-table>

    <!-- 作品详情弹框 -->
    <WorkDetailModal v-model:open="workDetailModalVisible" :work-id="currentWorkId" />

    <!-- 单个设置奖项弹窗 -->
    <a-modal v-model:open="setAwardVisible" title="设置奖项" @ok="handleSetAward" :confirm-loading="setAwardLoading">
      <a-form layout="vertical" style="margin-top: 16px">
        <a-form-item label="作品">
          <span>{{ currentAwardWork?.workNo }} — {{ currentAwardWork?.registration?.user?.nickname || currentAwardWork?.registration?.team?.teamName }}</span>
        </a-form-item>
        <a-form-item label="奖项名称" required>
          <a-select v-model:value="awardForm.awardName" placeholder="选择或输入奖项名称" mode="combobox" :options="existingAwardOptions" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 自动设置奖项弹窗 -->
    <a-modal v-model:open="autoAwardVisible" title="按排名自动设置奖项" @ok="handleAutoSetAwards" :confirm-loading="autoAwardLoading" width="520px">
      <p style="color: #6b7280; font-size: 13px; margin-bottom: 16px">
        自定义奖项名称和获奖人数，系统将按排名从高到低依次分配。
      </p>
      <div class="award-tiers">
        <div v-for="(tier, idx) in autoAwardTiers" :key="idx" class="award-tier-row">
          <a-input v-model:value="tier.name" placeholder="奖项名称，如：金奖" style="flex: 1" />
          <a-input-number v-model:value="tier.count" :min="1" placeholder="人数" style="width: 100px" />
          <a-button type="text" danger @click="autoAwardTiers.splice(idx, 1)" :disabled="autoAwardTiers.length <= 1">
            <template #icon><delete-outlined /></template>
          </a-button>
        </div>
        <a-button type="dashed" block @click="autoAwardTiers.push({ name: '', count: 1 })" style="margin-top: 8px">
          <template #icon><plus-outlined /></template>
          添加奖项
        </a-button>
      </div>
      <div style="margin-top: 16px; display: flex; justify-content: space-between; color: #6b7280; font-size: 13px">
        <span>已排名作品：{{ summary.rankedWorks }} 个</span>
        <span>将分配：{{ autoAwardTotal }} 个</span>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import {
  ArrowLeftOutlined, SearchOutlined, ReloadOutlined,
  FileTextOutlined, CheckCircleOutlined, OrderedListOutlined,
  TrophyOutlined, FundOutlined, CalculatorOutlined,
  DeleteOutlined, PlusOutlined,
} from '@ant-design/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { resultsApi, type ContestResult, type ResultsSummary } from '@/api/contests'
import WorkDetailModal from '../components/WorkDetailModal.vue'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const isSuperAdmin = computed(() => authStore.hasAnyRole(['super_admin']))
const tenantCode = route.params.tenantCode as string
const contestId = Number(route.params.id)

// 奖项颜色：按在列表中出现的顺序循环分配
const awardColors = ['red', 'orange', 'blue', 'green', 'purple', 'cyan', 'magenta']
const getAwardColor = (awardName: string) => {
  const names = [...new Set(dataSource.value.filter(w => w.awardName).map(w => w.awardName!))]
  const idx = names.indexOf(awardName)
  return idx >= 0 ? awardColors[idx % awardColors.length] : 'default'
}

const getRankClass = (rank: number) => {
  if (rank === 1) return 'gold'
  if (rank === 2) return 'silver'
  if (rank === 3) return 'bronze'
  return ''
}

// 活动信息
const contestInfo = ref<any>(null)
const summary = ref({ totalWorks: 0, scoredWorks: 0, rankedWorks: 0, awardedWorks: 0, unscoredWorks: 0, avgScore: null as string | null })
const canPublish = computed(() => summary.value.rankedWorks > 0)

// 奖项筛选选项（从已有数据中动态提取）
const awardFilterOptions = computed(() => {
  const names = new Set<string>()
  dataSource.value.forEach(w => { if (w.awardName) names.add(w.awardName) })
  return Array.from(names)
})

// 列表
const loading = ref(false)
const publishLoading = ref(false)
const dataSource = ref<ContestResult[]>([])
const pagination = reactive({ current: 1, pageSize: 10, total: 0, showSizeChanger: true, showTotal: (t: number) => `共 ${t} 条` })
const searchParams = reactive({ workNo: '', accountNo: '', awardLevel: undefined as string | undefined })

// 作品详情
const workDetailModalVisible = ref(false)
const currentWorkId = ref<number | null>(null)

// 计算loading
const calcScoreLoading = ref(false)
const calcRankLoading = ref(false)

// 单个设奖
const setAwardVisible = ref(false)
const setAwardLoading = ref(false)
const currentAwardWork = ref<ContestResult | null>(null)
const awardForm = reactive({ awardLevel: '' as string, awardName: '' })

// 奖项选项：来自自动设奖配置 + 数据中已有的奖项名称
const existingAwardOptions = computed(() => {
  const names = new Set<string>()
  // 从自动设奖配置中获取
  autoAwardTiers.value.forEach(t => { if (t.name) names.add(t.name) })
  // 从已有数据中获取
  dataSource.value.forEach(w => { if (w.awardName) names.add(w.awardName) })
  return Array.from(names).map(n => ({ value: n, label: n }))
})

// 自动设奖
const autoAwardVisible = ref(false)
const autoAwardLoading = ref(false)
const autoAwardTiers = ref<Array<{ name: string; count: number }>>([
  { name: '一等奖', count: 1 },
  { name: '二等奖', count: 2 },
  { name: '三等奖', count: 3 },
])
const autoAwardTotal = computed(() => autoAwardTiers.value.reduce((sum, t) => sum + (t.count || 0), 0))

const columns = computed(() => {
  const cols: any[] = [
    { title: '排名', key: 'rank', width: 70 },
    { title: '作品编号', key: 'workNo', width: 120 },
    { title: '最终得分', key: 'finalScore', width: 90 },
    { title: '奖项', key: 'awardLevel', width: 100 },
    { title: '姓名/队伍', key: 'nickname', width: 120 },
    { title: '账号', key: 'username', width: 120 },
  ]
  cols.push({ title: '操作', key: 'action', width: 120, fixed: 'right' as const })
  return cols
})

const fetchSummary = async () => {
  try {
    const res: ResultsSummary = await resultsApi.getSummary(contestId)
    contestInfo.value = res.contest
    summary.value = { ...res.summary, avgScore: res.scoreStats?.avgScore || null }
  } catch { /* */ }
}

const fetchList = async () => {
  loading.value = true
  try {
    const response = await resultsApi.getResults(contestId, {
      page: pagination.current,
      pageSize: pagination.pageSize,
      workNo: searchParams.workNo || undefined,
      accountNo: searchParams.accountNo || undefined,
    })
    if (response.contest) {
      contestInfo.value = response.contest
    }
    let list = response.list
    // 前端过滤奖项
    if (searchParams.awardLevel) {
      if (searchParams.awardLevel === '_none') {
        list = list.filter(w => !w.awardName)
      } else {
        list = list.filter(w => w.awardName === searchParams.awardLevel)
      }
    }
    dataSource.value = list
    pagination.total = searchParams.awardLevel ? list.length : response.total
  } catch (e: any) { message.error(e?.response?.data?.message || '获取列表失败') }
  finally { loading.value = false }
}

const handleSearch = () => { pagination.current = 1; fetchList() }
const handleReset = () => { searchParams.workNo = ''; searchParams.accountNo = ''; searchParams.awardLevel = undefined; pagination.current = 1; fetchList() }
const handleTableChange = (pag: any) => { pagination.current = pag.current; pagination.pageSize = pag.pageSize; fetchList() }
const handleBack = () => { router.push(`/${tenantCode}/contests/results`) }
const handleViewWorkDetail = (record: any) => { currentWorkId.value = record.id; workDetailModalVisible.value = true }

// 计算得分
const handleCalculateScores = async () => {
  calcScoreLoading.value = true
  try {
    const res = await resultsApi.calculateScores(contestId)
    message.success(res.message)
    fetchList()
    fetchSummary()
  } catch (e: any) { message.error(e?.response?.data?.message || '计算失败') }
  finally { calcScoreLoading.value = false }
}

// 计算排名
const handleCalculateRankings = async () => {
  calcRankLoading.value = true
  try {
    const res = await resultsApi.calculateRankings(contestId)
    message.success(res.message)
    fetchList()
    fetchSummary()
  } catch (e: any) { message.error(e?.response?.data?.message || '计算失败') }
  finally { calcRankLoading.value = false }
}

// 单个设奖
const openSetAward = (record: ContestResult) => {
  currentAwardWork.value = record
  awardForm.awardName = record.awardName || ''
  awardForm.awardLevel = record.awardLevel || ''
  setAwardVisible.value = true
}
const handleSetAward = async () => {
  if (!awardForm.awardName) { message.warning('请输入奖项名称'); return }
  setAwardLoading.value = true
  try {
    await resultsApi.setAward(currentAwardWork.value!.id, {
      awardLevel: awardForm.awardName, // 用名称作为 level
      awardName: awardForm.awardName,
    })
    message.success('设置成功')
    setAwardVisible.value = false
    fetchList()
    fetchSummary()
  } catch (e: any) { message.error(e?.response?.data?.message || '设置失败') }
  finally { setAwardLoading.value = false }
}

// 自动设奖
const handleAutoSetAwards = async () => {
  const validTiers = autoAwardTiers.value.filter(t => t.name && t.count > 0)
  if (validTiers.length === 0) { message.warning('请至少设置一个奖项'); return }
  autoAwardLoading.value = true
  try {
    await resultsApi.autoSetAwards(contestId, { awards: validTiers })
    message.success('自动设奖完成')
    autoAwardVisible.value = false
    fetchList()
    fetchSummary()
  } catch (e: any) { message.error(e?.response?.data?.message || '设奖失败') }
  finally { autoAwardLoading.value = false }
}

// 发布/撤回
const handlePublish = () => {
  const isPublished = contestInfo.value?.resultState === 'published'
  Modal.confirm({
    title: isPublished ? '确定撤回成果发布？' : '确定发布成果？',
    content: isPublished ? '撤回后成果将不再对外公开' : `将发布 ${summary.value.rankedWorks} 个作品的排名和奖项信息`,
    okText: isPublished ? '撤回' : '确定发布',
    okType: isPublished ? 'danger' : 'primary',
    onOk: async () => {
      publishLoading.value = true
      try {
        if (isPublished) {
          await resultsApi.unpublish(contestId)
          message.success('已撤回发布')
        } else {
          await resultsApi.publish(contestId)
          message.success('发布成功')
        }
        fetchList()
        fetchSummary()
      } catch (e: any) { message.error(e?.response?.data?.message || '操作失败') }
      finally { publishLoading.value = false }
    },
  })
}

onMounted(() => { fetchSummary(); fetchList() })
</script>

<style scoped lang="scss">
$primary: #6366f1;

.page-header {
  display: flex; justify-content: space-between; align-items: center;
  padding: 16px 24px; background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); margin-bottom: 16px;
  .header-left { display: flex; align-items: center; gap: 8px; }
  .page-title { font-size: 18px; font-weight: 600; color: #1e1b4b; }
}

.stats-row { display: flex; gap: 12px; margin-bottom: 16px; }
.stat-card {
  flex: 1; display: flex; align-items: center; gap: 12px; padding: 14px 16px; background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  .stat-icon { width: 36px; height: 36px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 16px; flex-shrink: 0; }
  .stat-info { display: flex; flex-direction: column;
    .stat-count { font-size: 18px; font-weight: 700; color: #1e1b4b; line-height: 1.2; }
    .stat-label { font-size: 12px; color: #9ca3af; }
  }
}

.action-bar {
  padding: 16px 20px; background: rgba($primary, 0.03); border: 1px dashed rgba($primary, 0.15);
  border-radius: 12px; margin-bottom: 16px;
}

.filter-bar { padding: 20px 24px; background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); margin-bottom: 16px; }

.data-table {
  :deep(.ant-table-wrapper) { background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); overflow: hidden;
    .ant-table-thead > tr > th { background: #fafafa; font-weight: 600; }
    .ant-table-tbody > tr:hover > td { background: rgba($primary, 0.03); }
    .ant-table-pagination { padding: 16px; margin: 0; }
  }
}

.rank-badge {
  display: inline-flex; align-items: center; justify-content: center;
  width: 28px; height: 28px; border-radius: 50%; font-size: 13px; font-weight: 700; background: #f3f4f6; color: #374151;
  &.gold { background: linear-gradient(135deg, #fbbf24, #f59e0b); color: #fff; }
  &.silver { background: linear-gradient(135deg, #d1d5db, #9ca3af); color: #fff; }
  &.bronze { background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff; }
}

.score { font-weight: 700; color: #10b981; }
.text-muted { color: #d1d5db; }

.award-tiers {
  .award-tier-row {
    display: flex; gap: 8px; align-items: center; margin-bottom: 8px;
  }
}
</style>
