<script setup>
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import PublicFrame from '@/components/common/PublicFrame.vue';
import PageState from '@/components/common/PageState.vue';
import StatusBadge from '@/components/common/StatusBadge.vue';
import { api } from '@/lib/api';
import { formatDate } from '@/lib/format';
import { buildPublicDocuments } from '@/lib/publicDocuments';
import { sessionStore } from '@/stores/session';

const route = useRoute();
const router = useRouter();
const loading = ref(true);
const error = ref('');
const document = ref(null);

async function load() {
  loading.value = true;
  error.value = '';
  try {
    const id = String(route.params.id);
    const data = await api('/api/public/announcements');
    document.value = buildPublicDocuments(sessionStore.state.publicData, data).find(item => item.documentId === id) || null;
    if (document.value?.documentType === 'notice') {
      const detail = await api(`/api/public/notices/${encodeURIComponent(id)}`);
      document.value = { ...document.value, ...detail.notice };
    }
    if (!document.value) throw new Error('公告不存在或尚未公开');
  } catch (requestError) {
    error.value = requestError.message;
  } finally {
    loading.value = false;
  }
}

onMounted(load);
</script>

<template>
  <PublicFrame>
    <section class="app-container document-page">
      <button class="document-page__back" type="button" @click="router.push('/announcements')">← 返回公开信息目录</button>
      <PageState :loading="loading" :error="error" @retry="load">
        <article v-if="document" class="public-document">
          <header><span>{{ document.category }} · {{ document.subtype }}</span><h1>{{ document.title }}</h1><p>{{ formatDate(document.publishedAt || document.publishAt, true) }}<template v-if="document.author"> · {{ document.author }}</template></p></header>
          <section v-if="document.documentType === 'notice'" class="document-richtext" v-html="document.contentHtml || `<p>${String(document.content || '').replaceAll('\n', '</p><p>')}</p>`"></section>
          <section v-else-if="document.documentType === 'reporting'" class="document-reporting">
            <div class="record-metrics"><article><span>招生计划</span><strong>{{ document.statistics?.totalQuota || 0 }}</strong></article><article><span>正式录取</span><strong>{{ document.statistics?.finalCount || 0 }}</strong></article><article><span>已报到</span><strong>{{ document.statistics?.reportedCount || 0 }}</strong></article><article><span>完成率</span><strong>{{ document.statistics?.reportingRate || 0 }}%</strong></article></div>
            <p>{{ document.decisionNote || document.summary }}</p>
          </section>
          <section v-else class="document-table-wrap">
            <p>{{ document.summary }}</p>
            <table v-if="document.documentType === 'plan'"><thead><tr><th>类别代码</th><th>招生类别</th><th>计划人数</th><th>定向指标</th></tr></thead><tbody><tr v-for="row in document.rows" :key="row.code"><td>{{ row.code }}</td><td>{{ row.name }}</td><td>{{ row.quota }}</td><td>{{ row.indicatorQuota || 0 }}</td></tr></tbody></table>
            <table v-else-if="document.documentType === 'qualification'"><thead><tr><th>报名号</th><th>姓名</th><th>指标资格</th><th>特长类型</th></tr></thead><tbody><tr v-for="row in document.rows" :key="row.registrationNumber"><td>{{ row.registrationNumber }}</td><td>{{ row.name }}</td><td><StatusBadge :value="row.eligible ? 'approved' : 'rejected'" /></td><td>{{ row.specialtyLabel || '普通生' }}</td></tr></tbody></table>
            <table v-else-if="document.documentType === 'admission'"><thead><tr><th>报名号</th><th>姓名</th><th>总成绩</th><th>录取学校</th><th>录取类别</th></tr></thead><tbody><tr v-for="row in document.rows" :key="row.registrationNumber"><td>{{ row.registrationNumber }}</td><td>{{ row.name }}</td><td>{{ row.totalScore }}</td><td>{{ row.admittedSchool }}</td><td>{{ row.categoryName }}</td></tr></tbody></table>
            <table v-else><thead><tr><th>招生学校</th><th>招生类别</th><th>计划数</th><th>录取数</th><th>最高分</th><th>分数线</th></tr></thead><tbody><tr v-for="row in document.rows" :key="`${row.schoolName}-${row.categoryName}`"><td>{{ row.schoolName }}</td><td>{{ row.categoryName }}</td><td>{{ row.planQuota }}</td><td>{{ row.admittedCount }}</td><td>{{ row.highestScore }}</td><td><strong>{{ row.cutoffScore }}</strong></td></tr></tbody></table>
          </section>
        </article>
      </PageState>
    </section>
  </PublicFrame>
</template>
