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

<script setup lang="ts">
import { onMounted } from "vue";
// import {
//   getInspectedSettingOfImportInspect,
//   getSingleInspectedTaskOfImportInspect,
//   saveInspectedTaskOfImportInspect,
// } from "@/api/importInspectPage";
import {
  getInspectedSettingOfImportInspect,
  getSingleInspectedTaskOfImportInspect,
  saveInspectedTaskOfImportInspect,
} from "@/api/scoreVerify";
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 "../studentInspect/MarkBody.vue";
import MarkBody from "./markBody.vue";
import MarkBoardInspect from "./MarkBoardInspect.vue";
import type { AdminPageSetting } from "@/types";
import { message } from "ant-design-vue";
import { addFileServerPrefixToTask } from "@/utils/utils";

const route = useRoute();
const { studentId } = route.query as {
  studentId: string | number;
};

let studentIds: (number | string)[] = $ref([]);
// let tagIds: number[] = $ref([]);
let currentStudentId = $ref<string | number>(0);

async function updateSetting() {
  const settingRes = await getInspectedSettingOfImportInspect(
    studentId as string
  );
  const { examType, fileServer, doubleTrack } = settingRes.data;
  store.initSetting({ examType, fileServer, doubleTrack } as AdminPageSetting);
  // store.status.totalCount = settingRes.data.inspectCount;
  // store.status.markedCount = 0;

  // if (!settingRes.data.inspectCount) {
  //   store.message = settingRes.data.message;
  // } else {
  if (studentId) {
    studentIds = [studentId];
  } else {
    studentIds = settingRes.data.studentIds || [];
  }
  // tagIds = settingRes.data.tagIds;
  // }
}
// 要通过fetchTask调用
async function updateTask() {
  if (!currentStudentId) {
    return;
  }
  const mkey = "fetch_task_key";
  void message.info({ content: "获取任务中...", duration: 1.5, key: mkey });
  let res = await getSingleInspectedTaskOfImportInspect("" + currentStudentId);
  void message.success({
    content: res.data.task?.studentId ? "获取成功" : "无任务",
    key: mkey,
  });
  isCurrentTagged = !!res.data.flagged;
  if (res.data.task?.studentId) {
    let rawTask = res.data.task;
    store.currentTask = addFileServerPrefixToTask(rawTask);
  } else {
    store.message = res.data.message;
  }
}
let isCurrentTagged = $ref(false);

// 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.totalCount = studentIds.length;
  store.status.markedCount = studentIds.indexOf(currentStudentId) + 1;
  await updateTask();
}

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

const saveTaskToServer = async () => {
  const mkey = "save_task_key";
  void message.loading({ content: "标记评卷任务...", key: mkey });
  const res = await saveInspectedTaskOfImportInspect(
    currentStudentId + "",
    !isCurrentTagged + ""
  );
  if (res.data.success) {
    void message.success({
      content: isCurrentTagged ? "取消标记成功" : "标记成功",
      key: mkey,
      duration: 2,
    });
    isCurrentTagged = !isCurrentTagged;
    // if (isCurrentTagged) {
    //   tagIds.splice(tagIds.indexOf(currentStudentId), 1);
    // } else {
    //   tagIds.push(currentStudentId);
    // }
  } else {
    console.log(res.data.message);
    void 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>
