<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.imageName }}
          </li>
        </ul>
      </div>
      <div class="check-menu-page">
        <SimplePagination
          v-model="pageNumber"
          :total="total"
          :page-size="pageSize"
          @change="onChangeListPage"
        />
      </div>
    </div>
    <div class="check-body">
      <ScanImage
        v-if="dataCheckStore.curPage"
        :key="dataCheckStore.curPage.kid"
        :cant-change-img="true"
        @prev="onPrevPage"
        @next="onNextPage"
      />
    </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 { allCheckList, fetchAndParseData } from "./api";
import { StudentPage } from "./types";
import { useDataCheckStore, useAppStore } from "@/store";

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

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

const dataCheckStore = useDataCheckStore();
const appStore = useAppStore();
dataCheckStore.resetInfo();

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

async function getAllStudents() {
  loading.value = true;
  const res = await allCheckList().catch(() => null);
  loading.value = false;
  if (!res) return;

  allStudentList.value = res;
  total.value = res.length;
  pageCount.value = Math.ceil(total.value / pageSize.value);
}

async function getList() {
  studentList.value = allStudentList.value.slice(
    (pageNumber.value - 1) * pageSize.value,
    pageNumber.value * pageSize.value
  );

  parseStudentPageList(studentList.value);
}

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);
      });
    });
  });
}

// table
function onChangeListPage(index: number) {
  pageNumber.value = index;
  getList();
  selectPage(0);
}
async function onSearch() {
  pageNumber.value = 1;
  await getAllStudents();
  onChangeListPage(1);
}

// 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);
}

function getImgDpi(imgWidth: number): number {
  const dpi = (25.4 * imgWidth) / 183;

  if (Math.abs(dpi - 100) < 5) {
    return 100;
  }
  if (Math.abs(dpi - 150) < 5) {
    return 150;
  }
  return 150;
}

function getImgSize(url: string) {
  return new Promise<{ width: number; height: number }>((resolve) => {
    const img = new Image();
    img.src = url;
    console.log(url);

    img.onload = () => {
      resolve({
        width: img.width,
        height: img.height,
      });
    };
  });
}

// page
async function selectPage(index: number) {
  const recogData = await fetchAndParseData(dataList.value[index].recogUri);
  const size = await getImgSize(dataList.value[index].sheetUri);
  dataList.value[index].recogDpi = getImgDpi(size.width);
  dataList.value[index].recogData = recogData;
  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(async () => {
  const appConfig = await window.electronApi.getAppIni();
  if (!appConfig.base.serverUrl) {
    message.error("请先设置服务器地址");
    return;
  }
  appStore.setState({ serverUrl: appConfig.base.serverUrl });
  registShortcut();
  onSearch();
});
onBeforeUnmount(() => {
  removeShortcut();
});
</script>
