<template>
  <div class="my-container">
    <mark-header />
    <div class="tw-flex tw-gap-1">
      <mark-history
        @reload="reloadAndfetchTask"
        :should-reload="shouldReloadHistory"
      />
      <mark-body @error="renderError" />
      <MarkBoardInspect @inspect="saveTaskToServer" @reject="rejectQuestions" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { store } from "@/features/mark/store";
import MarkHeader from "./MarkHeader.vue";
import { useRoute } from "vue-router";
import MarkBody from "./MarkBody.vue";
import MarkHistory from "./MarkHistory.vue";
import MarkBoardInspect from "./MarkBoardInspect.vue";
import type { MarkStore, Question, Task } from "@/types";
import { message } from "ant-design-vue";
import {
  clearInspectedTask,
  getInspectedTaskStatus,
  getOneOfInspectedTask,
  rejectInspectedTask,
  saveInspectedTask,
} from "@/api/libraryInspectPage";
import { getPaper } from "@/api/jsonMark";
import { getInspectedSetting } from "@/api/inspectPage";

const route = useRoute();
let isSingleStudent = !!route.query.libraryId;
const { subjectCode, groupNumber, libraryId } = route.query as {
  subjectCode: string;
  groupNumber: string;
  libraryId: string; // TODO: for未来单一任务
};

async function updateClearTask() {
  await clearInspectedTask(subjectCode, groupNumber);
}

async function updateSetting() {
  const settingRes = await getInspectedSetting(subjectCode);
  store.setting.examType = settingRes.data.examType;
  store.setting.fileServer = settingRes.data.fileServer;
  store.setting.userName = settingRes.data.userName;
  store.setting.subject = settingRes.data.subject;
  store.setting.uiSetting = {
    "answer.paper.scale": 1,
    "score.board.collapse": false,
  } as MarkStore["setting"]["uiSetting"];
  store.setting.splitConfig = settingRes.data.splitConfig;
  if (store.setting.subject?.paperUrl) {
    store.setting.subject.paperUrl =
      store.setting.fileServer + store.setting.subject?.paperUrl;

    await getPaper(store);
  }
}
async function updateStatus() {
  const res = await getInspectedTaskStatus(subjectCode, groupNumber);
  if (res.data.valid) store.status = res.data;
}
async function updateTask() {
  // const mkey = "fetch_task_key";
  message.info({ content: "获取任务中...", duration: 2 });
  let res;
  // if (isSingleStudent) {
  //   res = await getSingleStuTask();
  // } else {
  res = await getOneOfStuTask();
  // }
  // message.success({ content: "获取成功", key: mkey });

  if (res.data.libraryId) {
    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;
    // if (store.currentTask)
    //   store.setting.subject = store.currentTask
    //     .subject as MarkStore["setting"]["subject"];
  } else {
    store.message = res.data.message;
  }
}

const shouldReloadHistory = ref(0);

async function reloadAndfetchTask() {
  await updateClearTask();
  await updateSetting();
  await fetchTask();
}

async function fetchTask() {
  !isSingleStudent && (await updateStatus());
  await updateTask();
}

onMounted(async () => {
  // await updateClearTask();
  // fetchTask(); // mark-header 会调用 (watchEffect)
});

async function getSingleStuTask() {
  // return getSingleInspectedTask(libraryId);
}

async function getOneOfStuTask() {
  return getOneOfInspectedTask(subjectCode, groupNumber);
}

const realLibraryId = computed(
  () => (isSingleStudent ? libraryId : store.currentTask?.libraryId) as string
);
const saveTaskToServer = async () => {
  console.log("save inspect task to server");
  const mkey = "save_task_key";
  message.loading({ content: "保存评卷任务...", key: mkey });
  const res = (await saveInspectedTask(realLibraryId.value)) as any;
  if (res.data.success && store.currentTask) {
    message.success({ content: "复核成功", key: mkey, duration: 2 });
    if (!store.historyOpen) {
      store.currentTask = undefined;
      if (!isSingleStudent) fetchTask();
    } else {
      shouldReloadHistory.value = Date.now();
    }
  } else if (res.data.message) {
    console.log(res.data.message);
    message.error({ content: res.data.message, key: mkey, duration: 10 });
  } else if (!store.currentTask) {
    message.warn({ content: "暂无新任务", key: mkey, duration: 10 });
  }
};

const rejectQuestions = async (questions: Array<Question>) => {
  if (!store.currentTask) return;
  const mkey = "reject_task_key";
  message.loading({ content: "打回评卷任务...", key: mkey });
  const res = (await rejectInspectedTask(
    //realLibraryId.value,
    store.currentTask.libraryId + "",
    questions
  )) as any;
  if (res.data.success) {
    store.currentTask = undefined;
    message.success({ content: "打回成功", key: mkey, duration: 2 });
    if (!store.historyOpen) {
      store.currentTask = undefined;
      if (!isSingleStudent) fetchTask();
    } else {
      shouldReloadHistory.value = Date.now();
    }
  } else if (res.data.message) {
    console.log(res.data.message);
    message.error({ content: res.data.message, key: mkey, duration: 10 });
  } else if (!store.currentTask) {
    message.warn({ content: "暂无新任务", key: mkey, duration: 10 });
  }
};

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

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