<template>
  <main class="public-page">
    <section class="certificate-page">
      <p class="kicker">电子证书</p>
      <h1>证书公开展示</h1>
      <el-alert v-if="message" class="notice" :title="message" :type="messageType" :closable="false" />

      <article v-if="certificate" class="certificate-card">
        <span :class="['status', certificate.status === 'valid' ? 'ok' : 'bad']">{{ statusText(certificate.status) }}</span>
        <h2>{{ certificate.certificate_name }}</h2>
        <p class="name">{{ certificate.learner_name }}</p>
        <p class="copy">
          已完成 {{ certificate.course_name || certificate.project_code }} {{ certificate.stage_name || "" }} 相关培训学习。
        </p>
        <dl class="meta">
          <div>
            <dt>证书编号</dt>
            <dd>{{ certificate.certificate_no }}</dd>
          </div>
          <div>
            <dt>发证日期</dt>
            <dd>{{ certificate.issue_date }}</dd>
          </div>
          <div>
            <dt>发证单位</dt>
            <dd>{{ certificate.issuer_name }}</dd>
          </div>
        </dl>
        <el-button v-if="certificate.can_download_pdf" type="primary" class="download" :loading="downloading" @click="downloadPdf">
          下载 PDF 证书
        </el-button>
      </article>
    </section>
  </main>
</template>

<script setup lang="ts">
import { ElLoading, ElMessage } from "element-plus";
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";

import { http, type PublicCertificate } from "../api";
import { apiErrorMessage, saveBlob } from "../download";

const route = useRoute();
const token = String(route.params.token);
const certificate = ref<PublicCertificate | null>(null);
const message = ref("");
const messageType = ref<"success" | "warning" | "error">("success");
const downloading = ref(false);

function statusText(status: string) {
  return status === "valid" ? "有效" : "已作废";
}

async function loadCertificate() {
  try {
    const { data } = await http.get<PublicCertificate>(`/public/certificates/token/${token}`);
    certificate.value = data;
    message.value = data.status === "valid" ? "该证书真实有效。" : "该证书已作废，请联系发证单位核实。";
    messageType.value = data.status === "valid" ? "success" : "warning";
  } catch (error: any) {
    message.value = error?.response?.data?.detail || "链接无效或已失效";
    messageType.value = "error";
  }
}

async function downloadPdf() {
  if (!certificate.value) return;
  downloading.value = true;
  const loading = ElLoading.service({
    lock: true,
    text: "PDF正在排队或生成，请稍候...",
    background: "rgba(255, 255, 255, 0.72)",
  });
  try {
    const { data } = await http.get(`/public/certificates/token/${token}/download`, { responseType: "blob" });
    saveBlob(data, `${certificate.value.certificate_no}.pdf`);
  } catch (error: any) {
    ElMessage.error(await apiErrorMessage(error, "PDF生成失败，请稍后再试"));
  } finally {
    loading.close();
    downloading.value = false;
  }
}

onMounted(loadCertificate);
</script>

<style scoped>
.public-page {
  min-height: 100vh;
  background: #f7fafc;
  padding: 36px 20px;
}

.certificate-page {
  max-width: 760px;
  margin: 0 auto;
  background: #ffffff;
  border: 1px solid #e1ebef;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 16px 46px rgba(76, 102, 118, 0.08);
}

.kicker {
  margin: 0 0 6px;
  color: #208a87;
  font-size: 13px;
  font-weight: 700;
}

h1,
h2 {
  margin: 0;
}

h1 {
  font-size: 28px;
}

.notice {
  margin-top: 20px;
}

.certificate-card {
  margin-top: 20px;
  border: 1px solid #dfe9ec;
  border-radius: 10px;
  padding: 34px;
  text-align: center;
  background: #fbfefe;
}

.status {
  display: inline-flex;
  height: 24px;
  align-items: center;
  border-radius: 999px;
  padding: 0 9px;
  margin-bottom: 16px;
  font-size: 12px;
}

.status.ok {
  color: #116d6b;
  background: #dff5f3;
}

.status.bad {
  color: #991b1b;
  background: #fee2e2;
}

.name {
  margin: 24px 0 10px;
  font-size: 30px;
  font-weight: 700;
}

.copy {
  max-width: 560px;
  margin: 0 auto 24px;
  color: #475569;
  line-height: 1.8;
}

.meta {
  display: grid;
  gap: 10px;
  margin: 0;
  color: #64748b;
}

.meta dt {
  font-size: 12px;
}

.meta dd {
  margin: 3px 0 0;
  color: #172033;
}

.download {
  margin-top: 24px;
}
</style>
