<template>
  <div class="super-detail-page">
    <a-spin :spinning="loading">
      <template v-if="contest">
        <!-- 顶部信息栏 -->
        <div class="header-bar">
          <div class="header-left">
            <a-button type="text" @click="$router.back()">
              <template #icon><ArrowLeftOutlined /></template>
              返回
            </a-button>
            <h1 class="title">{{ contest.contestName }}</h1>
          </div>
          <div class="header-tags">
            <a-tag :color="contest.contestType === 'individual' ? 'blue' : 'green'">
              {{ contest.contestType === 'individual' ? '个人参与' : '团队参与' }}
            </a-tag>
            <a-tag :color="stageTagMap[currentStage]?.color || 'default'">
              {{ stageTagMap[currentStage]?.label || '已发布' }}
            </a-tag>
            <a-tag v-if="contest.visibility" color="purple">
              {{ visibilityMap[contest.visibility] || contest.visibility }}
            </a-tag>
            <span class="header-meta">
              主办：{{ creatorTenantName }}
              <a-divider type="vertical" />
              创建：{{ formatDate(contest.createTime) }}
            </span>
          </div>
        </div>

        <!-- 数据概览卡片 -->
        <div class="overview-cards">
          <div class="ov-card" @click="goToRegistrations">
            <div class="ov-icon" style="background: rgba(59,130,246,0.1)">
              <TeamOutlined style="color: #3b82f6" />
            </div>
            <div class="ov-data">
              <span class="ov-count">{{ contest._count?.registrations || 0 }}</span>
              <span class="ov-label">报名人数</span>
            </div>
            <RightOutlined class="ov-arrow" />
          </div>
          <div class="ov-card" @click="goToWorks">
            <div class="ov-icon" style="background: rgba(16,185,129,0.1)">
              <FileTextOutlined style="color: #10b981" />
            </div>
            <div class="ov-data">
              <span class="ov-count">{{ contest._count?.works || 0 }}</span>
              <span class="ov-label">作品数量</span>
            </div>
            <RightOutlined class="ov-arrow" />
          </div>
          <div class="ov-card" @click="goToReviewProgress">
            <div class="ov-icon" style="background: rgba(245,158,11,0.1)">
              <AuditOutlined style="color: #f59e0b" />
            </div>
            <div class="ov-data">
              <span class="ov-count">
                {{ contest.reviewedCount || 0 }}<span class="ov-sub">/{{ contest.totalWorksCount || 0 }}</span>
              </span>
              <span class="ov-label">评审进度</span>
            </div>
            <RightOutlined class="ov-arrow" />
          </div>
          <div class="ov-card" @click="goToJudges">
            <div class="ov-icon" style="background: rgba(139,92,246,0.1)">
              <UserOutlined style="color: #8b5cf6" />
            </div>
            <div class="ov-data">
              <span class="ov-count">{{ contest._count?.judges || 0 }}</span>
              <span class="ov-label">评委人数</span>
            </div>
            <RightOutlined class="ov-arrow" />
          </div>
        </div>

        <!-- 时间轴 -->
        <div class="timeline-bar">
          <div
            v-for="(phase, idx) in phases"
            :key="phase.key"
            :class="['phase', { completed: phase.status === 'completed', current: phase.status === 'current', future: phase.status === 'future' }]"
          >
            <div class="phase-dot">
              <CheckOutlined v-if="phase.status === 'completed'" />
              <span v-else>{{ idx + 1 }}</span>
            </div>
            <div class="phase-info">
              <span class="phase-name">{{ phase.name }}</span>
              <span class="phase-time">{{ phase.timeRange }}</span>
            </div>
            <div v-if="idx < phases.length - 1" class="phase-line" :class="{ done: phase.status === 'completed' }"></div>
          </div>
        </div>

        <!-- Tab 区域 -->
        <a-card class="tab-card">
          <a-tabs v-model:activeKey="activeTab">
            <a-tab-pane key="config" tab="活动配置">
              <a-descriptions bordered :column="2" size="small" class="config-desc">
                <a-descriptions-item label="活动名称" :span="2">{{ contest.contestName }}</a-descriptions-item>
                <a-descriptions-item label="活动类型">{{ contest.contestType === 'individual' ? '个人参与' : '团队参与' }}</a-descriptions-item>
                <a-descriptions-item label="可见范围">{{ visibilityMap[contest.visibility] || '-' }}</a-descriptions-item>
                <a-descriptions-item v-if="contest.visibility === 'targeted' && contest.targetCities?.length" label="定向城市" :span="2">
                  <a-tag v-for="c in contest.targetCities" :key="c">{{ c }}</a-tag>
                </a-descriptions-item>
                <a-descriptions-item v-if="contest.visibility === 'targeted'" label="年龄限制">
                  {{ contest.ageMin || 0 }} - {{ contest.ageMax || '不限' }} 岁
                </a-descriptions-item>
              </a-descriptions>

              <a-divider orientation="left">报名配置</a-divider>
              <a-descriptions bordered :column="2" size="small">
                <a-descriptions-item label="报名时间" :span="2">{{ formatDate(contest.registerStartTime) }} ~ {{ formatDate(contest.registerEndTime) }}</a-descriptions-item>
                <a-descriptions-item label="是否需要审核">{{ contest.requireAudit ? '是' : '否' }}</a-descriptions-item>
                <a-descriptions-item v-if="contest.contestType === 'team'" label="团队人数">
                  {{ contest.teamMinMembers || '-' }} ~ {{ contest.teamMaxMembers || '-' }} 人
                </a-descriptions-item>
              </a-descriptions>

              <a-divider orientation="left">作品配置</a-divider>
              <a-descriptions bordered :column="2" size="small">
                <a-descriptions-item label="提交时间" :span="2">{{ formatDate(contest.submitStartTime) }} ~ {{ formatDate(contest.submitEndTime) }}</a-descriptions-item>
                <a-descriptions-item label="提交规则">{{ contest.submitRule === 'resubmit' ? '允许重新提交' : '单次提交' }}</a-descriptions-item>
                <a-descriptions-item label="作品类型">{{ workTypeMap[contest.workType] || '-' }}</a-descriptions-item>
                <a-descriptions-item v-if="contest.workRequirement" label="作品要求" :span="2">{{ contest.workRequirement }}</a-descriptions-item>
              </a-descriptions>

              <a-divider orientation="left">评审配置</a-divider>
              <a-descriptions bordered :column="2" size="small">
                <a-descriptions-item label="评审时间" :span="2">{{ formatDate(contest.reviewStartTime) }} ~ {{ formatDate(contest.reviewEndTime) }}</a-descriptions-item>
                <a-descriptions-item label="评审规则">{{ contest.reviewRule?.ruleName || '-' }}</a-descriptions-item>
                <a-descriptions-item label="成果状态">
                  <a-tag :color="contest.resultState === 'published' ? 'green' : 'default'">
                    {{ contest.resultState === 'published' ? '已发布' : '未发布' }}
                  </a-tag>
                </a-descriptions-item>
              </a-descriptions>

              <a-divider orientation="left">组织信息</a-divider>
              <a-descriptions bordered :column="2" size="small">
                <a-descriptions-item label="主办单位">{{ formatOrgList(contest.organizers) }}</a-descriptions-item>
                <a-descriptions-item label="协办单位">{{ formatOrgList(contest.coOrganizers) }}</a-descriptions-item>
                <a-descriptions-item label="赞助单位">{{ formatOrgList(contest.sponsors) }}</a-descriptions-item>
                <a-descriptions-item label="联系人">{{ contest.contactName || '-' }} {{ contest.contactPhone ? `/ ${contest.contactPhone}` : '' }}</a-descriptions-item>
              </a-descriptions>
            </a-tab-pane>

            <a-tab-pane key="content" tab="活动内容">
              <div v-if="contest.content" class="rich-content" v-html="contest.content"></div>
              <a-empty v-else description="暂无活动内容" />
            </a-tab-pane>

            <a-tab-pane key="notices" tab="通知公告">
              <a-spin :spinning="noticesLoading">
                <a-empty v-if="!notices.length" description="暂无公告" />
                <div v-else class="notice-list">
                  <div v-for="item in notices" :key="item.id" class="notice-item">
                    <div class="notice-header">
                      <span class="notice-title">{{ item.title }}</span>
                      <a-tag size="small">{{ item.noticeType === 'urgent' ? '紧急' : '公告' }}</a-tag>
                    </div>
                    <div class="notice-body">{{ item.content }}</div>
                    <div class="notice-time">{{ formatDateTime(item.publishTime) }}</div>
                  </div>
                </div>
              </a-spin>
            </a-tab-pane>

            <a-tab-pane key="results" tab="活动结果">
              <a-empty v-if="contest.resultState !== 'published'" description="成果尚未发布" />
              <div v-else>（成果表格，复用现有逻辑）</div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </template>

      <a-empty v-else-if="!loading" description="活动不存在" style="padding: 100px 0" />
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  ArrowLeftOutlined, TeamOutlined, FileTextOutlined, AuditOutlined,
  UserOutlined, RightOutlined, CheckOutlined,
} from '@ant-design/icons-vue'
import { contestsApi, noticesApi, type Contest, type ContestNotice } from '@/api/contests'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()
const tenantCode = route.params.tenantCode as string
const contestId = Number(route.params.id)

