<template>
  <div
    class="history-container tw-px-1"
    :class="[store.historyOpen ? 'show' : 'hide']"
  >
    <div class="tw-mt-1 tw-mb-1 tw-flex tw-place-items-center">
      <div class="tw-text-lg main-text-color tw-mr-3 tw-font-bold">
        {{ title }}
      </div>
      <input
        v-if="showSearch"
        v-model="secretNumberInput"
        type="text"
        placeholder="查找试卷"
        class="tw-flex-1 tw-rounded tw-h-8 tw-pl-1 tw-pr-8"
        @keydown.stop
        @keypress.stop
        @keyup.enter="searchHistoryTask"
      />
      <SearchOutlined
        v-if="showSearch"
        style="margin-left: -24px; font-size: 18px; padding: 3px"
        @click="searchHistoryTask"
      />
    </div>
    <div class="tw-flex tw-justify-between tw-mt-5">
      <div class="tw-cursor-pointer tw-flex">编号</div>
      <div
        class="tw-cursor-pointer tw-flex tw-items-center"
        @click="toggleOrderBy(orderTimeField)"
      >
        时间
        <CaretUpOutlined
          v-if="showOrder && order === orderTimeField && sort === 'ASC'"
        />
        <CaretDownOutlined
          v-if="showOrder && order === orderTimeField && sort === 'DESC'"
        />
      </div>
      <div
        class="tw-cursor-pointer tw-flex tw-items-center"
        @click="toggleOrderBy('markerScore')"
      >
        分数
        <CaretUpOutlined
          v-if="showOrder && order === 'markerScore' && sort === 'ASC'"
        />
        <CaretDownOutlined
          v-if="showOrder && order === 'markerScore' && sort === 'DESC'"
        />
      </div>
    </div>
    <a-spin :spinning="loading" size="large" tip="Loading..." :delay="500">
      <div style="margin-bottom: -40px; padding-bottom: 40px">
        <div v-for="(task, index) of store.historyTasks" :key="index">
          <div
            class="tw-flex tw-justify-between tw-place-items-center tw-rounded tw-cursor-pointer tw-font-bold tw-py-2"
            :class="store.currentTask === task && 'current-task'"
            @click="replaceCurrentTask(task)"
          >
            <div class="tw-break-words" style="width: 62px">
              {{ task.secretNumber }}
            </div>
            <div>
              {{ $filters.datetimeFilter(task.markerTime ?? task.inspectTime) }}
            </div>
            <div style="width: 30px; text-align: right">
              {{ task.markerScore === -1 ? "未选做" : task.markerScore }}
            </div>
          </div>
        </div>
      </div>
    </a-spin>
    <div
      class="tw-flex tw-justify-between tw-place-content-center tw-mt-2 pager-container"
    >
      <div class="tw-font-bold" style="line-height: 30px">
        第{{ currentPage }}页
      </div>
      <div class="tw-flex tw-gap-2">
        <a-button
          shape="circle"
          type="primary"
          title="上一页"
          @click="previousPage"
        >
          <div class="left-triangle"></div>
        </a-button>
        <a-button
          shape="circle"
          type="primary"
          title="下一页"
          @click="nextPage"
        >
          <div class="right-triangle"></div>
        </a-button>
      </div>
    </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 {
  SearchOutlined,
  CaretDownOutlined,
  CaretUpOutlined,
} from "@ant-design/icons-vue";
import { cloneDeep } from "lodash-es";
import EventBus from "@/plugins/eventBus";
import { addFileServerPrefixToTask } from "@/utils/utils";

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

let secretNumberInput = $ref("");
let loading = $ref(false);
let currentPage = $ref(1);
let order: MarkHistoryOrderBy = $ref("markerTime");
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) {
      // 恢复以前的行为，取回评失败则评卷任务为空
      replaceCurrentTask(undefined);
    } finally {
      store.globalMask = false;
    }
    replaceCurrentTask(store.historyTasks[0]);
  } else {
    replaceCurrentTask(store.tasks[0]);
    store.historyTasks.splice(0);
    secretNumberInput = "";
    currentPage = 1;
    order = "markerTime";
    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 不支持 async，这里是个workaround。 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,
      });
      if (res?.data) {
        let data = cloneDeep(res.data);
        data = data.map(addFileServerPrefixToTask);
        if (store.currentTask) {
          // 这种方式(对象被重新构造了)能查找到index，我也很惊讶
          const indexOfTasks = store.historyTasks.indexOf(store.currentTask);
          if (data[0]) {
            // 如果原任务依然存在
            store.historyTasks.splice(indexOfTasks, 1, data[0]);
            replaceCurrentTask(store.historyTasks[indexOfTasks]);
          } else {
            // 问题卷会查找不到，这里直接删除此任务
            store.historyTasks.splice(indexOfTasks, 1);
            replaceCurrentTask(store.historyTasks[indexOfTasks]);
          }
        } else {
          // 问题卷会将清除它作为 currentTask ，然后刷新当前页
          store.historyTasks = data;
          replaceCurrentTask(store.historyTasks[0]);
        }
      }
    } finally {
      store.globalMask = false;
    }
  })().catch((e) => console.log("reload-history error", e));
});

async function updateHistoryTask({
  pageNumber = 1,
  pageSize = 20,
  order = "markerTime",
  sort = "DESC",
  secretNumber = null,
}: HistoryQueryParams) {
  loading = true;
  const res = await getHistory({
    pageNumber,
    pageSize,
    order,
    sort,
    secretNumber,
    subjectCode,
    groupNumber,
    markerId,
    markerScore,
  });
  loading = false;
  if (res?.data) {
    let data = cloneDeep(res.data) ;
    data = data.map(addFileServerPrefixToTask);
    store.historyTasks = data;
    replaceCurrentTask(store.historyTasks[0]);
  }
}

function replaceCurrentTask(task: Task | undefined) {
  store.currentTask = task;
}

function previousPage() {
  if (currentPage > 1) {
    currentPage -= 1;
  }
}
function nextPage() {
  if (store.historyTasks.length >= 20) {
    currentPage += 1;
  }
}

function toggleOrderBy(toOrder: MarkHistoryOrderBy) {
  if (showOrder) {
    if (toOrder === order) {
      sort = sort === "DESC" ? "ASC" : "DESC";
    } else {
      order = toOrder;
    }
  }
}

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

<style scoped>
.history-container {
  min-width: 290px;
  padding: 20px;
  font-size: var(--app-secondary-font-size);
  overflow-y: auto;
  height: calc(100vh - 56px);
  transition: margin-left 0.5s;
}
.history-container.show {
  margin-left: 0;
}
.history-container.hide {
  margin-left: -290px;
}

.current-task {
  background-color: var(--app-score-color);
  color: white;
  padding-left: 5px;
  margin-left: -5px;
  padding-right: 5px;
  margin-right: -5px;
}

.left-triangle {
  width: 12px;
  height: 12px;
  background-color: white;
  clip-path: polygon(0 50%, 100% 0, 100% 100%);
  transform: translateX(60%);
}

.right-triangle {
  width: 12px;
  height: 12px;
  background-color: white;
  clip-path: polygon(100% 50%, 0 100%, 0 0);
  transform: translateX(90%);
}
.pager-container {
  position: absolute;
  bottom: 0px;
  padding-bottom: 20px;
  width: 250px;
  background-color: var(--app-main-bg-color);
}
</style>
