<template>
  <div class="registrations-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.state"
          :class="['stat-card', { active: activeState === item.state }]"
          @click="handleStatClick(item.state)"
        >
          <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.registrationState"
              placeholder="全部"
              allow-clear
              style="width: 110px"
            >
              <a-select-option value="pending">待审核</a-select-option>
              <a-select-option value="passed">已通过</a-select-option>
              <a-select-option value="rejected">已拒绝</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="参与方式">
            <a-select
              v-model:value="superSearch.participantType"
              placeholder="全部"
              allow-clear
              style="width: 120px"
            >
              <a-select-option value="self">本人参与</a-select-option>
              <a-select-option value="child">代子女报名</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 === 'participant'">
            <div class="participant-cell">
              <span class="name">{{ record.user?.nickname || record.accountName || '-' }}</span>
              <span v-if="record.participantType === 'child' && record.child" class="child-tag">
                子女：{{ record.child.name }}
              </span>
            </div>
          </template>
          <template v-else-if="column.key === 'participantType'">
            <a-tag v-if="record.participantType === 'child'" color="green">代子女</a-tag>
            <a-tag v-else color="blue">本人</a-tag>
          </template>
          <template v-else-if="column.key === 'accountNo'">
            {{ record.accountNo || record.user?.username || '-' }}
          </template>
          <template v-else-if="column.key === 'orgName'">
            {{ record.user?.tenant?.name || '-' }}
          </template>
          <template v-else-if="column.key === 'registrationState'">
            <a-tag :color="stateColorMap[record.registrationState] || 'default'">
              {{ stateTextMap[record.registrationState] || record.registrationState }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'registrationTime'">
            {{ formatDate(record.registrationTime) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-button type="link" size="small" @click="showSuperDetail(record)">
              查看详情
            </a-button>
          </template>
        </template>
      </a-table>

      <!-- 详情 Drawer -->
      <a-drawer
        v-model:open="superDetailVisible"
        title="报名详情"
        :width="520"
        :destroy-on-close="true"
      >
        <template v-if="superDetailData">
          <a-descriptions title="基本信息" :column="2" bordered size="small">
            <a-descriptions-item label="所属活动" :span="2">{{ superDetailData.contest?.contestName || '-' }}</a-descriptions-item>
            <a-descriptions-item label="参与者">{{ superDetailData.user?.nickname || superDetailData.accountName || '-' }}</a-descriptions-item>
            <a-descriptions-item label="报名账号">{{ superDetailData.accountNo || superDetailData.user?.username || '-' }}</a-descriptions-item>
            <a-descriptions-item label="手机号">{{ superDetailData.user?.phone || '-' }}</a-descriptions-item>
            <a-descriptions-item label="参与方式">
              <a-tag v-if="superDetailData.participantType === 'child'" color="green">代子女报名</a-tag>
              <a-tag v-else color="blue">本人参与</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="审核状态">
              <a-tag :color="stateColorMap[superDetailData.registrationState] || 'default'">
                {{ stateTextMap[superDetailData.registrationState] || '-' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="报名时间">{{ formatDate(superDetailData.registrationTime) }}</a-descriptions-item>
            <a-descriptions-item v-if="superDetailData.reason" label="审核理由" :span="2">{{ superDetailData.reason }}</a-descriptions-item>
          </a-descriptions>

          <!-- 子女信息 -->
          <template v-if="superDetailData.participantType === 'child' && superDetailData.child">
            <div class="detail-section">
              <h4>子女信息</h4>
              <a-descriptions :column="2" bordered size="small">
                <a-descriptions-item label="姓名">{{ superDetailData.child.name }}</a-descriptions-item>
                <a-descriptions-item label="性别">{{ superDetailData.child.gender === 'male' ? '男' : superDetailData.child.gender === 'female' ? '女' : '-' }}</a-descriptions-item>
                <a-descriptions-item label="年级">{{ superDetailData.child.grade || '-' }}</a-descriptions-item>
                <a-descriptions-item label="城市">{{ superDetailData.child.city || '-' }}</a-descriptions-item>
                <a-descriptions-item label="学校" :span="2">{{ superDetailData.child.schoolName || '-' }}</a-descriptions-item>
              </a-descriptions>
            </div>
          </template>

          <!-- 团队信息 -->
          <template v-if="superDetailData.team">
            <div class="detail-section">
              <h4>团队信息</h4>
              <a-descriptions :column="2" bordered size="small">
                <a-descriptions-item label="队伍名称">{{ superDetailData.team.teamName }}</a-descriptions-item>
                <a-descriptions-item label="成员数">{{ superDetailData.team.members?.length || 0 }}人</a-descriptions-item>
              </a-descriptions>
              <a-table
                v-if="superDetailData.team.members?.length"
                :columns="teamMemberColumns"
                :data-source="superDetailData.team.members"
                :pagination="false"
                row-key="id"
                size="small"
                style="margin-top: 12px"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'role'">
                    <a-tag :color="record.role === 'leader' ? 'gold' : 'blue'">
                      {{ record.role === 'leader' ? '队长' : '成员' }}
                    </a-tag>
                  </template>
                </template>
              </a-table>
            </div>
          </template>
        </template>
      </a-drawer>
    </template>

    <!-- ========== 机构端：保持原有两层结构 ========== -->
    <template v-else>
      <a-card class="title-card">
        <template #title>报名管理</template>
      </a-card>

      <a-tabs v-model:activeKey="activeTab" @change="handleTabChange" class="org-tabs">
        <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="activeTab === 'individual' ? orgIndividualColumns : orgTeamColumns"
        :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 === 'contestName'">
            <a @click="handleViewContest(record.id)">{{ record.contestName }}</a>
          </template>
          <template v-else-if="column.key === 'organizers'">
            {{ formatOrganizers(record.organizers) }}
          </template>
          <template v-else-if="column.key === 'registrationCount'">
            {{ record._count?.registrations || 0 }}
          </template>
          <template v-else-if="column.key === 'teamCount'">
            {{ record._count?.teams || 0 }}
          </template>
          <template v-else-if="column.key === 'registerTime'">
            <div v-if="record.registerStartTime || record.registerEndTime">
              <div>开始：{{ formatDate(record.registerStartTime) }}</div>
              <div>结束：{{ formatDate(record.registerEndTime) }}</div>
            </div>
            <span v-else class="text-muted">-</span>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleViewRecords(record)">报名记录</a-button>
              <a-button v-permission="'contest:update'" type="link" size="small" :disabled="record.registerState === 'open'" @click="handleStartRegistration(record)">启动报名</a-button>
              <a-button v-permission="'contest:update'" type="link" danger size="small" :disabled="record.registerState !== 'open'" @click="handleStopRegistration(record)">关闭报名</a-button>
            </a-space>
          </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,
  TeamOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
} from "@ant-design/icons-vue"
import {
  contestsApi,
  registrationsApi,
  type Contest,
  type ContestRegistration,
  type QueryContestParams,
  type QueryRegistrationParams,
  type RegistrationStats,
} from "@/api/contests"
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 stateColorMap: Record<string, string> = { pending: 'orange', passed: 'green', rejected: 'red', withdrawn: 'default' }
const stateTextMap: Record<string, string> = { pending: '待审核', passed: '已通过', rejected: '已拒绝', withdrawn: '已撤回' }

// =============================================
// 超管端逻辑
// =============================================
const stats = ref<RegistrationStats>({ total: 0, pending: 0, passed: 0, rejected: 0 })
const activeState = ref<string>('')
const superLoading = ref(false)
const superDataSource = ref<ContestRegistration[]>([])
const superPagination = reactive({
  current: 1, pageSize: 10, total: 0,
  showSizeChanger: true,
  showTotal: (t: number) => `共 ${t} 条`,
})
const superSearch = reactive<QueryRegistrationParams>({
  contestId: undefined,
  keyword: undefined,
  registrationState: undefined,
  participantType: undefined,
})

const statsItems = computed(() => [
  { state: '', label: '全部', count: stats.value.total, icon: TeamOutlined, color: '#6366f1', bgColor: 'rgba(99,102,241,0.1)' },
  { state: 'pending', label: '待审核', count: stats.value.pending, icon: ClockCircleOutlined, color: '#f59e0b', bgColor: 'rgba(245,158,11,0.1)' },
  { state: 'passed', label: '已通过', count: stats.value.passed, icon: CheckCircleOutlined, color: '#10b981', bgColor: 'rgba(16,185,129,0.1)' },
  { state: 'rejected', label: '已拒绝', count: stats.value.rejected, icon: CloseCircleOutlined, color: '#ef4444', bgColor: 'rgba(239,68,68,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 registrationsApi.getStats(superSearch.contestId)
  } catch { /* 静默 */ }
}

const fetchSuperList = async () => {
  superLoading.value = true
  try {
    const res = await registrationsApi.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 = (state: string) => {
  activeState.value = state
  superSearch.registrationState = state || undefined
  superPagination.current = 1
  fetchSuperList()
}

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

const handleSuperReset = () => {
  superSearch.contestId = undefined
  superSearch.keyword = undefined
  superSearch.registrationState = undefined
  superSearch.participantType = undefined
  activeState.value = ''
  superPagination.current = 1
  fetchSuperList()
  fetchSuperStats()
}

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

// 超管详情
const superDetailVisible = ref(false)
const superDetailData = ref<ContestRegistration | null>(null)

const showSuperDetail = async (record: ContestRegistration) => {
  superDetailVisible.value = true
  try {
    superDetailData.value = await registrationsApi.getDetail(record.id)
  } catch {
    message.error('获取报名详情失败')
    superDetailData.value = record
  }
}

const superColumns = [
  { title: '序号', key: 'index', width: 60 },
  { title: '所属活动', key: 'contestName', width: 180 },
  { title: '参与者', key: 'participant', width: 140 },
  { title: '参与方式', key: 'participantType', width: 90 },
  { title: '报名账号', key: 'accountNo', width: 120 },
  { title: '主办机构', key: 'orgName', width: 120 },
  { title: '审核状态', key: 'registrationState', width: 90 },
  { title: '报名时间', key: 'registrationTime', width: 150 },
  { title: '操作', key: 'action', width: 80, fixed: 'right' as const },
]

const teamMemberColumns = [
  { title: '姓名', dataIndex: ['user', 'nickname'], key: 'nickname', width: 120 },
  { title: '账号', dataIndex: ['user', 'username'], key: 'username', width: 150 },
  { title: '角色', dataIndex: 'role', key: 'role', width: 80 },
]

// =============================================
// 机构端逻辑（保持不变）
// =============================================
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<QueryContestParams>({ contestName: '' })

const orgIndividualColumns = [
  { title: '序号', key: 'index', width: 70 },
  { title: '活动名称', key: 'contestName', width: 250 },
  { title: '主办单位', key: 'organizers', width: 200 },
  { title: '报名人数', key: 'registrationCount', width: 120 },
  { title: '报名时间', key: 'registerTime', width: 200 },
  { title: '操作', key: 'action', width: 220, fixed: 'right' as const },
]

const orgTeamColumns = [
  { title: '序号', key: 'index', width: 70 },
  { title: '活动名称', key: 'contestName', width: 250 },
  { title: '主办单位', key: 'organizers', width: 200 },
  { title: '报名队伍数', key: 'teamCount', width: 120 },
  { title: '报名时间', key: 'registerTime', width: 200 },
  { title: '操作', key: 'action', width: 220, fixed: 'right' as const },
]

const fetchList = async () => {
  loading.value = true
  try {
    const res = await contestsApi.getList({
      ...searchParams,
      contestType: activeTab.value,
      page: pagination.current,
      pageSize: pagination.pageSize,
    })
    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 handleViewContest = (id: number) => router.push({ name: 'ContestsDetail', params: { tenantCode, id } })
const handleViewRecords = (record: Contest) => router.push({ name: 'RegistrationRecords', params: { tenantCode, id: record.id } })

const formatOrganizers = (org: any) => {
  if (!org) return '-'
  if (Array.isArray(org)) return org.join('、') || '-'
  if (typeof org === 'string') { try { const p = JSON.parse(org); return Array.isArray(p) ? p.join('、') : org } catch { return org } }
  return '-'
}

const handleStartRegistration = async (record: Contest) => {
  try { await contestsApi.update(record.id, { registerState: 'open' } as any); message.success('已启动报名'); fetchList() }
  catch (e: any) { message.error(e?.response?.data?.message || '启动报名失败') }
}
const handleStopRegistration = async (record: Contest) => {
  try { await contestsApi.update(record.id, { registerState: 'closed' } as any); message.success('已关闭报名'); fetchList() }
  catch (e: any) { message.error(e?.response?.data?.message || '关闭报名失败') }
}

// =============================================
// 初始化
// =============================================
onMounted(() => {
  if (isSuperAdmin.value) {
    // 读取 URL 参数
    const queryContestId = route.query.contestId ? Number(route.query.contestId) : undefined
    const queryStatus = route.query.status as string | undefined
    if (queryContestId) superSearch.contestId = queryContestId
    if (queryStatus) { superSearch.registrationState = queryStatus as any; activeState.value = queryStatus }

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

.participant-cell {
  .name { font-weight: 600; color: #1e1b4b; }
  .child-tag { display: block; font-size: 11px; color: #10b981; margin-top: 2px; }
}

.text-muted { color: #d1d5db; }

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