<script setup lang="ts">
import { httpApp } from "@/plugins/axiosApp";
import { ExamType, OnlineExam } from "@/types/student-client";
import { closeMediaStream } from "@/utils/camera";
import { onMounted, watch } from "vue";
import OnlineExamList from "./OnlineExamList.vue";

const { examType = "ONLINE" } = defineProps<{ examType?: ExamType }>();

let courses: OnlineExam[] = $ref([]);
let endCourses: OnlineExam[] = $ref([]);

let loading = $ref(true);

onMounted(async () => {
  // router.back 时关闭摄像头
  closeMediaStream();
  logger({
    cnl: ["local", "server"],
    pgu: "AUTO",
    act: "进入页面",
  });

  await getData().finally(() => (loading = false));
});

watch(
  () => examType,
  async () => {
    loading = true;
    await getData().finally(() => (loading = false));
  }
);

async function getData() {
  courses = [];
  let examListRes: { data: OnlineExam[]; status: number } = {
    data: [],
    status: 0,
  };
  let url = "";
  if (examType === "ONLINE") {
    url = "/api/branch_ecs_oe_admin/examControl/queryExamList";
  } else if (examType === "ONLINE_HOMEWORK") {
    url = "/api/branch_ecs_oe_admin/examControl/queryHomeworkList";
  }
  let tried = 0;
  while (tried < 5) {
    examListRes = await httpApp.get(url, {
      noErrorMessage: true,
      "axios-retry": {
        retries: 4,
        retryCondition(error) {
          // console.log(error);
          if (error.response?.status === 503) {
            tried++;
            return true;
          } else {
            return false;
          }
        },
        retryDelay: () => 10 * 1000,
        shouldResetTimeout: true,
      },
    });
    tried = 5;
  }

  if (examListRes.status !== 200) {
    logger({
      cnl: ["server"],
      act: "待考列表获取失败",
      dtl: "调用待考列表获取接口超过失败次数",
    });
    $message.error("服务器繁忙(503)！请稍后重试。", {
      duration: 15,
      closable: true,
    });
    return;
  } else {
    courses = examListRes.data || [];
    if (examType === "ONLINE") {
      let url = "/api/branch_ecs_oe_admin/examControl/queryExamEndList";
      endCourses = (await httpApp.get(url)).data || [];
    }
  }
}
		
async function refresh() {
  loading = true;
  await getData().finally(() => (loading = false));
}
</script>

<template>
  <div class="part-box">
    <div v-if="loading">loading</div>
    <OnlineExamList
      v-else
      :courses="courses"
      :endCourses="endCourses"
      :examType="examType"
      @refresh="refresh"
    />
  </div>
</template>

<style scoped></style>
