<template>
  <div class="my-container">
    <mark-header />
    <div class="tw-flex tw-gap-1">
      <mark-history
        v-if="!isSingleStudent"
        :subjectCode="subjectCode"
        :groupNumber="groupNumber"
        orderTimeField="inspectTime"
        :getHistory="getLibraryInspectedHistoryOfLibraryInspect"
      />
      <mark-body @error="renderError" />
      <MarkBoardInspect @inspect="saveTaskToServer" @reject="rejectQuestions" />
    </div>
  </div>
  <MinimapModal />
</template>

<script setup lang="ts">
import { onMounted, watch } from "vue";
import { store } from "@/store/store";
import MarkHeader from "./MarkHeader.vue";
import MinimapModal from "@/features/mark/MinimapModal.vue";
import { useRoute } from "vue-router";
import MarkBody from "./MarkBody.vue";
import MarkHistory from "@/features/mark/MarkHistory.vue";
import MarkBoardInspect from "./MarkBoardInspect.vue";
import type { Question } from "@/types";
import { message } from "ant-design-vue";
import {
  clearInspectedTaskOfLibraryInspect,
  getInspectedTaskStatusOfLibraryInspect,
  getLibraryInspectedHistoryOfLibraryInspect,
  getOneOfInspectedTaskOfLibraryInspect,
  rejectInspectedTaskOfLibraryInspect,
  saveInspectedTaskOfLibraryInspect,
} from "@/api/libraryInspectPage";
import { getPaper } from "@/api/jsonMark";
import { getAdminPageSetting } from "@/api/inspectPage";
import EventBus from "@/plugins/eventBus";
import { addFileServerPrefixToTask } from "@/utils/utils";

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 clearInspectedTaskOfLibraryInspect(subjectCode, groupNumber);
}

async function updateSetting() {
  const settingRes = await getAdminPageSetting(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 updateStatus() {
  const res = await getInspectedTaskStatusOfLibraryInspect(
    subjectCode,
    groupNumber
  );
  if (res.data.valid) Object.assign(store.status, res.data);
}
async function updateTask() {
  const mkey = "fetch_task_key";
  void message.info({ content: "获取任务中...", duration: 1.5, key: mkey });
  let res = await getOneOfStuTask();
  void message.success({
    content: res.data.studentId ? "获取成功" : "无任务",
    key: mkey,
  });

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

watch(
  () => store.historyOpen,
  async () => {
    if (!store.historyOpen) {
      await updateClearTask();
      await fetchTask();
    }
  }
);

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

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

async function getOneOfStuTask() {
  return getOneOfInspectedTaskOfLibraryInspect(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";
  void message.loading({ content: "保存评卷任务...", key: mkey });
  const res = await saveInspectedTaskOfLibraryInspect(realLibraryId);
  if (res.data.success && store.currentTask) {
    void message.success({ content: "复核成功", key: mkey, duration: 2 });
    if (!store.historyOpen) {
      store.currentTask = undefined;
      if (!isSingleStudent) await fetchTask();
    } else {
      EventBus.emit("should-reload-history");
    }
  } else if (res.data.message) {
    console.log(res.data.message);
    void message.error({ content: res.data.message, key: mkey, duration: 10 });
  } else if (!store.currentTask) {
    void message.warn({ content: "暂无新任务", key: mkey, duration: 10 });
  }
};

const rejectQuestions = async (questions: Array<Question>) => {
  if (!store.currentTask) return;
  const mkey = "reject_task_key";
  void message.loading({ content: "打回评卷任务...", key: mkey });
  const res = await rejectInspectedTaskOfLibraryInspect(
    store.currentTask.libraryId + "",
    questions
  );
  if (res.data.success) {
    store.currentTask = undefined;
    void message.success({ content: "打回成功", key: mkey, duration: 2 });
    if (!store.historyOpen) {
      store.currentTask = undefined;
      if (!isSingleStudent) await fetchTask();
    } else {
      EventBus.emit("should-reload-history");
    }
  } else if (res.data.message) {
    console.log(res.data.message);
    void message.error({ content: res.data.message, key: mkey, duration: 10 });
  } else if (!store.currentTask) {
    void message.warn({ content: "暂无新任务", key: mkey, duration: 10 });
  }
};

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

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