const loading = ref(false)
const contest = ref<Contest | null>(null)
const notices = ref<ContestNotice[]>([])
const noticesLoading = ref(false)
const activeTab = ref('config')

// ========== 映射 ==========
const stageTagMap: Record<string, { label: string; color: string }> = {
  unpublished: { label: '未发布', color: 'default' },
  published: { label: '已发布', color: 'blue' },
  registering: { label: '报名中', color: 'processing' },
  submitting: { label: '征稿中', color: 'success' },
  reviewing: { label: '评审中', color: 'warning' },
  finished: { label: '已结束', color: 'default' },
}
const visibilityMap: Record<string, string> = {
  public: '公开', targeted: '定向推送', designated: '指定机构', internal: '仅内部',
}
const workTypeMap: Record<string, string> = {
  image: '图片', video: '视频', document: '文档', code: '代码', other: '其他',
}

// ========== 阶段计算 ==========
const currentStage = computed(() => (contest.value as any)?.stage || 'published')

const phases = computed(() => {
  const c = contest.value
  if (!c) return []
  const now = dayjs()

  const getStatus = (start?: string, end?: string) => {
    if (!start || !end) return 'future'
    if (now.isAfter(dayjs(end))) return 'completed'
    if (now.isAfter(dayjs(start))) return 'current'
    return 'future'
  }

  return [
    {
      key: 'register', name: '报名阶段',
      timeRange: `${formatShortDate(c.registerStartTime)} ~ ${formatShortDate(c.registerEndTime)}`,
      status: getStatus(c.registerStartTime, c.registerEndTime),
    },
    {
      key: 'submit', name: '征稿阶段',
      timeRange: `${formatShortDate(c.submitStartTime)} ~ ${formatShortDate(c.submitEndTime)}`,
      status: getStatus(c.submitStartTime, c.submitEndTime),
    },
    {
      key: 'review', name: '评审阶段',
      timeRange: `${formatShortDate(c.reviewStartTime)} ~ ${formatShortDate(c.reviewEndTime)}`,
      status: getStatus(c.reviewStartTime, c.reviewEndTime),
    },
    {
      key: 'result', name: '成果发布',
      timeRange: c.resultState === 'published' ? '已发布' : '未发布',
      status: c.resultState === 'published' ? 'completed' : 'future',
    },
  ]
})

