<script setup>
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import PublicFrame from '@/components/common/PublicFrame.vue';
import { api } from '@/lib/api';
import { formatDate } from '@/lib/format';

const route = useRoute();
const router = useRouter();
const code = ref(String(route.params.code || ''));
const loading = ref(false);
const result = ref(null);
const error = ref('');

async function verify(value = code.value) {
  const normalized = value.trim().toUpperCase();
  if (!normalized) return;
  if (String(route.params.code || '') !== normalized) {
    await router.push(`/verify/${encodeURIComponent(normalized)}`);
    return;
  }
  loading.value = true;
  result.value = null;
  error.value = '';
  try {
    result.value = await api(`/api/public/verifications/${encodeURIComponent(normalized)}`);
  } catch (requestError) {
    error.value = requestError.message;
  } finally {
    loading.value = false;
  }
}

watch(() => route.params.code, value => { code.value = String(value || ''); if (value) verify(String(value)); });
onMounted(() => { if (route.params.code) verify(String(route.params.code)); });
</script>

<template>
  <PublicFrame>
    <section class="verification-page app-container">
      <div class="verification-page__intro"><p>DOCUMENT AUTHENTICITY</p><h1>文书防伪查询</h1><span>核对成绩单和录取通知书的系统签发记录。</span></div>
      <form class="verification-form" @submit.prevent="verify()"><label><span>防伪查询码</span><input v-model="code" required autocomplete="off" placeholder="例如 SR-XXXXXXXXXXXXXXXXXXXXXXXX"></label><button type="submit" :disabled="loading">{{ loading ? '正在核验…' : '立即核验' }}</button></form>
      <section v-if="result?.document" class="verification-result is-valid"><span>✓</span><div><small>VERIFIED DOCUMENT</small><h2>文书真实有效</h2><p>查询码与系统签发记录一致。</p></div><dl><div><dt>文书类型</dt><dd>{{ result.document.typeName }}</dd></div><div><dt>考生</dt><dd>{{ result.document.candidateName }}</dd></div><div><dt>考试</dt><dd>{{ result.document.examName }}</dd></div><div v-if="result.document.schoolName"><dt>录取学校</dt><dd>{{ result.document.schoolName }}</dd></div><div><dt>签发时间</dt><dd>{{ formatDate(result.document.issuedAt, true) }}</dd></div></dl></section>
      <section v-else-if="error" class="verification-result is-invalid"><span>!</span><div><small>NOT VERIFIED</small><h2>未找到有效文书</h2><p>{{ error }}</p></div></section>
      <aside class="verification-safety"><strong>安全提示</strong><p>查询结果只展示脱敏身份与文书摘要。请勿在非官方页面提交密码或验证码。</p></aside>
    </section>
  </PublicFrame>
</template>
