<template>
  <div class="my-container">
    <mark-header />
    <div class="tw-flex tw-gap-1">
      <mark-body
        v-if="store.setting.examType === 'SCAN_IMAGE'"
        @error="renderError"
      />
      <CommonMarkBody
        v-else
        :useMarkResult="false"
        :store="store"
        @error="renderError"
        :makeTrack="() => {}"
      />
    </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, Setting } from "@/types";
import { message } from "ant-design-vue";
import { getSingleStudentTask } from "@/api/studentTrackPage";
import { getInspectedSetting } from "@/api/inspectPage";
import { getPaper } from "@/api/jsonMark";

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.isScanImage) {
    await getPaper(store);
  }
}

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

  if (res.data.studentId) {
    let rawTask = res.data as Task;
    rawTask.sliceUrls = rawTask.sliceUrls?.map(
      (s) => store.setting.fileServer + s
    );
    rawTask.sheetUrls = rawTask.sheetUrls?.map(
      (s) => store.setting.fileServer + s
    );
    rawTask.jsonUrl = store.setting.fileServer + rawTask.jsonUrl;
    store.currentTask = res.data;
  } 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>
