<template>
  <div :class="['mark-history', { hide: !markStore.historyOpen }]">
    <div class="mark-history-title">
      {{ title }}
    </div>
    <div
      v-if="showSearch && markStore.getStatusValueName !== '试评'"
      class="mark-history-search"
    >
      <a-select
        ref="select"
        v-model:value="searchType"
        style="width: 75px; margin-right: 12px; font-size: 12px"
      >
        <a-select-option value="1">编号</a-select-option>
        <a-select-option value="2">分数</a-select-option>
      </a-select>
      <a-input
        v-model:value="secretNumberInput"
        style="font-size: 13px"
        class="search-value"
        placeholder="查找试卷"
        allowClear
        @keyup.enter="searchHistoryTask"
        @keypress.stop=""
        @keydown.stop=""
      >
      </a-input>
      <a-button
        type="primary"
        style="margin-left: 8px"
        @click="searchHistoryTask"
        >搜索</a-button
      >
    </div>
    <div class="mark-history-table-head">
      <div class="head-item">编号</div>
      <div class="head-item head-item-time">时间</div>
      <div class="head-item">分数</div>
    </div>
    <div class="mark-history-table-body">
      <a-spin :spinning="loading" size="large" tip="Loading..." :delay="500">
        <div
          v-for="(task, index) of markStore.historyTasks"
          :key="index"
          :class="[
            'body-row',
            {
              'is-active': markStore.currentTask?.studentId === task.studentId,
            },
          ]"
          @click="replaceCurrentTask(task)"
        >
          <div class="body-col">
            {{ task.secretNumber }}
          </div>
          <div class="body-col">
            {{ $filters.datetimeFilter(task.markerTime ?? task.inspectTime) }}
          </div>
          <div class="body-col">
            {{ task.markerScore === -1 ? "未选做" : task.markerScore }}
          </div>
        </div>
      </a-spin>
    </div>
    <div class="mark-history-table-page">
      <div>共{{ total }}项数据</div>
      <a-pagination
        :current="currentPage"
        simple
        :total="total"
        :pageSize="limitPageSize"
        @change="pageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import type {
  GetHistory,
  HistoryQueryParams,
  MarkHistoryOrderBy,
  MarkHistorySortField,
  Task,
} from "@/types";
import { watch } from "vue";
import { message } from "ant-design-vue";
import { cloneDeep } from "lodash-es";
import { useMarkStore } from "@/store";
import EventBus from "@/plugins/eventBus";
import useDraw from "./composables/useDraw";

const limitPageSize = 20;
const markStore = useMarkStore();
const { preDrawImageHistory } = useDraw();

const {
  title = "回评",
  showSearch = false,
  orderTimeField = "marker_time",
  subjectCode = undefined,
  groupNumber = undefined,
  markerId = undefined,
  markerScore = undefined,
  examId = undefined,
  getHistory,
} = defineProps<{
  title?: string;
  showSearch?: boolean;
  orderTimeField?: "marker_time" | "inspect_time";
  subjectCode?: string;
  groupNumber?: string;
  markerId?: string;
  markerScore?: string;
  examId?: string;
  getHistory: GetHistory;
}>();

let searchType = $ref("1");

// 密号输入
let secretNumberInput = $ref("");
const format = (val: string, preVal: string) => {
  const reg = /^-?\d*(\.\d*)?$/;

  if ((!isNaN(+val) && reg.test(val)) || val === "" || val === "-") {
    secretNumberInput = val;
  } else {
    secretNumberInput = preVal;
  }
};
watch(
  () => secretNumberInput,
  (val, preVal) => {
    format(val, preVal);
  }
);

let loading = $ref(false);
let currentPage = $ref(1);
let total = $ref(0);
let order: MarkHistoryOrderBy = $ref("marker_time");
if (orderTimeField) {
  order = orderTimeField;
}
let sort: MarkHistorySortField = $ref("DESC");

const currentTaskChange = async () => {
  if (markStore.historyOpen) {
    markStore.globalMask = true;
    try {
      await updateHistoryTask({
        secretNumber: secretNumberInput,
        order: order,
        sort: sort,
        pageNumber: currentPage,
      });
    } catch (e) {
      // 恢复以前的行为，取回评失败则评卷任务为空
      await replaceCurrentTask(undefined);
    } finally {
      markStore.globalMask = false;
    }
    await replaceCurrentTask(markStore.historyTasks[0]);
  } else {
    await replaceCurrentTask(markStore.tasks[0]);
    markStore.historyTasks.splice(0);
    secretNumberInput = "";
    currentPage = 1;
    order = "marker_time";
    sort = "DESC";
  }
};
watch(() => markStore.historyOpen, currentTaskChange);
watch([$$(order), $$(sort), $$(currentPage)], currentTaskChange);

EventBus.on("should-reload-history", () => {
  (async () => {
    markStore.globalMask = true;
    try {
      const res = await getHistory({
        secretNumber: markStore.currentTask?.secretNumber,
        order,
        sort,
        pageNumber: 1,
        subjectCode,
        groupNumber,
        markerId,
        markerScore,
        examId,
        pageSize: 10,
      });
      if (res?.data) {
        const data = res.data.records;
        if (markStore.currentTask) {
          // 这种方式(对象被重新构造了)能查找到index，我也很惊讶
          const indexOfTasks = markStore.historyTasks.indexOf(
            markStore.currentTask
          );
          if (data[0]) {
            // 如果原任务依然存在
            markStore.historyTasks.splice(indexOfTasks, 1, data[0]);
            await replaceCurrentTask(markStore.historyTasks[indexOfTasks]);
          } else {
            // 问题卷会查找不到，这里直接删除此任务
            markStore.historyTasks.splice(indexOfTasks, 1);
            await replaceCurrentTask(markStore.historyTasks[indexOfTasks]);
          }
        } else {
          // 问题卷会将清除它作为 currentTask ，然后刷新当前页
          markStore.historyTasks = data;
          await replaceCurrentTask(markStore.historyTasks[0]);
        }
      }
    } finally {
      markStore.globalMask = false;
    }
  })().catch((e) => console.log("reload-history error", e));
});

async function updateHistoryTask({
  pageNumber = 1,
  order = "marker_time",
  sort = "DESC",
  secretNumber = null,
}: HistoryQueryParams) {
  loading = true;
  let params = {
    pageNumber,
    pageSize: limitPageSize,
    order,
    sort,
    subjectCode,
    groupNumber,
    markerId,
    markerScore,
    examId,
  };
  let key = searchType == "1" ? "secretNumber" : "markerScore";
  params[key] = secretNumber || undefined;
  const res = await getHistory(params);
  loading = false;
  if (res?.data) {
    markStore.historyTasks = res.data.records;
    total = res.data.total;
    replaceCurrentTask(markStore.historyTasks[0]).catch((err) => {
      console.log(err);
      void message.error("切换至回评任务失败");
    });
  }
}

async function replaceCurrentTask(task: Task | undefined) {
  if (markStore.isScanImage && !!task) {
    await preDrawImageHistory(task);
  }
  markStore.currentTask = cloneDeep(task);
}

function pageChange(page) {
  currentPage = page;
}

async function searchHistoryTask() {
  if (currentPage !== 1) {
    currentPage = 1;
  } else {
    await currentTaskChange();
  }
}
</script>
