<template>
  <div class="my-container">
    <mark-header />
    <div class="tw-flex tw-gap-1">
      <mark-body @error="renderError" usingImage="sheetUrls" />
      <MarkBoardInspect
        :tagged="isCurrentTagged"
        :isFirst="isFirst"
        :isLast="isLast"
        @makeTag="saveTaskToServer"
        @fetchTask="fetchTask"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from "vue";
import {
  getInspectedSetting,
  getSingleInspectedTask,
  saveInspectedTask,
} from "@/api/importInspectPage";
import { store } from "@/store/store";
import MarkHeader from "./MarkHeader.vue";
import { useRoute } from "vue-router";
import MarkBody from "../inspect/MarkBody.vue";
import MarkBoardInspect from "./MarkBoardInspect.vue";
import type { Task, Setting } from "@/types";
import { message } from "ant-design-vue";

const route = useRoute();
let isSingleStudent = !!route.query.studentId;
const { studentId } = route.query as {
  studentId: string;
};

let studentIds = $ref([] as Array<number>);
let tagIds = $ref([] as Array<number>);
let currentStudentId = $ref(0);

async function updateSetting() {
  const settingRes = await getInspectedSetting(studentId);
  store.setting.examType = settingRes.data.examType;
  store.setting.fileServer = settingRes.data.fileServer;
  store.status.totalCount = settingRes.data.inspectCount;
  store.status.markedCount = 0;
  store.setting.uiSetting = {
    "answer.paper.scale": 1,
    "score.board.collapse": false,
    "normal.mode": "keyboard",
  } as Setting["uiSetting"];

  if (!settingRes.data.inspectCount) {
    store.message = settingRes.data.message;
  } else {
    studentIds = settingRes.data.studentIds;
    tagIds = settingRes.data.tagIds;
  }
}
// 要通过fetchTask调用
async function updateTask() {
  // const mkey = "fetch_task_key";
  message.info({ content: "获取任务中...", duration: 1.5 });
  let res;
  if (currentStudentId) {
    res = await getSingleInspectedTask("" + currentStudentId);
  } else {
    return;
  }

  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
    );
    store.currentTask = res.data;
    store.setting.subject = res.data.subject;
  } else {
    store.message = res.data.message;
  }
}

const isCurrentTagged = computed(() => tagIds.includes(currentStudentId));
const isFirst = computed(() => studentIds.indexOf(currentStudentId) === 0);
const isLast = computed(
  () => studentIds.indexOf(currentStudentId) === studentIds.length - 1
);

async function fetchTask(next: boolean, init?: boolean) {
  if (init) {
    currentStudentId = studentIds[0];
  } else if (isLast && next) {
    return; // currentStudentId是最后一个不调用
  } else if (isFirst && !next) {
    return; // currentStudentId是第一个不调用
  } else {
    currentStudentId =
      studentIds[studentIds.indexOf(currentStudentId) + (next ? 1 : -1)];
  }
  if (!currentStudentId) return; // 无currentStudentId不调用
  store.status.markedCount = studentIds.indexOf(currentStudentId) + 1;
  await updateTask();
}

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

const realStudentId = computed(
  () => (isSingleStudent ? studentId : store.currentTask?.studentId) as string
);
const saveTaskToServer = async () => {
  const mkey = "save_task_key";
  message.loading({ content: "标记评卷任务...", key: mkey });
  const res = (await saveInspectedTask(
    currentStudentId + "",
    !isCurrentTagged + ""
  )) as any;
  if (res.data.success) {
    message.success({
      content: isCurrentTagged ? "取消标记成功" : "标记成功",
      key: mkey,
      duration: 2,
    });
    if (isCurrentTagged) {
      tagIds.splice(tagIds.indexOf(currentStudentId), 1);
    } else {
      tagIds.push(currentStudentId);
    }
  } else {
    console.log(res.data.message);
    message.error({ content: res.data.message, key: mkey, duration: 10 });
  }
};

const renderError = () => {
  store.currentTask = undefined;
  store.message = "加载失败，请重新加载。";
};
</script>

<style scoped>
.my-container {
  width: 100%;
  overflow: clip;
}
</style>
