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

<script setup lang="ts">
import { onMounted, watch } from "vue";
import {
  clearInspectedTask,
  getAdminPageSetting,
  getInspectedTaskStatus,
  getOneOfInspectedTask,
  getSingleInspectedTask,
  rejectInspectedTask,
  saveInspectedTask,
} from "@/api/inspectPage";
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 { getPaper } from "@/api/jsonMark";
import { getInspectedHistory } from "@/api/inspectPage";
import EventBus from "@/plugins/eventBus";
import { addFileServerPrefixToTask } from "@/utils/utils";

let isMultComments = $ref(false); //是否双评
const getIsMultComments = (bool: boolean) => {
  isMultComments = bool;
};
let hasScrollToBottom = $ref(false);
const getScrollStatus = () => {
  hasScrollToBottom = true;
};
watch(
  () => store.setting,
  () => {
    hasScrollToBottom = !store.setting?.inspectScroll;
  },
  { deep: true }
);
const route = useRoute();
let isSingleStudent = !!route.query.studentId;
const {
  studentId,
  subjectCode,
  startScore,
  endScore,
  mainNumber,
  mainStartScore,
  mainEndScore,
  questionScore,
  selectiveStatus,
  secretNumber,
} = route.query as {
  studentId: string;
  subjectCode: string;
  startScore: string;
  endScore: string;
  mainNumber: string;
  mainStartScore: string;
  mainEndScore: string;
  questionScore: string;
  selectiveStatus: string;
  secretNumber: string;
};

async function updateClearTask() {
  await clearInspectedTask(studentId, subjectCode);
}

async function updateSetting() {
  const settingRes = await getAdminPageSetting(subjectCode);
  const {
    examType,
    fileServer,
    subject,
    userName,
    splitConfig,
    enableSplit,
    doubleTrack,
    inspectScroll,
  } = settingRes.data;
  store.initSetting({
    examType,
    fileServer,
    subject,
    userName,
    splitConfig,
    enableSplit,
    doubleTrack,
    inspectScroll,
  });
  if (store.setting.subject?.paperUrl && store.isMultiMedia) {
    await getPaper(store);
  }
}
async function updateStatus() {
  const res = await getInspectedTaskStatus({
    subjectCode,
    mainNumber,
    startScore,
    endScore,
    mainStartScore,
    mainEndScore,
    questionScore,
    selectiveStatus,
    secretNumber,
  });
  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;
    store.currentTask = addFileServerPrefixToTask(rawTask);
    if (res.data.subject) store.setting.subject = res.data.subject;
  } else {
    store.message = res.data.message;
  }
}

watch(
  () => store.historyOpen,
  async () => {
    if (!store.historyOpen) {
      await updateClearTask();
      await updateSetting();
      await fetchTask();
    }
  }
);
async function fetchTask() {
  !isSingleStudent && (await updateStatus());
  await updateTask();
}

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

async function getSingleStuTask() {
  return getSingleInspectedTask(studentId);
}

async function getOneOfStuTask() {
  return getOneOfInspectedTask({
    subjectCode,
    mainNumber,
    startScore,
    endScore,
    mainStartScore,
    mainEndScore,
    questionScore,
    selectiveStatus,
    secretNumber,
  });
}

const realStudentId = $computed(
  () => (isSingleStudent ? studentId : store.currentTask?.studentId) 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 saveInspectedTask(realStudentId);
  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,
  reason = "",
}: {
  questions: Array<Question>;
  reason: string;
}) => {
  const mkey = "reject_task_key";
  void message.loading({ content: "打回评卷任务...", key: mkey });
  const res = await rejectInspectedTask(realStudentId, questions, reason);
  if (res.data.success && store.currentTask) {
    store.currentTask = undefined;
    void message.success({ content: "打回成功", key: mkey, duration: 2 });
    if (!store.historyOpen) {
      store.currentTask = undefined;
      if (!isSingleStudent) {
        await fetchTask();
        hasScrollToBottom = false;
      }
    } 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>
