<template>
  <div class="data-check">
    <div class="check-menu">
      <div class="check-menu-body">
        <ul>
          <li
            v-for="(item, index) in studentList"
            :key="item.id"
            :class="{ 'is-active': dataCheckStore.curStudent?.id === item.id }"
            @click="onSelectStudent(index)"
          >
            {{ item.examNumber }}
          </li>
        </ul>
      </div>
      <div class="check-menu-page">
        <SimplePagination
          :total="total"
          :page-size="pageSize"
          @change="onChangeListPage"
        />
      </div>
    </div>
    <div class="check-body">
      <ScanImage
        v-if="dataCheckStore.curPage && isOriginImage"
        :key="dataCheckStore.curPage.kid"
        @prev="onPrevPage"
        @next="onNextPage"
      />
      <SliceImage v-if="dataCheckStore.curPage && !isOriginImage" />
    </div>

    <CheckAction @search="onSearch" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, onBeforeUnmount } from "vue";
import { message } from "ant-design-vue";
import { CaretLeftOutlined, CaretRightOutlined } from "@ant-design/icons-vue";

import { DataCheckListFilter, DataCheckListItem } from "@/ap/types/dataCheck";
import { dataCheckList } from "@/ap/dataCheck";
import { StudentPage } from "./types";
import { useDataCheckStore, useUserStore } from "@/store";

import SimplePagination from "@/components/SimplePagination/index.vue";
import ScanImage from "./ScanImage/index.vue";
import SliceImage from "./SliceImage/index.vue";
import CheckAction from "./CheckAction.vue";

defineOptions({
  name: "DataCheck",
});

const dataCheckStore = useDataCheckStore();
dataCheckStore.resetInfo();
const userStore = useUserStore();

let searchModel = {} as DataCheckListFilter;
const pageNumber = ref(1);
const pageSize = ref(20);
const total = ref(0);
const pageCount = ref(0);
const studentList = ref<DataCheckListItem[]>([]);
const dataList = ref<StudentPage[]>([]);
const loading = ref(false);

async function getList() {
  loading.value = true;
  const datas = {
    ...searchModel,
    pageNumber: pageNumber.value,
    pageSize: pageSize.value,
  };
  const res = await dataCheckList(datas).catch(() => null);
  loading.value = false;
  if (!res) return;

  total.value = res.totalCount;
  pageCount.value = res.pageCount;
  studentList.value = res.result;

  parseStudentPageList(res.result);
}

function parseStudentPageList(students: DataCheckListItem[]) {
  dataList.value = [] as StudentPage[];

  students.forEach((student, studentIndex) => {
    student.papers.forEach((paper, paperIndex) => {
      if (!paper.pages) return;
      paper.pages.forEach((page, pageIndex) => {
        const row: StudentPage = {
          ...page,
          paperId: paper.id,
          paperIndex,
          paperNumber: paper.number,
          pageIndex,
          studentIndex,
          studentId: student.id,
          examId: searchModel.examId,
          kid: `${student.id}-${studentIndex}-${paperIndex}-${pageIndex}`,
        };
        if (
          row.question?.result?.length &&
          Array.isArray(row.question?.result)
        ) {
          row.question.result = row.question.result.map((item: string) =>
            item.replace(/[^#a-zA-Z]/g, "")
          );
        }
        dataList.value.push(row);
      });
    });
  });
}

// imageType
const isOriginImage = computed(() => {
  return dataCheckStore.imageType === "ORIGIN";
});

// table
async function onChangeListPage(index: number) {
  pageNumber.value = index;
  await getList();
  selectPage(0);
}
async function onSearch(datas: DataCheckListFilter) {
  console.log("datas", datas);
  searchModel = {
    ...datas,
    examStatus:
      datas.examStatus === "UNCHECK"
        ? "UNCHECK1,UNCHECK2,UNCHECK3"
        : datas.examStatus,
  };
  pageNumber.value = 1;
  if (!searchModel.subjectCode) {
    total.value = 0;
    pageCount.value = 0;
    studentList.value = [];
    dataCheckStore.resetInfo();
    window.$message.error("请选择科目");
    return;
  }
  await getList();
  selectPage(0);
}

// onSearch({ examId: userStore.curExam.id } as DataCheckListFilter);

// student
function onSelectStudent(index: number) {
  const student = studentList.value[index];
  const pageIndex = dataList.value.findIndex(
    (item) => item.studentId === student.id
  );
  if (pageIndex === -1) return;

  selectPage(pageIndex);
}

async function onPrevStudent() {
  if (dataCheckStore.curStudentIndex <= 0) {
    if (pageNumber.value === 1) {
      message.error("没有上一个学生了");
      return;
    }

    pageNumber.value--;
    await getList();
    onSelectStudent(studentList.value.length - 1);
    return;
  }

  onSelectStudent(dataCheckStore.curStudentIndex - 1);
}

async function onNextStudent() {
  if (dataCheckStore.curStudentIndex >= studentList.value.length - 1) {
    if (pageNumber.value >= pageCount.value) {
      message.error("没有下一个学生了");
      return;
    }

    pageNumber.value++;
    await getList();
    onSelectStudent(0);
    return;
  }

  onSelectStudent(dataCheckStore.curStudentIndex + 1);
}

// page
function selectPage(index: number) {
  dataCheckStore.setInfo({
    curPage: dataList.value[index],
    curPageIndex: index,
  });

  if (!dataCheckStore.curPage) return;

  const curStudent = studentList.value[
    dataCheckStore.curPage.studentIndex
  ] as DataCheckListItem;
  dataCheckStore.setInfo({
    curStudent,
    curStudentIndex: dataCheckStore.curPage.studentIndex,
  });
}

async function onPrevPage() {
  if (dataCheckStore.curPageIndex <= 0) {
    if (pageNumber.value === 1) {
      message.error("没有上一张了");
      return;
    }

    pageNumber.value--;
    await getList();
    selectPage(dataList.value.length - 1);
    return;
  }

  selectPage(dataCheckStore.curPageIndex - 1);
}

async function onNextPage() {
  if (dataCheckStore.curPageIndex >= dataList.value.length - 1) {
    if (pageNumber.value >= pageCount.value) {
      message.error("没有下一张了");
      return;
    }

    pageNumber.value++;
    await getList();
    selectPage(0);
    return;
  }

  selectPage(dataCheckStore.curPageIndex + 1);
}

// shortcut
function registShortcut() {
  document.addEventListener("keydown", shortcutHandle);
}
function removeShortcut() {
  document.removeEventListener("keydown", shortcutHandle);
}
function shortcutHandle(e: KeyboardEvent) {
  const moveAction = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"];
  if (!moveAction.includes(e.code) || e.repeat) {
    return;
  }

  e.preventDefault();

  if (e.code === "ArrowUp") {
    onPrevStudent();
    return;
  }
  if (e.code === "ArrowDown") {
    onNextStudent();
    return;
  }
  if (e.code === "ArrowLeft") {
    onPrevPage();
    return;
  }
  if (e.code === "ArrowRight") {
    onNextPage();
    return;
  }
}

onMounted(() => {
  registShortcut();
});
onBeforeUnmount(() => {
  removeShortcut();
});
</script>
