<template>
  <div class="works-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.status"
          :class="['stat-card', { active: activeStatus === item.status }]"
          @click="handleStatClick(item.status)"
        >
          <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.status"
              placeholder="全部"
              allow-clear
              style="width: 110px"
            >
              <a-select-option value="submitted">已提交</a-select-option>
              <a-select-option value="reviewing">评审中</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 === 'status'">
            <a-tag :color="workStatusMap[record.status]?.color || 'default'">
              {{ workStatusMap[record.status]?.label || record.status }}
            </a-tag>
          </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="handleViewWork(record)">
              查看详情
            </a-button>
          </template>
        </template>
      </a-table>

      <!-- 作品详情弹框 -->
      <WorkDetailModal v-model:open="workModalVisible" :work-id="currentWorkId" />
    </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 === 'registrationCount'">
            {{ activeTab === 'team' ? (record._count?.teams || 0) : (record._count?.registrations || 0) }}
          </template>
          <template v-else-if="column.key === 'worksCount'">
            {{ record._count?.works || 0 }} / {{ activeTab === 'team' ? (record._count?.teams || 0) : (record._count?.registrations || 0) }}
          </template>
          <template v-else-if="column.key === 'contestTime'">
            <div v-if="record.startTime || record.endTime">
              <div>{{ formatDate(record.startTime) }}</div>
              <div>至 {{ formatDate(record.endTime) }}</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,
  SendOutlined,
  EyeOutlined,
  CheckCircleOutlined,
} from "@ant-design/icons-vue"
import {
  contestsApi,
  worksApi,
  type Contest,
  type ContestWork,
  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 workStatusMap: Record<string, { label: string; color: string }> = {
  submitted: { label: '已提交', color: 'blue' },
  reviewing: { label: '评审中', color: 'orange' },
  accepted: { label: '已通过', color: 'green' },
  rejected: { label: '已拒绝', color: 'red' },
  locked: { label: '已锁定', color: 'default' },
}

// =============================================
// 超管端逻辑
// =============================================
const stats = ref<WorksStats>({ total: 0, submitted: 0, reviewing: 0, reviewed: 0 })
const activeStatus = 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<QueryWorkParams>({
  contestId: undefined,
  keyword: undefined,
  status: undefined,
})

const statsItems = computed(() => [
  { status: '', label: '全部', count: stats.value.total, icon: FileTextOutlined, color: '#6366f1', bgColor: 'rgba(99,102,241,0.1)' },
  { status: 'submitted', label: '已提交', count: stats.value.submitted, icon: SendOutlined, color: '#3b82f6', bgColor: 'rgba(59,130,246,0.1)' },
  { status: 'reviewing', label: '评审中', count: stats.value.reviewing, icon: EyeOutlined, color: '#f59e0b', bgColor: 'rgba(245,158,11,0.1)' },
  { status: 'reviewed', 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 fetchSuperList = async () => {
  superLoading.value = true
  try {
    const res = await worksApi.getList({
      page: superPagination.current,
      pageSize: superPagination.pageSize,
      ...superSearch,
    })
    superDataSource.value = res.list
    superPagination.total = res.total
  } catch {
    message.error('获取作品数据失败')
  } finally {
    superLoading.value = false
  }
}

const handleStatClick = (status: string) => {
  activeStatus.value = status
  // "已评完"不是数据库状态字段，暂时清除status筛选让用户看全部
  if (status === 'reviewed') {
    superSearch.status = undefined
  } else {
    superSearch.status = status || undefined
  }
  superPagination.current = 1
  fetchSuperList()
}

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

const handleSuperReset = () => {
  superSearch.contestId = undefined
  superSearch.keyword = undefined
  superSearch.status = undefined
  activeStatus.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
}

const superColumns = [
  { title: '序号', key: 'index', width: 60 },
  { title: '所属活动', key: 'contestName', width: 180 },
  { title: '作品编号', key: 'workNo', width: 150 },
  { title: '提交者', key: 'submitter', width: 130 },
  { title: '报名账号', key: 'accountNo', width: 120 },
  { title: '作品状态', key: 'status', width: 90 },
  { title: '递交时间', key: 'submitTime', width: 150 },
  { title: '操作', key: 'action', width: 80, fixed: 'right' as const },
]

// =============================================
// 机构端逻辑（保持不变）
// =============================================
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 = computed(() => [
  { title: '序号', key: 'index', width: 70 },
  { title: '活动名称', dataIndex: 'contestName', key: 'contestName', width: 200 },
  { title: '主办机构', key: 'organizers', width: 140 },
  { title: activeTab.value === 'team' ? '报名队伍数' : '报名人数', key: 'registrationCount', width: 120 },
  { title: '已递交/应递交作品数', key: 'worksCount', width: 160 },
  { title: '活动时间', key: 'contestTime', width: 180 },
  { title: '操作', key: 'action', width: 100, fixed: 'right' as const },
])

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/works/${record.id}/list?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; }

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