<template>
  <div class="my-container">
    <mark-header />
    <div class="tw-flex tw-gap-1">
      <mark-history
        v-if="!isSingleStudent"
        :subjectCode="subjectCode"
        :groupNumber="groupNumber"
        :get-history="getArbitrateHistory"
      />
      <ArbitrateMarkList />
      <mark-body @error="renderError" />
      <mark-board-key-board
        v-if="showMarkBoardKeyBoard"
        @submit="saveTaskToServer(false)"
        @unselectiveSubmit="saveTaskToServer(true)"
      />
      <mark-board-mouse
        v-if="showMarkBoardMouse"
        @submit="saveTaskToServer(false)"
        @unselectiveSubmit="saveTaskToServer(true)"
      />
    </div>
  </div>
  <AnswerModal />
  <PaperModal />
  <MinimapModal />
</template>

<script setup lang="ts">
import { computed, onMounted, watch } from "vue";
// 要共用UI就要共用store
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 { message } from "ant-design-vue";
import {
  clearArbitrateTask,
  getArbitrateSetting,
  getArbitrateTaskStatus,
  getOneOfArbitrateTask,
  getSingleArbitrateTask,
  saveArbitrateTask,
} from "@/api/arbitratePage";
import ArbitrateMarkList from "./ArbitrateMarkList.vue";
import type { Setting, Task } from "@/types";
import { isNumber } from "lodash";
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";

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
  );
  store.setting.examType = settingRes.data.examType;
  store.setting.fileServer = settingRes.data.fileServer;
  store.setting.subject = settingRes.data.subject;
  store.setting.userName = settingRes.data.userName;
  store.setting.selective = settingRes.data.selective;
  store.setting.uiSetting = {
    "answer.paper.scale": 1,
    "score.board.collapse": false,
    "normal.mode": "keyboard",
  } as Setting["uiSetting"];
  store.setting.splitConfig = settingRes.data.splitConfig;

  if (store.setting.subject?.answerUrl) {
    store.setting.subject.answerUrl =
      store.setting.fileServer + store.setting.subject?.answerUrl;
  }
  if (store.setting.subject?.paperUrl) {
    store.setting.subject.paperUrl =
      store.setting.fileServer + store.setting.subject?.paperUrl;

    if (!store.isScanImage) {
      await getPaper(store);
    }
  }
}
async function updateStatus() {
  const res = await getArbitrateTaskStatus(subjectCode, groupNumber);
  if (res.data.valid) store.status = res.data;
}
async function updateTask() {
  // const mkey = "fetch_task_key";
  message.info({ content: "获取任务中...", duration: 1.5 });
  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;
  } else {
    store.message = res.data.message;
  }
}

// async function reloadAndfetchTask() {
//   // 需要清除缓存，才能取到之前锁定的任务
//   await updateClearTask();
//   // await updateSetting();
//   await fetchTask();
// }
watch(
  () => store.historyOpen,
  async () => {
    if (!store.historyOpen) {
      await updateClearTask();
      // await updateSetting();
      await fetchTask();
    }
  }
);

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

const showMarkBoardKeyBoard = computed(() => {
  return store.setting.uiSetting["normal.mode"] === "keyboard";
});
const showMarkBoardMouse = computed(() => {
  return store.setting.uiSetting["normal.mode"] === "mouse";
});

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

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

// FIXME: 更新分数，在评卷界面不需要
watch(
  () => store.currentTask,
  () => {
    const markResult = store.currentTask?.markResult;

    if (markResult && store.currentTask) {
      const scoreList = store.currentTask.questionList.map((q) => q.score);
      markResult.scoreList = [...(scoreList as number[])];
      markResult.markerScore =
        (markResult.scoreList.filter((s) => isNumber(s)) as number[]).reduce(
          (acc, v) => (acc += Math.round(v * 100)),
          0
        ) / 100;
    }
  },
  { deep: true }
);

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

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

const saveTaskToServer = async (unselective: boolean) => {
  if (!store.currentTask) return;
  console.log("save inspect task to server");
  const mkey = "save_task_key";
  message.loading({ content: "保存评卷任务...", key: mkey });
  let res;
  if (unselective) {
    res = (await saveArbitrateTask(
      store.currentTask.libraryId + "",
      store.currentTask.studentId + "",
      -1,
      [],
      true
    )) as any;
  } else {
    res = (await saveArbitrateTask(
      store.currentTask.libraryId + "",
      store.currentTask.studentId + "",
      store.currentTask.markResult.markerScore as number,
      store.currentTask.markResult.scoreList as Array<number>,
      false
    )) 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 {
      EventBus.emit("should-reload-history");
    }
  } 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%;
  overflow: clip;
}
</style>
