<template>
  <section>
    <header class="page-head">
      <div>
        <h2>一期工作台</h2>
        <p>快速查看证书、导入和状态数据。</p>
      </div>
      <el-button type="primary" @click="downloadTemplate">下载导入模板</el-button>
    </header>

    <div class="stats">
      <el-card v-for="item in cards" :key="item.label" class="stat" shadow="never">
        <span>{{ item.label }}</span>
        <strong>{{ item.value }}</strong>
      </el-card>
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive } from "vue";
import { useRouter } from "vue-router";

import { http } from "../api";
import { downloadFile } from "../download";

const router = useRouter();
const summary = reactive({
  learner_count: 0,
  certificate_count: 0,
  valid_certificate_count: 0,
  voided_certificate_count: 0,
  recent_import_count: 0,
});

const cards = computed(() => [
  { label: "学员总数", value: summary.learner_count },
  { label: "证书总数", value: summary.certificate_count },
  { label: "有效证书", value: summary.valid_certificate_count },
  { label: "作废证书", value: summary.voided_certificate_count },
  { label: "近期导入", value: summary.recent_import_count },
]);

async function loadSummary() {
  try {
    const { data } = await http.get("/admin/dashboard/summary");
    Object.assign(summary, data);
  } catch {
    localStorage.removeItem("admin_token");
    await router.push("/admin/login");
  }
}

function downloadTemplate() {
  downloadFile("/admin/import-batches/template", "certificate-import-template.xlsx");
}

onMounted(loadSummary);
</script>

<style scoped>
.page-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
}

.page-head p {
  margin: 6px 0 0;
  color: #64748b;
}

.stats {
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  gap: 14px;
}

.stat {
  border: 1px solid #dbe6ea;
  border-radius: 10px;
  background: linear-gradient(180deg, #ffffff, #f8fbfc);
  box-shadow: 0 8px 22px rgba(42, 64, 78, 0.055);
}

.stat span {
  color: #64748b;
  font-size: 13px;
  font-weight: 650;
}

.stat strong {
  display: block;
  margin-top: 8px;
  font-size: 30px;
  font-weight: 800;
  color: #172033;
}

@media (max-width: 1100px) {
  .stats {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
</style>
