<template>
  <div class="mark arbitrate">
    <mark-header :isSingleStudent="isSingleStudent" />
    <mark-tool :actions="['minimap', 'sizeScale', 'imgScale']" />
    <div class="mark-main">
      <mark-history
        v-if="!isSingleStudent"
        :examId="examId"
        :subjectCode="paperNumber"
        :groupNumber="groupNumber + ''"
        :getHistory="getArbitrateHistory"
      />
      <ArbitrateMarkList />
      <mark-body @error="renderError" />
      <mark-board-track
        v-if="store.isTrackMode"
        @unselectiveSubmit="saveTaskToServer(true)"
        @submit="saveTaskToServerByTrack"
      />
      <template v-if="!store.isTrackMode">
        <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 />
  <MarkBoardTrackDialog v-if="store.isTrackMode" @submit="saveTaskToServer" />
</template>

<script setup lang="ts">
import { onMounted, watch, h } from "vue";
import { store } from "@/store/store";
import MarkHeader from "./MarkHeader.vue";
import MarkTool from "../mark/MarkTool.vue";
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 MarkBoardTrackDialog from "@/features/mark/MarkBoardTrackDialog.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 { getArbitrateHistory } from "@/api/arbitratePage";
import EventBus from "@/plugins/eventBus";
import { isNumber } from "lodash-es";
import type { Question } from "@/types";
import vls from "@/utils/storage";

const { paperNumber, groupNumber, examId, arbitrateId } = vls.get(
  "arbitrate",
  {}
);
let isSingleStudent = !!arbitrateId;

const params = isSingleStudent
  ? { arbitrateId }
  : { paperNumber, groupNumber, examId };

async function updateClearTask() {
  await clearArbitrateTask(params);
}

async function updateSetting() {
  const settingRes = await getArbitrateSetting(params);
  store.setting = Object.assign({}, store.setting, {
    selective: false,
    examType: "SCAN_IMAGE",
    subject: {
      name: settingRes.data.courseName,
      code: settingRes.data.courseCode,
    },
    mode: settingRes.data.markMode,
    enableSplit: false,
  });
}
async function updateStatus() {
  const res = await getArbitrateTaskStatus(params);
  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 ? "获取成功" : "当前无评卷任务",
    key: mkey,
  });

  if (res.data) {
    let rawTask = res.data;
    rawTask.sheetUrls = rawTask.sheetUrls || [];
    // rawTask.sheetUrls = ["/1-1.jpg", "/1-2.jpg"];
    rawTask.sliceUrls = [...rawTask.sheetUrls];
    store.currentTask = rawTask;
  } else {
    store.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(params);
}

async function getOneOfStuTask() {
  return getOneOfArbitrateTask(params);
}

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;

  const mkey = "save_task_key";

  let res;
  if (unselective) {
    res = await saveArbitrateTask(
      store.currentTask.taskId,
      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.taskId + "",
      store.currentTask.studentId + "",
      store.currentTask.markResult.markerScore,
      store.currentTask.markResult.scoreList,
      false,
      trackList,
      specialTagList
    );
  }
  if (!res.data.success) {
    void message.error({
      content: res.data.message || "仲裁失败，请重新尝试！",
      key: mkey,
      duration: 5,
    });
    return;
  }

  if (isSingleStudent) {
    void message.success({
      content: "仲裁成功，页面将在3秒钟之后关闭",
      key: mkey,
      duration: 2,
    });
    setTimeout(() => {
      window.close();
    }, 3000);
    return;
  }

  void message.success({ content: "仲裁成功", key: mkey, duration: 2 });
  if (!store.historyOpen) {
    store.currentTask = undefined;
    await fetchTask();
  } else {
    EventBus.emit("should-reload-history");
  }
};

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