// ========== 数据加载 ==========
const creatorTenantName = computed(() => (contest.value as any)?.creatorTenant?.name || '-')

const fetchDetail = async () => {
  loading.value = true
  try {
    contest.value = await contestsApi.getDetail(contestId)
  } catch {
    message.error('获取活动详情失败')
  } finally {
    loading.value = false
  }
}

const fetchNotices = async () => {
  noticesLoading.value = true
  try {
    notices.value = await noticesApi.getList(contestId)
  } catch { /* 静默 */ }
  finally { noticesLoading.value = false }
}

// ========== 跳转 ==========
const goToRegistrations = () => router.push(`/${tenantCode}/contests/registrations?contestId=${contestId}`)
const goToWorks = () => router.push(`/${tenantCode}/contests/works/${contestId}/list`)
const goToReviewProgress = () => router.push(`/${tenantCode}/contests/reviews/${contestId}/progress`)
const goToJudges = () => router.push(`/${tenantCode}/contests/reviews/progress?contestId=${contestId}`)

// ========== 工具 ==========
const formatDate = (d?: string) => d ? dayjs(d).format('YYYY-MM-DD HH:mm') : '-'
const formatShortDate = (d?: string) => d ? dayjs(d).format('MM-DD') : '-'
const formatDateTime = (d?: string) => d ? dayjs(d).format('YYYY-MM-DD HH:mm') : '-'
const formatOrgList = (org: any) => {
  if (!org) return '-'
  if (typeof org === 'string') return org
  if (Array.isArray(org)) return org.join('、')
  return '-'
}

