<template>
  <div class="title cl" style="background: #fff">
    <span class="y"
      >共有<b id="total-count">{{ examList.items.length }}</b
      >场考试，请选择</span
    >
    <h2>考试列表</h2>
  </div>
  <table cellpadding="0" cellspacing="0" width="100%" class="tablelist">
    <thead>
      <th>ID</th>
      <th>考试名称</th>
      <th>创建时间</th>
      <th>操作</th>
    </thead>
    <tbody id="exam-list">
      <tr v-for="(exam, index) in showExams.items" :key="index">
        <td>{{ exam.id }}</td>
        <td>{{ exam.name }}</td>
        <td>{{ exam.examTime }}</td>
        <td>
          <a-button @click="selectExam(exam)">进入考试</a-button>
          <a-button @click="downloadImg(exam)">图片下载</a-button>
        </td>
      </tr>
    </tbody>
  </table>
  <a-pagination
    style="margin-top: 20px; float: right"
    v-model:current="currentPage"
    :total="examList.items.length"
    show-less-items
    @change="pageChange"
  />
</template>

<script setup lang="ts">
import { store } from "@/store";
import { onMounted, reactive, ref } from "vue";
import { getExams } from "@/api/api";
import { useRouter } from "vue-router";
import { Store } from "@/types";
const router = useRouter();

let currentPage = ref(1);
let pageSize = 10;
let examList = reactive({ items: [] as Array<Store["env"]["exam"]> });
let showExams = reactive({ items: [] as Array<Store["env"]["exam"]> });

onMounted(async () => {
  await fetchData();
});

const fetchData = async () => {
  const exams = await getExams(currentPage.value, 1000);
  examList.items = exams.data;
  currentPage.value = store.env.pageNumber || 1;
  showExams.items = examList.items.slice(
    (currentPage.value - 1) * pageSize,
    currentPage.value * pageSize
  );
};

const pageChange = (page: number, pageSize: number) => {
  // console.log(page, pageSize);
  currentPage.value = page;
  // fetchData();
  showExams.items = examList.items.slice(
    (page - 1) * pageSize,
    page * pageSize
  );
};

const selectExam = (exam: Store["env"]["exam"]) => {
  store.env.exam = exam;
  store.env.examId = exam.id;
  router.push("/home");
};

const downloadImg = (exam: Store["env"]["exam"]) => {
  store.env.exam = exam;
  store.env.examId = exam.id;
  store.env.pageNumber = currentPage.value;
  router.push("/image-download");
};
</script>
