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

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import {
  getInspectedSetting,
  getSingleInspectedTask,
  saveInspectedTask,
} from "@/api/importInspectPage";
import { store } from "@/features/mark/store";
import MarkHeader from "./MarkHeader.vue";
import { useRoute } from "vue-router";
import MarkBody from "./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.value = settingRes.data.studentIds;
    tagIds.value = settingRes.data.tagIds;
  }
}
// 要通过fetchTask调用
async function updateTask() {
  // const mkey = "fetch_task_key";
  message.info({ content: "获取任务中...", duration: 1.5 });
  let res;
  if (currentStudentId.value) {
    res = await getSingleInspectedTask("" + currentStudentId.value);
  } 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.value.includes(currentStudentId.value)
);
const isFirst = computed(
  () => studentIds.value.indexOf(currentStudentId.value) === 0
);
const isLast = computed(
  () =>
    studentIds.value.indexOf(currentStudentId.value) ===
    studentIds.value.length - 1
);

async function fetchTask(next: boolean, init?: boolean) {
  if (init) {
    currentStudentId.value = studentIds.value[0];
  } else if (isLast.value && next) {
    return; // currentStudentId.value是最后一个不调用
  } else if (isFirst.value && !next) {
    return; // currentStudentId.value是第一个不调用
  } else {
    currentStudentId.value =
      studentIds.value[
        studentIds.value.indexOf(currentStudentId.value) + (next ? 1 : -1)
      ];
  }
  if (!currentStudentId.value) return; // 无currentStudentId不调用
  store.status.markedCount =
    studentIds.value.indexOf(currentStudentId.value) + 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.value + "",
    !isCurrentTagged.value + ""
  )) as any;
  if (res.data.success) {
    message.success({
      content: isCurrentTagged.value ? "取消标记成功" : "标记成功",
      key: mkey,
      duration: 2,
    });
    if (isCurrentTagged.value) {
      tagIds.value.splice(tagIds.value.indexOf(currentStudentId.value), 1);
    } else {
      tagIds.value.push(currentStudentId.value);
    }
  } 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>
