<template>
  <div :class="['mark-history', { hide: !store.historyOpen }]">
    <div class="mark-history-title">
      {{ title }}
    </div>
    <div
      v-if="showSearch && store.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 store.historyTasks"
          :key="index"
          :class="['body-row', { 'is-active': store.currentTask === task }]"
          @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" @keypress.stop="" @keydown.stop="">
      <div>共{{ total }}项数据</div>
      <a-pagination
        v-model: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 { store } from "@/store/store";
import EventBus from "@/plugins/eventBus";
import { preDrawImageHistory } from "@/utils/utils";
import { message } from "ant-design-vue";

const limitPageSize = 20;

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

EventBus.on("should-reload-history", () => {
  // await updateHistoryTask({
  //   secretNumber: secretNumberInput,
  //   order: order,
  //   sort: sort,
  //   pageNumber: currentPage,
  // });
  // // 提交后，渲染第一条
  // replaceCurrentTask(store.historyTasks[0]);
  // TODO: 因为 mitt 不支持 å https://github.com/developit/mitt/issues/122
  (async () => {
    store.globalMask = true;
    try {
      const res = await getHistory({
        secretNumber: store.currentTask?.secretNumber,
        order,
        sort,
        pageNumber: currentPage,
        subjectCode,
        groupNumber,
        markerId,
        markerScore,
        examId,
        pageSize: limitPageSize,
      });
      if (res?.data) {
        const data = res.data.records;
        total = res.data.total;
        if (store.currentTask) {
          // 这种方式(对象被重新构造了)能查找到index，我也很惊讶
          const indexOfTasks = store.historyTasks.indexOf(store.currentTask);
          if (data[0]) {
            // 如果原任务依然存在
            store.historyTasks.splice(indexOfTasks, 1, data[0]);
            await replaceCurrentTask(store.historyTasks[indexOfTasks]);
          } else {
            // 问题卷会查找不到，这里直接删除此任务
            store.historyTasks.splice(indexOfTasks, 1);
            await replaceCurrentTask(store.historyTasks[indexOfTasks]);
          }
        } else {
          // 问题卷会将清除它作为 currentTask ，然后刷新当前页
          store.historyTasks = data;
          await replaceCurrentTask(store.historyTasks[0]);
        }
      }
    } finally {
      store.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) {
    store.historyTasks = res.data.records;
    total = res.data.total;
    replaceCurrentTask(store.historyTasks[0]).catch((err) => {
      console.log(err);
      void message.error("切换至回评任务失败");
    });
  }
}

async function replaceCurrentTask(task: Task | undefined) {
  // console.log("replaceCurrentTask:", task);

  if (store.isScanImage && !!task) {
    await preDrawImageHistory(task);
  }
  store.currentTask = task;
}

function pageChange(page) {
  currentPage = page;
}

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