<template>
  <main class="public-page">
    <PublicServiceHeader />
    <section class="certificate-page">
      <header class="page-title">
        <p class="kicker">DIGITAL CERTIFICATE</p>
        <h1>电子证书</h1>
        <p>查看证书签发信息并下载正式 PDF 文件</p>
      </header>
      <el-alert v-if="message" class="notice" :title="message" :type="messageType" :closable="false" />

      <article v-if="certificate" class="certificate-card">
        <span :class="['status-icon', certificate.status === 'valid' ? 'ok' : 'bad']">
          <el-icon><CircleCheck v-if="certificate.status === 'valid'" /><Warning v-else /></el-icon>
        </span>
        <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>{{ coursePeriodText }}</dd>
          </div>
          <div>
            <dt>发证日期</dt>
            <dd>{{ certificate.issue_date }}</dd>
          </div>
        </dl>
        <el-button v-if="certificate.can_download_pdf" type="primary" :icon="Download" class="download" :loading="downloading" @click="downloadPdf">
          下载 PDF 证书
        </el-button>
      </article>
    </section>
    <footer class="page-foot">慧遇书院电子证书服务</footer>
  </main>
</template>

<script setup lang="ts">
import { CircleCheck, Download, Warning } from "@element-plus/icons-vue";
import { ElLoading, ElMessage } from "element-plus";
import { computed, onMounted, ref } from "vue";
import { useRoute } from "vue-router";

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

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);
const coursePeriodText = computed(() => {
  if (!certificate.value) return "";
  const start = certificate.value.course_start_date || certificate.value.issue_date;
  const end = certificate.value.course_end_date || certificate.value.issue_date;
  return `${start} 至 ${end}`;
});

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: "当前查询人数较多，请稍后。。。",
    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: #f4f6f7;
}

.certificate-page {
  max-width: 820px;
  margin: 0 auto;
  padding: 54px 20px 36px;
}

.page-title {
  text-align: center;
}

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

h1,
h2 {
  margin: 0;
}

h1 {
  font-size: 34px;
}

.page-title > p:last-child {
  margin: 9px 0 0;
  color: #6c7982;
  font-size: 14px;
}

.notice {
  margin-top: 20px;
}

.certificate-card {
  margin-top: 22px;
  border: 1px solid #dce3e6;
  border-top: 3px solid #b28a43;
  border-radius: 7px;
  padding: 38px;
  text-align: center;
  background: #ffffff;
  box-shadow: 0 14px 36px rgba(31, 47, 57, 0.08);
}

.status-icon {
  width: 46px;
  height: 46px;
  display: grid;
  place-items: center;
  margin: 0 auto 10px;
  border-radius: 50%;
  font-size: 25px;
}

.status-icon.ok {
  color: #176f69;
  background: #e8f3f1;
}

.status-icon.bad {
  color: #a6312c;
  background: #fae9e8;
}

.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;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 0;
  margin: 0;
  border: 1px solid #e3e8ea;
  border-radius: 6px;
  color: #64748b;
}

.meta div {
  min-width: 0;
  padding: 14px;
  border-right: 1px solid #e3e8ea;
}

.meta div:nth-child(3) {
  border-right: 0;
}

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

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

.download {
  margin-top: 24px;
  min-width: 180px;
}

.page-foot {
  padding: 22px 20px 30px;
  color: #8a949b;
  font-size: 12px;
  text-align: center;
}

@media (max-width: 640px) {
  .certificate-page {
    padding-top: 36px;
  }

  .certificate-card {
    padding: 28px 18px;
  }

  .meta {
    grid-template-columns: 1fr;
  }

  .meta div {
    border-right: 0;
    border-bottom: 1px solid #e3e8ea;
  }

  .meta div:last-child {
    border-bottom: 0;
  }
}
</style>
