<template>
  <div class="my-container">
    <mark-header />
    <div class="tw-flex tw-gap-1">
      <mark-history @reload="reloadAndfetchTask" />
      <mark-body />
      <MarkBoardInspect @inspect="saveTaskToServer" @reject="rejectQuestions" />
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted } from "vue";
import {
  clearInspectedTask,
  getInspectedSetting,
  getInspectedTaskStatus,
  getOneOfInspectedTask,
  getSingleInspectedTask,
  rejectInspectedTask,
  saveInspectedTask,
} from "@/api/inspectPage";
import { store } from "./store";
import MarkHeader from "./MarkHeader.vue";
import { useRoute } from "vue-router";
import MarkBody from "./MarkBody.vue";
import MarkHistory from "./MarkHistory.vue";
import MarkBoardInspect from "./MarkBoardInspect.vue";
import { Question } from "@/types";
import { message } from "ant-design-vue";

export default defineComponent({
  name: "Inspect",
  components: {
    MarkHeader,
    MarkBody,
    MarkHistory,
    MarkBoardInspect,
  },
  setup: () => {
    const route = useRoute();
    let isSingleStudent = !!route.query.studentId;
    const {
      studentId,
      subjectCode,
      startScore,
      endScore,
      mainNumber,
      mainStartScore,
      mainEndScore,
      questionScore,
    } = route.query as {
      studentId: string;
      subjectCode: string;
      startScore: string;
      endScore: string;
      mainNumber: string;
      mainStartScore: string;
      mainEndScore: string;
      questionScore: string;
    };

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

    async function updateSetting() {
      const settingRes = await getInspectedSetting();
      store.setting.fileServer = settingRes.data.fileServer;
      store.setting.userName = settingRes.data.userName;
      store.setting.uiSetting = {
        "answer.paper.scale": 1,
        "score.board.collapse": false,
      };
    }
    async function updateStatus() {
      const res = await getInspectedTaskStatus({
        subjectCode,
        mainNumber,
        startScore,
        endScore,
        mainStartScore,
        mainEndScore,
        questionScore,
      });
      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 });

      store.currentTask = res.data;
      if (store.currentTask) store.setting.subject = store.currentTask.subject;
    }

    async function reloadAndfetchTask() {
      await updateClearTask();
      await fetchTask();
    }

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

    onMounted(async () => {
      await updateClearTask();

      updateSetting();
      // fetchTask(); // mark-header 会调用 (watchEffect)
    });

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

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

    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) {
        store.currentTask = undefined;
        message.success({ content: "复核成功", key: mkey, duration: 2 });
        if (!isSingleStudent) fetchTask();
      } else {
        console.log(res.data.message);
        message.error({ content: res.data.message, 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 (!isSingleStudent) fetchTask();
      } else {
        message.error({ content: res.data.message, duration: 10 });
        console.log(res.data.message);
      }
    };

    return {
      store,
      fetchTask,
      reloadAndfetchTask,
      saveTaskToServer,
      rejectQuestions,
    };
  },
});
</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>
