<template>
  <div class="my-container">
    <mark-header />
    <div class="tw-flex tw-gap-1">
      <mark-history
        @reload="reloadAndfetchTask"
        :should-reload="shouldReloadHistory"
      />
      <ArbitrateMarkList />
      <mark-body @error="renderError" />
      <mark-board-key-board
        v-if="showMarkBoardKeyBoard"
        @submit="saveTaskToServer"
      />
      <mark-board-mouse v-if="showMarkBoardMouse" @submit="saveTaskToServer" />
    </div>
  </div>
  <AnswerModal />
  <PaperModal />
  <MinimapModal />
</template>

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

export default defineComponent({
  name: "Arbitrate",
  components: {
    MarkHeader,
    MarkBody,
    MarkHistory,
    MarkBoardKeyBoard,
    MarkBoardMouse,
    ArbitrateMarkList,
    MinimapModal,
    AnswerModal,
    PaperModal,
  },
  setup: () => {
    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.fileServer = settingRes.data.fileServer;
      store.setting.userName = settingRes.data.userName;
      store.setting.uiSetting = {
        "answer.paper.scale": 1,
        "score.board.collapse": false,
        "normal.mode": "keyboard",
      } as Setting["uiSetting"];
      store.setting.splitConfig = settingRes.data.splitConfig;
      store.setting.subject = settingRes.data.subject;
      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;
      }
    }
    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: 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;
      } 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();
    }

    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,
      () => {
        // 回评切换任务，先删除之前回评任务的markResult
        removeOldPreviousMarkResult();
        store.currentMarkResult = findCurrentTaskMarkResult();

        // 重置当前选择的quesiton和score
        store.currentQuestion = undefined;
        store.currentScore = undefined;
      }
    );

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

        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 realStudentId = computed(
      () =>
        (isSingleStudent ? libraryId : store.currentTask?.libraryId) as string
    );
    const saveTaskToServer = async () => {
      if (!store.currentTask) return;
      console.log("save inspect task to server");
      const mkey = "save_task_key";
      message.loading({ content: "保存评卷任务...", key: mkey });
      const res = (await saveArbitrateTask(
        store.currentTask.libraryId + "",
        store.currentTask.studentId + "",
        store.currentMarkResult?.markerScore as number,
        store.currentMarkResult?.scoreList as Array<number>
      )) 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 renderError = () => {
      store.currentTask = undefined;
      store.message = "加载失败，请重新加载。";
    };

    return {
      store,
      fetchTask,
      reloadAndfetchTask,
      showMarkBoardKeyBoard,
      showMarkBoardMouse,
      saveTaskToServer,
      shouldReloadHistory,
      renderError,
    };
  },
});
</script>

<style scoped>
.my-container {
  width: 100%;
}
a {
  color: #42b983;
}

label {
  margin: 0 0.5em;
  font-weight: bold;
}

code {
  background-color: #eee;
  padding: 2px 4px;
  border-radius: 4px;
  color: #304455;
}
</style>
