<template>
  <div class="my-container">
    <mark-header />
    <div class="tw-flex tw-gap-1">
      <mark-body v-if="store.isScanImage" @error="renderError" />
      <CommonMarkBody
        v-else
        :use-mark-result="false"
        :store="store"
        :make-track="() => {}"
        @error="renderError"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from "vue";
import { store } from "@/store/store";
import MarkHeader from "./MarkHeader.vue";
import { useRoute } from "vue-router";
import MarkBody from "../inspect/MarkBody.vue";
import CommonMarkBody from "@/features/mark/CommonMarkBody.vue";
import type { Task } from "@/types";
import { message } from "ant-design-vue";
import { getSingleStudentTask } from "@/api/studentTrackPage";
import { getInspectedSetting } from "@/api/inspectPage";
import { getPaper } from "@/api/jsonMark";
import { addFileServerPrefixToTask } from "@/utils/utils";

const route = useRoute();
let studentId = route.query.studentId;
let subjectCode = route.query.subjectCode as string;

async function updateSetting() {
  const settingRes = await getInspectedSetting(subjectCode);
  const { examType, fileServer, subject, userName, splitConfig } =
    settingRes.data;
  store.initSetting({
    examType,
    fileServer,
    subject,
    userName,
    splitConfig,
  });
  if (store.setting.subject?.paperUrl && store.isMultiMedia) {
    await getPaper(store);
  }
}

async function updateTask() {
  const mkey = "fetch_task_key";
  void message.info({ content: "获取任务中...", duration: 1.5, key: mkey });
  let res = await getSingleStuTask();
  void message.success({
    content: res.data.studentId ? "获取成功" : "无任务",
    key: mkey,
  });

  if (res.data.studentId) {
    let rawTask = res.data as Task;
    store.currentTask = addFileServerPrefixToTask(rawTask);
  } else {
    store.message = res.data.message;
  }
}

async function fetchTask() {
  await updateTask();
}

onMounted(async () => {
  await updateSetting();
  await fetchTask();
});

async function getSingleStuTask() {
  return getSingleStudentTask(studentId as string);
}

const renderError = () => {
  store.currentTask = undefined;
  store.message = "加载失败，请重新加载。";
};
</script>

<style scoped>
.my-container {
  width: 100%;
}
</style>
