<template>
  <div class="review">
    <div class="review-head">
      <a-row align="center">
        <a-col :span="9">
          <h2 class="review-title">419872222786601 - 考生2 - CET4</h2>
        </a-col>
        <a-col :span="6">
          <div class="review-stat">
            <p class="color-success">
              <CheckCircleFilled />已处理：{{ progress.finishCount }}
            </p>
            <p class="color-error">
              <CloseCircleFilled />未处理：{{ progress.todoCount }}
            </p>
          </div>
        </a-col>
        <a-col :span="9">
          <a-button v-if="reviewStore.tabKey === 'review'" :disabled="loading">
            <template #icon><ArrowLeftOutlined /></template> 上一个
          </a-button>
        </a-col>
      </a-row>
    </div>

    <!-- body -->
    <div class="review-body">
      <ReviewImage />
    </div>

    <!-- action -->
    <ReviewAction @mark="onMark" @reset="onReset" @search="onSearch" />

    <!-- reset confirm -->
    <ResetConfirmDialog
      ref="resetConfirmDialogRef"
      :subject="resetSubject"
      @confirm="onResetConfirm"
    />
    <!-- ReviewMarkPan -->
    <ReviewMarkPan v-if="reviewStore.curTask" @mark="onMark" />
  </div>
</template>

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

import { reviewTaskList, reviewTaskReset, reviewTaskSave } from "@/ap/review";
import { ReviewTaskListItem } from "@/ap/types/review";
import { SubjectItem } from "@/ap/types/base";

import { useUserStore, useReviewStore } from "@/store";
import useLoading from "@/hooks/useLoading";

import ReviewAction from "./ReviewAction.vue";
import ReviewImage from "./ReviewImage.vue";
import ResetConfirmDialog from "./ResetConfirmDialog.vue";
import ReviewMarkPan from "./ReviewMarkPan.vue";

const userStore = useUserStore();
const reviewStore = useReviewStore();

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

const searchModel = reactive({
  examId: userStore.curExam.id,
  subjectCode: "",
});

const { loading, setLoading } = useLoading();
const dataList = ref<ReviewTaskListItem[]>([]);
const curTaskIndex = ref(0);

async function getTasks() {
  // TODO:假设一次取3个
  const res = await reviewTaskList(searchModel);
  dataList.value = res || [];
}

function setCurTask() {
  reviewStore.setInfo({ curTask: dataList.value[curTaskIndex.value] });
}

function getNextTask() {
  if (curTaskIndex.value >= dataList.value.length - 1) {
    await getTasks();
    if (!dataList.value.length) {
      message.error("没有下一个了！");
      reviewStore.setInfo({ curTask: null });
      return;
    }
    curTaskIndex.value = 0;
    setCurTask();
    return;
  }

  curTaskIndex.value++;
  setCurTask();
}

function getPrevTask() {
  if (loading.value) return;
  loading.value = true;

  if (curTaskIndex.value <= 0) {
    let result = true;
    await getTasks().catch(() => {
      result = false;
    });
    if (!result) return;

    loading.value = false;
    if (!dataList.value.length) {
      message.error("没有上一个了！");
      reviewStore.setInfo({ curTask: null });
      return;
    }
    curTaskIndex.value = dataList.value.length - 1;
    setCurTask();
    return;
  }

  curTaskIndex.value--;
  setCurTask();
}

// actions
async function onMark(result: boolean) {
  if (!reviewStore.curTask) return;

  if (loading.value) return;
  loading.value = true;

  try {
    await reviewTaskSave({ id: reviewStore.curTask.id, result });
    reviewStore.setInfo({
      curTask: Object.assign({}, reviewStore.curTask, {
        markStatus: result,
      }),
    });

    if (reviewStore.tabKey === "history") return;

    await getNextTask();
  } catch (error) {
    loading.value = false;
  }
}

async function onSearch(subjectCode: string) {
  searchModel.subjectCode = subjectCode;
  await getTasks();

  curTaskIndex.value = 0;
  setCurTask();
}

const resetConfirmDialogRef = ref();
const resetSubject = ref<SubjectItem | null>(null);
async function onReset(data: SubjectItem | null) {
  resetSubject.value = data;
  resetConfirmDialogRef.value?.open();
}

function onResetConfirm() {
  onSearch("");
}

// watch
watch(
  () => reviewStore.tabKey,
  (val) => {
    if (val === "review") {
      reviewStore.setInfo({
        curTask: dataList.value[curTaskIndex.value] || null,
      });
    }
  }
);

// 键盘事件
function registKeyEvent() {
  document.addEventListener("keydown", keyEventHandle);
}
function removeKeyEvent() {
  document.removeEventListener("keydown", keyEventHandle);
}

function keyEventHandle(e: KeyboardEvent) {
  if (e.code === "Enter") {
    e.preventDefault();
    onMark(true);
    return;
  }
}

onMounted(() => {
  registKeyEvent();
});

onBeforeUnmount(() => {
  removeKeyEvent();
});
</script>
