<script setup lang="ts">
import { httpApp } from "@/plugins/axiosApp";
import router from "@/router";
import { useTimers } from "@/setups/useTimers";
import { store } from "@/store/store";
import { onMounted, onUnmounted } from "vue";
import { useRoute } from "vue-router";

const route = useRoute();
const examId = route.params.examId;
const examRecordDataId = route.params.examRecordDataId;

let spentTime = $ref(0);
const { addInterval } = useTimers();

addInterval(() => spentTime++, 1000);

async function realSubmitPaper() {
  store.increaseGlobalMaskCount("SubmitPaper");
  store.spinMessage = "正在交卷中...";
  try {
    await httpApp.get("/api/ecs_oe_student/examControl/endExam", {
      "axios-retry": {
        retries: 10,
        retryDelay: () => 10 * 1000,
        shouldResetTimeout: true,
      },
      noErrorMessage: true,
    });
    logger({
      cnl: ["server"],
      act: "交卷成功",
      ext: { spentTime, UA: navigator.userAgent },
    });
  } catch (e) {
    $message.warning("交卷失败");
    logger({ cnl: ["server"], act: "交卷失败", possibleError: e });
  }

  // 交卷失败也转向考试结束界面，失败原因包括网络故障等
  void router.replace({
    path: `/online-exam/exam/${examId}/examRecordData/${examRecordDataId}/end`,
  });
}

onMounted(() => realSubmitPaper());

onUnmounted(() => {
  store.decreaseGlobalMaskCount("SubmitPaper");
  store.spinMessage = "";
  try {
    const allCount = store.exam.compareResultMap.size;
    const remainedCount = [...store.exam.compareResultMap].filter(
      (v) => !v[1]
    ).length;
    logger({
      cnl: ["server"],
      act: "交卷前检测抓拍照片数量",
      dtl: allCount - remainedCount - 1 ? "不完全检测" : "完全检测",
      ext: { allCount, remainedCount },
    });
  } catch (error) {
    logger({
      cnl: ["server"],
      act: "SubmitPaper onUnmounted",
      possibleError: error,
    });
  }
});
</script>

<template>
  <div></div>
</template>
