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

<script setup lang="ts">
import { computed, onMounted, watch } from "vue";
import {
  clearInspectedTask,
  getInspectedSetting,
  getInspectedTaskStatus,
  getOneOfInspectedTask,
  getSingleInspectedTask,
  rejectInspectedTask,
  saveInspectedTask,
} from "@/api/inspectPage";
import { isScanImage, store } from "@/store/store";
import MarkHeader from "./MarkHeader.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, Task, Setting } from "@/types";
import { message } from "ant-design-vue";
import { getPaper } from "@/api/jsonMark";
import { getInspectedHistory } from "@/api/inspectPage";
import EventBus from "@/plugins/eventBus";

const route = useRoute();
let isSingleStudent = !!route.query.studentId;
const {
  studentId,
  subjectCode,
  startScore,
  endScore,
  mainNumber,
  mainStartScore,
  mainEndScore,
  questionScore,
  unselective,
} = route.query as {
  studentId: string;
  subjectCode: string;
  startScore: string;
  endScore: string;
  mainNumber: string;
  mainStartScore: string;
  mainEndScore: string;
  questionScore: string;
  unselective: string;
};

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

async function updateSetting() {
  const settingRes = await getInspectedSetting(subjectCode);
  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.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?.paperUrl) {
    store.setting.subject.paperUrl =
      store.setting.fileServer + store.setting.subject?.paperUrl;

    if (!isScanImage()) {
      await getPaper(store);
    }
  }
}
async function updateStatus() {
  const res = await getInspectedTaskStatus({
    subjectCode,
    mainNumber,
    startScore,
    endScore,
    mainStartScore,
    mainEndScore,
    questionScore,
    unselective,
  });
  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.studentId) {
    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 (res.data.subject) store.setting.subject = res.data.subject;
    // if (store.currentTask)
    //   Object.assign(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();
}

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,
    unselective,
  });
}

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";
  message.loading({ content: "保存评卷任务...", key: mkey });
  const res = (await saveInspectedTask(realStudentId.value)) 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 rejectQuestions = async (questions: Array<Question>) => {
  const mkey = "reject_task_key";
  message.loading({ content: "打回评卷任务...", key: mkey });
  const res = (await rejectInspectedTask(
    realStudentId.value,
    questions
  )) as any;
  if (res.data.success && store.currentTask) {
    store.currentTask = undefined;
    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>