onMounted(() => {
  fetchDetail()
  fetchNotices()
})
</script>

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

.super-detail-page {
  max-width: 1200px;
}

// 顶部信息栏
.header-bar {
  background: #fff;
  border-radius: 12px;
  padding: 20px 24px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);

  .header-left {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;

    .title {
      font-size: 20px;
      font-weight: 700;
      color: #1e1b4b;
      margin: 0;
    }
  }

  .header-tags {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;

    .header-meta {
      font-size: 13px;
      color: #6b7280;
      margin-left: 8px;
    }
  }
}

// 数据概览
.overview-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  margin-bottom: 16px;
}

.ov-card {
  display: flex;
  align-items: center;
  gap: 12px;
  background: #fff;
  border-radius: 12px;
  padding: 18px 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    box-shadow: 0 4px 20px rgba($primary, 0.12);
    transform: translateY(-2px);
  }

  .ov-icon {
    width: 44px;
    height: 44px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    flex-shrink: 0;
  }

  .ov-data {
    flex: 1;
    display: flex;
    flex-direction: column;

    .ov-count {
      font-size: 24px;
      font-weight: 700;
      color: #1e1b4b;
      line-height: 1.2;
    }
    .ov-sub { font-size: 14px; color: #9ca3af; font-weight: 400; }
    .ov-label { font-size: 12px; color: #9ca3af; margin-top: 2px; }
  }

  .ov-arrow { color: #d1d5db; font-size: 12px; }
}

// 时间轴
.timeline-bar {
  display: flex;
  align-items: flex-start;
  background: #fff;
  border-radius: 12px;
  padding: 24px 32px;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
}

.phase {
  display: flex;
  align-items: center;
  flex: 1;
  position: relative;

  .phase-dot {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: 600;
    flex-shrink: 0;
    background: #f3f4f6;
    color: #9ca3af;
    border: 2px solid #e5e7eb;
  }

  .phase-info {
    display: flex;
    flex-direction: column;
    margin-left: 10px;
    .phase-name { font-size: 13px; font-weight: 600; color: #374151; }
    .phase-time { font-size: 11px; color: #9ca3af; margin-top: 2px; }
  }

  .phase-line {
    flex: 1;
    height: 2px;
    background: #e5e7eb;
    margin: 0 16px;
    min-width: 20px;

    &.done { background: $primary; }
  }

  &.completed {
    .phase-dot { background: $primary; color: #fff; border-color: $primary; }
    .phase-info .phase-name { color: $primary; }
  }

  &.current {
    .phase-dot {
      background: #fff;
      color: $primary;
      border-color: $primary;
      box-shadow: 0 0 0 4px rgba($primary, 0.15);
    }
    .phase-info .phase-name { color: $primary; font-weight: 700; }
  }
}

// Tab
.tab-card {
  border: none;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);

  .config-desc { margin-bottom: 0; }
}

.rich-content {
  :deep(img) { max-width: 100%; border-radius: 8px; }
}

// 通知
.notice-list {
  .notice-item {
    padding: 14px 16px;
    background: #faf9fe;
    border-radius: 10px;
    margin-bottom: 10px;

    .notice-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 6px;
    }
    .notice-title { font-weight: 600; color: #1e1b4b; font-size: 14px; }
    .notice-body { font-size: 13px; color: #4b5563; line-height: 1.6; }
    .notice-time { font-size: 11px; color: #9ca3af; margin-top: 8px; }
  }
}
</style>
