<template>
  <div class="my-container">
    <mark-header />
    <div class="tw-flex tw-gap-1">
      <mark-body @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 "./MarkBody.vue";
import type { Task } from "@/types";
import { message } from "ant-design-vue";
import {
  getSingleLibraryTask,
  getSingleLibraryTaskTrial,
} from "@/api/libraryTrackPage";
import { getInspectedSetting } from "@/api/inspectPage";
import { getPaper } from "@/api/jsonMark";
import { addFileServerPrefixToTask } from "@/utils/utils";

const route = useRoute();
let libraryId = route.query.libraryId;
let subjectCode = route.query.subjectCode;

async function updateSetting() {
  const settingRes = await getInspectedSetting(subjectCode as string);
  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";
  message.info({ content: "获取任务中...", duration: 1.5, key: mkey });
  let res = await getSingleStuTask();
  message.success({
    content: res.data.task.libraryId ? "获取成功" : "无任务",
    key: mkey,
  });

  if (res.data.task) {
    store.setting.fileServer = res.data.fileServer;
    store.setting.splitConfig = res.data.splitConfig;
    store.setting.groupNumber = res.data.groupNumber;

    let rawTask = res.data.task 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() {
  if (route.name === "TrialRoute") {
    return getSingleLibraryTaskTrial(libraryId as string);
  } else {
    return getSingleLibraryTask(libraryId as string);
  }
}

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

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