<template>
  <div class="review-progress-page">
    <!-- ========== 超管端：扁平评审进度列表 ========== -->
    <template v-if="isSuperAdmin">
      <a-card class="title-card">
        <template #title>评审进度</template>
      </a-card>

      <!-- 统计卡片 -->
      <div class="stats-row">
        <div
          v-for="item in statsItems"
          :key="item.key"
          :class="['stat-card', { active: activeFilter === item.key }]"
          @click="handleStatClick(item.key)"
        >
          <div class="stat-icon" :style="{ background: item.bgColor }">
            <component :is="item.icon" :style="{ color: item.color }" />
          </div>
          <div class="stat-info">
            <span class="stat-count">{{ item.count }}</span>
            <span class="stat-label">{{ item.label }}</span>
          </div>
        </div>
      </div>

      <!-- 筛选栏 -->
      <div class="filter-bar">
        <a-form layout="inline" @finish="handleSuperSearch">
          <a-form-item label="所属活动">
            <a-select
              v-model:value="superSearch.contestId"
              placeholder="全部活动"
              allow-clear
              show-search
              :filter-option="filterContestOption"
              style="width: 200px"
              :options="contestOptions"
            />
          </a-form-item>
          <a-form-item label="作品/作者">
            <a-input
              v-model:value="superSearch.keyword"
              placeholder="作品编号 / 作者姓名"
              allow-clear
              style="width: 180px"
            />
          </a-form-item>
          <a-form-item label="评审进度">
            <a-select
              v-model:value="superSearch.reviewFilter"
              placeholder="全部"
              allow-clear
              style="width: 120px"
            >
              <a-select-option value="not_reviewed">未评审</a-select-option>
              <a-select-option value="in_progress">评审中</a-select-option>
              <a-select-option value="completed">已完成</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit">
                <template #icon><SearchOutlined /></template>
                搜索
              </a-button>
              <a-button @click="handleSuperReset">
                <template #icon><ReloadOutlined /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 表格 -->
      <a-table
        :columns="superColumns"
        :data-source="superDataSource"
        :loading="superLoading"
        :pagination="superPagination"
        row-key="id"
        @change="handleSuperTableChange"
        class="data-table"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'index'">
            {{ (superPagination.current - 1) * superPagination.pageSize + index + 1 }}
          </template>
          <template v-else-if="column.key === 'contestName'">
            <a-button
              type="link"
              size="small"
              class="contest-link"
              @click="router.push(`/${tenantCode}/contests/${record.contest?.id}/overview`)"
            >
              {{ record.contest?.contestName || '-' }}
            </a-button>
          </template>
          <template v-else-if="column.key === 'workNo'">
            <a class="work-link" @click="handleViewWork(record)">{{ record.workNo || '-' }}</a>
          </template>
          <template v-else-if="column.key === 'submitter'">
            <span v-if="record.registration?.team">{{ record.registration.team.teamName }}</span>
            <span v-else>{{ record.registration?.user?.nickname || '-' }}</span>
          </template>
          <template v-else-if="column.key === 'accountNo'">
            {{ record.submitterAccountNo || record.registration?.user?.username || '-' }}
          </template>
          <template v-else-if="column.key === 'reviewProgress'">
            <a-tag v-if="getReviewState(record) === 'completed'" color="success">已完成</a-tag>
            <a-tag v-else-if="getReviewState(record) === 'in_progress'" color="processing">
              {{ record.reviewedCount || 0 }}/{{ record.totalJudgesCount || 0 }}
            </a-tag>
            <a-tag v-else>未评审</a-tag>
          </template>
          <template v-else-if="column.key === 'averageScore'">
            <span v-if="record.averageScore != null" class="score-text">
              {{ record.averageScore.toFixed(2) }}
            </span>
            <span v-else class="text-muted">-</span>
          </template>
          <template v-else-if="column.key === 'submitTime'">
            {{ formatDate(record.submitTime) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-button type="link" size="small" @click="showScoreDetail(record)">
              查看详情
            </a-button>
          </template>
        </template>
      </a-table>

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

      <!-- 评分详情 Drawer -->
      <a-drawer
        v-model:open="scoreDrawerVisible"
        title="评审详情"
        :width="560"
        :destroy-on-close="true"
      >
        <template v-if="currentScoreWork">
          <a-descriptions title="作品信息" :column="2" bordered size="small">
            <a-descriptions-item label="所属活动" :span="2">{{ currentScoreWork.contest?.contestName || '-' }}</a-descriptions-item>
            <a-descriptions-item label="作品编号">{{ currentScoreWork.workNo || '-' }}</a-descriptions-item>
            <a-descriptions-item label="提交者">
              {{ currentScoreWork.registration?.team?.teamName || currentScoreWork.registration?.user?.nickname || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="平均分">
              <span v-if="currentScoreWork.averageScore != null" class="score-text">{{ currentScoreWork.averageScore.toFixed(2) }}</span>
              <span v-else>-</span>
            </a-descriptions-item>
            <a-descriptions-item label="评审进度">
              {{ currentScoreWork.reviewedCount || 0 }} / {{ currentScoreWork.totalJudgesCount || 0 }}
            </a-descriptions-item>
          </a-descriptions>

          <div class="detail-section">
            <h4>评委评分明细</h4>
            <a-spin :spinning="scoreListLoading">
              <a-empty v-if="!scoreList.length && !scoreListLoading" description="暂无评分记录" />
              <a-table
                v-else
                :columns="scoreColumns"
                :data-source="scoreList"
                :pagination="false"
                row-key="id"
                size="small"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'judgeName'">
                    {{ record.judge?.nickname || record.judge?.username || '-' }}
                  </template>
                  <template v-else-if="column.key === 'score'">
                    <span v-if="record.totalScore != null" class="score-text">{{ record.totalScore }}</span>
                    <span v-else class="text-muted">未评分</span>
                  </template>
                  <template v-else-if="column.key === 'scoreTime'">
                    {{ formatDate(record.scoreTime) }}
                  </template>
                  <template v-else-if="column.key === 'comments'">
                    {{ record.comments || '-' }}
                  </template>
                </template>
              </a-table>
            </a-spin>
          </div>
        </template>
      </a-drawer>
    </template>

    <!-- ========== 机构端：保持原有两层结构 ========== -->
    <template v-else>
      <a-card class="title-card">
        <template #title>评审进度</template>
      </a-card>

      <a-tabs v-model:activeKey="activeTab" class="org-tabs" @change="handleTabChange">
        <a-tab-pane key="individual" tab="个人参与" />
        <a-tab-pane key="team" tab="团队参与" />
      </a-tabs>

      <a-form :model="searchParams" layout="inline" class="filter-bar" @finish="handleSearch">
        <a-form-item label="活动名称">
          <a-input v-model:value="searchParams.contestName" placeholder="请输入活动名称" allow-clear style="width: 200px" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">
            <template #icon><SearchOutlined /></template>
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset">
            <template #icon><ReloadOutlined /></template>
            重置
          </a-button>
        </a-form-item>
      </a-form>

      <a-table
        :columns="orgColumns"
        :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 === 'organizers'">
            {{ record.organizers || '-' }}
          </template>
          <template v-else-if="column.key === 'reviewStatus'">
            <a-tag :color="getOrgReviewStatusColor(record)">{{ getOrgReviewStatusText(record) }}</a-tag>
          </template>
          <template v-else-if="column.key === 'reviewedCount'">
            {{ record.reviewedCount || 0 }} / {{ record.totalWorksCount || 0 }}
          </template>
          <template v-else-if="column.key === 'reviewTime'">
            <div v-if="record.reviewStartTime || record.reviewEndTime">
              <div>{{ formatDate(record.reviewStartTime) }}</div>
              <div>至 {{ formatDate(record.reviewEndTime) }}</div>
            </div>
            <span v-else class="text-muted">-</span>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-button type="link" size="small" @click="handleViewDetail(record)">查看详情</a-button>
          </template>
        </template>
      </a-table>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue"
import { useRouter, useRoute } from "vue-router"
import { message } from "ant-design-vue"
import { useAuthStore } from "@/stores/auth"
import {
  SearchOutlined,
  ReloadOutlined,
  FileTextOutlined,
  MinusCircleOutlined,
  SyncOutlined,
  CheckCircleOutlined,
} from "@ant-design/icons-vue"
import {
  contestsApi,
  worksApi,
  reviewsApi,
  type Contest,
  type ContestWork,
  type ContestWorkScore,
  type QueryWorkParams,
  type WorksStats,
} from "@/api/contests"
import WorkDetailModal from "../components/WorkDetailModal.vue"
import dayjs from "dayjs"

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

const formatDate = (d?: string) => d ? dayjs(d).format("YYYY-MM-DD HH:mm") : "-"

// =============================================
// 超管端逻辑
// =============================================
const stats = ref<WorksStats>({ total: 0, submitted: 0, reviewing: 0, reviewed: 0 })
const activeFilter = ref<string>('')
const superLoading = ref(false)
const superDataSource = ref<ContestWork[]>([])
const superPagination = reactive({
  current: 1, pageSize: 10, total: 0,
  showSizeChanger: true,
  showTotal: (t: number) => `共 ${t} 条`,
})
const superSearch = reactive({
  contestId: undefined as number | undefined,
  keyword: undefined as string | undefined,
  status: undefined as string | undefined,
  reviewFilter: undefined as string | undefined,
})

const statsItems = computed(() => [
  { key: '', label: '全部', count: stats.value.total, icon: FileTextOutlined, color: '#6366f1', bgColor: 'rgba(99,102,241,0.1)' },
  { key: 'not_reviewed', label: '未评审', count: stats.value.submitted, icon: MinusCircleOutlined, color: '#9ca3af', bgColor: 'rgba(156,163,175,0.1)' },
  { key: 'in_progress', label: '评审中', count: stats.value.reviewing, icon: SyncOutlined, color: '#f59e0b', bgColor: 'rgba(245,158,11,0.1)' },
  { key: 'completed', label: '已完成', count: stats.value.reviewed, icon: CheckCircleOutlined, color: '#10b981', bgColor: 'rgba(16,185,129,0.1)' },
])

// 活动下拉
const contestOptions = ref<{ label: string; value: number }[]>([])
const fetchContestOptions = async () => {
  try {
    const res = await contestsApi.getList({ page: 1, pageSize: 100 })
    contestOptions.value = res.list.map((c) => ({ label: c.contestName, value: c.id }))
  } catch { /* 静默 */ }
}
const filterContestOption = (input: string, option: any) => option.label?.toLowerCase().includes(input.toLowerCase())

const fetchSuperStats = async () => {
  try {
    stats.value = await worksApi.getStats(superSearch.contestId)
  } catch { /* 静默 */ }
}

const getReviewState = (record: any): string => {
  const reviewed = record.reviewedCount || 0
  const total = record.totalJudgesCount || 0
  if (reviewed === 0) return 'not_reviewed'
  if (total > 0 && reviewed >= total) return 'completed'
  return 'in_progress'
}

const fetchSuperList = async () => {
  superLoading.value = true
  try {
    const params: QueryWorkParams = {
      page: superPagination.current,
      pageSize: superPagination.pageSize,
      contestId: superSearch.contestId,
      keyword: superSearch.keyword,
      status: superSearch.status as any,
    }
    const res = await worksApi.getList(params)

    // 前端过滤评审进度
    let list = res.list
    if (superSearch.reviewFilter) {
      list = list.filter((w) => getReviewState(w) === superSearch.reviewFilter)
    }

    superDataSource.value = list
    superPagination.total = superSearch.reviewFilter ? list.length : res.total
  } catch {
    message.error('获取评审进度失败')
  } finally {
    superLoading.value = false
  }
}

const handleStatClick = (key: string) => {
  activeFilter.value = key
  superSearch.reviewFilter = key || undefined
  superPagination.current = 1
  fetchSuperList()
}

const handleSuperSearch = () => {
  superPagination.current = 1
  fetchSuperList()
  fetchSuperStats()
}

const handleSuperReset = () => {
  superSearch.contestId = undefined
  superSearch.keyword = undefined
  superSearch.status = undefined
  superSearch.reviewFilter = undefined
  activeFilter.value = ''
  superPagination.current = 1
  fetchSuperList()
  fetchSuperStats()
}

const handleSuperTableChange = (pag: any) => {
  superPagination.current = pag.current
  superPagination.pageSize = pag.pageSize
  fetchSuperList()
}

// 作品详情弹框
const workModalVisible = ref(false)
const currentWorkId = ref<number | null>(null)
const handleViewWork = (record: ContestWork) => {
  currentWorkId.value = record.id
  workModalVisible.value = true
}

// 评分详情 Drawer
const scoreDrawerVisible = ref(false)
const scoreListLoading = ref(false)
const scoreList = ref<ContestWorkScore[]>([])
const currentScoreWork = ref<ContestWork | null>(null)

const showScoreDetail = async (record: ContestWork) => {
  currentScoreWork.value = record
  scoreDrawerVisible.value = true
  scoreListLoading.value = true
  try {
    scoreList.value = await reviewsApi.getWorkScores(record.id)
  } catch {
    scoreList.value = []
  } finally {
    scoreListLoading.value = false
  }
}

const superColumns = [
  { title: '序号', key: 'index', width: 60 },
  { title: '所属活动', key: 'contestName', width: 180 },
  { title: '作品编号', key: 'workNo', width: 130 },
  { title: '提交者', key: 'submitter', width: 130 },
  { title: '报名账号', key: 'accountNo', width: 120 },
  { title: '评审进度', key: 'reviewProgress', width: 100 },
  { title: '平均分', key: 'averageScore', width: 80 },
  { title: '递交时间', key: 'submitTime', width: 150 },
  { title: '操作', key: 'action', width: 100, fixed: 'right' as const },
]

const scoreColumns = [
  { title: '评委姓名', key: 'judgeName', width: 120 },
  { title: '评分', key: 'score', width: 80 },
  { title: '评语', key: 'comments', width: 180, ellipsis: true },
  { title: '评分时间', key: 'scoreTime', width: 150 },
]

// =============================================
// 机构端逻辑（保持不变）
// =============================================
const activeTab = ref<'individual' | 'team'>('individual')
const loading = ref(false)
const dataSource = ref<Contest[]>([])
const pagination = reactive({ current: 1, pageSize: 10, total: 0 })
const searchParams = reactive({ contestName: '' })

const orgColumns = [
  { title: '序号', key: 'index', width: 70 },
  { title: '活动名称', dataIndex: 'contestName', key: 'contestName', width: 200 },
  { title: '主办机构', key: 'organizers', width: 140 },
  { title: '评审状态', key: 'reviewStatus', width: 100 },
  { title: '已评审/作品数', key: 'reviewedCount', width: 130 },
  { title: '评审时间', key: 'reviewTime', width: 180 },
  { title: '操作', key: 'action', width: 100, fixed: 'right' as const },
]

const getOrgReviewStatusColor = (record: Contest) => {
  const now = new Date()
  const start = record.reviewStartTime ? new Date(record.reviewStartTime) : null
  const end = record.reviewEndTime ? new Date(record.reviewEndTime) : null
  if (!start || now < start) return 'default'
  if (end && now > end) return 'success'
  return 'processing'
}
const getOrgReviewStatusText = (record: Contest) => {
  const now = new Date()
  const start = record.reviewStartTime ? new Date(record.reviewStartTime) : null
  const end = record.reviewEndTime ? new Date(record.reviewEndTime) : null
  if (!start || now < start) return '未开始'
  if (end && now > end) return '已完成'
  return '进行中'
}

const fetchList = async () => {
  loading.value = true
  try {
    const res = await contestsApi.getList({
      page: pagination.current,
      pageSize: pagination.pageSize,
      contestName: searchParams.contestName || undefined,
      contestType: activeTab.value,
    })
    dataSource.value = res.list
    pagination.total = res.total
  } catch { message.error('获取列表失败') }
  finally { loading.value = false }
}

const handleTabChange = () => { pagination.current = 1; fetchList() }
const handleSearch = () => { pagination.current = 1; fetchList() }
const handleReset = () => { searchParams.contestName = ''; pagination.current = 1; fetchList() }
const handleTableChange = (pag: any) => { pagination.current = pag.current; pagination.pageSize = pag.pageSize; fetchList() }
const handleViewDetail = (record: Contest) => {
  router.push(`/${tenantCode}/contests/reviews/${record.id}/progress?type=${activeTab.value}`)
}

// =============================================
// 初始化
// =============================================
onMounted(() => {
  if (isSuperAdmin.value) {
    const queryContestId = route.query.contestId ? Number(route.query.contestId) : undefined
    if (queryContestId) superSearch.contestId = queryContestId

    fetchContestOptions()
    fetchSuperStats()
    fetchSuperList()
  } else {
    fetchList()
  }
})
</script>

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

.title-card {
  margin-bottom: 16px;
  border: none;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  :deep(.ant-card-head) { border-bottom: none; .ant-card-head-title { font-size: 18px; font-weight: 600; } }
  :deep(.ant-card-body) { padding: 0; }
}

.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);
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.2s;
  &:hover { box-shadow: 0 4px 16px rgba($primary, 0.12); }
  &.active { border-color: $primary; background: rgba($primary, 0.02); }
  .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; } }
}

.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; }
  }
}

.contest-link { padding: 0; text-align: left; }
.work-link { color: $primary; cursor: pointer; &:hover { text-decoration: underline; } }
.text-muted { color: #d1d5db; }
.score-text { font-weight: 600; color: #1e1b4b; }

.detail-section {
  margin-top: 24px;
  h4 { font-size: 14px; font-weight: 600; color: #1e1b4b; margin: 0 0 12px; padding-bottom: 8px; border-bottom: 1px solid #f0ecf9; }
}

.org-tabs {
  background: #fff;
  padding: 0 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  margin-bottom: 16px;
}
</style>
