<template>
  <div class="my-container">
    <mark-header />
    <div class="tw-flex tw-gap-1">
      <mark-history
        v-if="!isSingleStudent"
        :subjectCode="subjectCode"
        :groupNumber="groupNumber"
        :getHistory="getArbitrateHistory"
      />
      <ArbitrateMarkList />
      <mark-body @error="renderError" />
      <template v-if="store.isTrackMode">
        <mark-board-track @submit="saveTaskToServerByTrack" />
      </template>
      <template v-else>
        <mark-board-key-board
          v-if="store.shouldShowMarkBoardKeyBoard"
          @submit="saveTaskToServer(false)"
          @unselectiveSubmit="saveTaskToServer(true)"
        />
        <mark-board-mouse
          v-if="store.shouldShowMarkBoardMouse"
          @submit="saveTaskToServer(false)"
          @unselectiveSubmit="saveTaskToServer(true)"
        />
      </template>
    </div>
  </div>
  <AnswerModal />
  <PaperModal />
  <MinimapModal />
</template>

<script setup lang="ts">
import { onMounted, watch, h } from "vue";
import { store } from "@/store/store";
import MarkHeader from "./MarkHeader.vue";
import { useRoute } from "vue-router";
import MarkBody from "./MarkBody.vue";
import MarkBoardKeyBoard from "@/features/mark/MarkBoardKeyBoard.vue";
import MarkBoardMouse from "@/features/mark/MarkBoardMouse.vue";
import MinimapModal from "@/features/mark/MinimapModal.vue";
import MarkHistory from "@/features/mark/MarkHistory.vue";
import MarkBoardTrack from "@/features/mark/MarkBoardTrack.vue";
import { message } from "ant-design-vue";
import {
  clearArbitrateTask,
  getArbitrateSetting,
  getArbitrateTaskStatus,
  getOneOfArbitrateTask,
  getSingleArbitrateTask,
  saveArbitrateTask,
} from "@/api/arbitratePage";
import ArbitrateMarkList from "./ArbitrateMarkList.vue";
import AnswerModal from "../mark/AnswerModal.vue";
import PaperModal from "../mark/PaperModal.vue";
import { getPaper } from "@/api/jsonMark";
import { getArbitrateHistory } from "@/api/arbitratePage";
import EventBus from "@/plugins/eventBus";
import { addFileServerPrefixToTask, preDrawImage } from "@/utils/utils";
import { isNumber } from "lodash-es";
import type { Question } from "@/types";

const route = useRoute();
let isSingleStudent = !!route.query.historyId;
const {
  subjectCode,
  groupNumber,
  historyId: libraryId,
} = route.query as {
  subjectCode: string;
  groupNumber: string;
  historyId: string;
};

async function updateClearTask() {
  await clearArbitrateTask(libraryId, subjectCode);
}

async function updateSetting() {
  const settingRes = await getArbitrateSetting(
    libraryId,
    subjectCode,
    groupNumber
  );
  const { examType, fileServer, subject, userName, splitConfig, enableSplit } =
    settingRes.data;
  store.initSetting({
    examType,
    fileServer,
    subject,
    userName,
    splitConfig,
    enableSplit,
  });
  /*****************************根据本地临时会话存储的mode内容********************************* */
  let arbitrateLocalMode = sessionStorage.getItem("arbitrate_local_mode");
  if (
    arbitrateLocalMode &&
    (arbitrateLocalMode === "TRACK" || arbitrateLocalMode === "COMMON")
  ) {
    store.setting.mode = arbitrateLocalMode;
  }
  /************************************************************** */
  store.setting.selective = settingRes.data.selective;

  if (store.setting.subject?.paperUrl && store.isMultiMedia) {
    await getPaper(store);
  }
}
async function updateStatus() {
  const res = await getArbitrateTaskStatus(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;
  if (isSingleStudent) {
    res = await getSingleStuTask();
  } else {
    res = await getOneOfStuTask();
  }
  void message.success({
    content: res.data.studentId ? "获取成功" : "无任务",
    key: mkey,
  });

  if (res.data.studentId) {
    let rawTask = res.data;
    let t = addFileServerPrefixToTask(rawTask);
    if (store.isScanImage && !!t) {
      await preDrawImage(t);
    }
    store.currentTask = t;
  } 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();
});

watch(
  () => store.currentTask,
  () => {
    // 重置当前选择的quesiton和score
    store.currentQuestion = undefined;
    store.currentScore = undefined;
  }
);

async function getSingleStuTask() {
  return getSingleArbitrateTask(libraryId);
}

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

const saveTaskToServerByTrack = async () => {
  let trackList = store.currentTask.markResult.trackList;
  let specialTagList = store.currentTask.markResult.specialTagList;
  await saveTaskToServer(false, trackList, specialTagList);
};

const saveTaskToServer = async (
  unselective: boolean,
  trackList?: any,
  specialTagList?: any
) => {
  if (!store.currentTask) return;
  const markResult = store.currentTask.markResult;
  if (!markResult) return;
  console.log("save inspect task to server");
  const mkey = "save_task_key";
  void message.loading({ content: "保存评卷任务...", key: mkey });
  let res;
  if (unselective) {
    res = await saveArbitrateTask(
      store.currentTask.libraryId + "",
      store.currentTask.studentId + "",
      -1,
      [],
      true
    );
  } else {
    type SubmitError = {
      question: Question;
      index: number;
      error: string;
    };
    const errors: SubmitError[] = [];
    markResult.scoreList.forEach((score, index) => {
      if (!store.currentTask) return;
      const question = store.currentTask.questionList[index];
      let error;
      if (!isNumber(score)) {
        error = `${question.mainNumber}-${question.subNumber}${
          question.questionName ? "（" + question.questionName + "）" : ""
        } 没有给分，不能提交。`;
      } else if (isNumber(question.maxScore) && score > question.maxScore) {
        error = `${question.mainNumber}-${question.subNumber}${
          question.questionName ? "（" + question.questionName + "）" : ""
        } 给分大于最高分不能提交。`;
      } else if (isNumber(question.minScore) && score < question.minScore) {
        error = `${question.mainNumber}-${question.subNumber}${
          question.questionName ? "（" + question.questionName + "）" : ""
        } 给分小于最低分不能提交。`;
      }
      if (error) {
        errors.push({ question, index, error });
      }
    });
    if (errors.length) {
      console.log(errors);
      const msg = errors.map((v) => h("div", `${v.error}`));
      return message.warning({
        content: h("span", ["校验失败", ...msg]),
        duration: 10,
        key: mkey,
      });
    }
    res = await saveArbitrateTask(
      store.currentTask.libraryId + "",
      store.currentTask.studentId + "",
      store.currentTask.markResult.markerScore,
      store.currentTask.markResult.scoreList,
      false,
      trackList,
      specialTagList
    );
  }
  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 renderError = () => {
  store.currentTask = undefined;
  store.message = "加载失败，请重新加载。";
};
</script>

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