<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-4 tw-font-bold">回评</div>
      <input
        v-model="secretNumberInput"
        @keydown.stop="() => {}"
        @keypress.stop="() => {}"
        type="text"
        placeholder="查找试卷"
        class="tw-flex-1 tw-rounded tw-h-8 tw-pl-1 tw-pr-8"
        @keyup.enter="searchHistoryTask"
      />
      <SearchOutlined
        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
        @click="toggleOrderBy('markerTime')"
        class="tw-cursor-pointer tw-flex"
      >
        时间
        <CaretUpOutlined
          style="font-size: 16px"
          v-if="order === 'markerTime' && sort === 'ASC'"
        />
        <CaretDownOutlined
          style="font-size: 16px"
          v-if="order === 'markerTime' && sort === 'DESC'"
        />
      </div>
      <div
        @click="toggleOrderBy('markerScore')"
        class="tw-cursor-pointer tw-flex"
      >
        分数
        <CaretUpOutlined
          style="font-size: 16px"
          v-if="order === 'markerScore' && sort === 'ASC'"
        />
        <CaretDownOutlined
          style="font-size: 16px"
          v-if="order === 'markerScore' && sort === 'DESC'"
        />
      </div>
    </div>
    <a-spin :spinning="loading" size="large" tip="Loading..." delay="0.5">
      <div style="margin-bottom: -40px; padding-bottom: 40px">
        <div v-for="(task, index) of store.historyTasks" :key="index">
          <div
            @click="replaceCurrentTask(task)"
            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'"
          >
            <div class="tw-break-words tw-w-1/3">{{ task.secretNumber }}</div>
            <div>
              {{ $filters.datetimeFilter(task.markTime) }}
            </div>
            <div style="width: 30px; text-align: right">
              {{ 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"
          @click="previousPage"
          type="primary"
          title="上一页"
        >
          <div class="left-triangle"></div>
        </a-button>
        <a-button
          shape="circle"
          @click="nextPage"
          type="primary"
          title="下一页"
        >
          <div class="right-triangle"></div>
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getHistoryTask } from "@/api/markPage";
import type { MarkHistoryOrderBy, MarkHistorySortField, Task } from "@/types";
import { ref, watch } from "vue";
import { store } from "./store";
import {
  CloseOutlined,
  SearchOutlined,
  CaretDownOutlined,
  CaretUpOutlined,
} from "@ant-design/icons-vue";
import { cloneDeep } from "lodash";

const props = defineProps<{ shouldReload: number }>();

const secretNumberInput = ref("");
const loading = ref(false);
const currentPage = ref(1);
const order = ref("markerTime" as MarkHistoryOrderBy);
const sort = ref("DESC" as MarkHistorySortField);

const currentTaskChange = async () => {
  if (store.historyOpen) {
    replaceCurrentTask(undefined);
    await updateHistoryTask({
      secretNumber: secretNumberInput.value,
      order: order.value,
      sort: sort.value,
      pageNumber: currentPage.value,
    });
    replaceCurrentTask(store.historyTasks[0]);
  } else {
    replaceCurrentTask(store.tasks[0]);
    store.historyTasks.splice(0);
    secretNumberInput.value = "";
    currentPage.value = 1;
    order.value = "markerTime";
    sort.value = "DESC";
  }
};
watch(() => store.historyOpen, currentTaskChange);
watch([order, sort, currentPage], currentTaskChange);

watch(
  () => props.shouldReload,
  async () => {
    // await updateHistoryTask({
    //   secretNumber: secretNumberInput.value,
    //   order: order.value,
    //   sort: sort.value,
    //   pageNumber: currentPage.value,
    // });
    // // 提交后，渲染第一条
    // replaceCurrentTask(store.historyTasks[0]);
    store.globalMask = true;
    try {
      const res = await getHistoryTask({
        secretNumber: store.currentTask?.secretNumber,
      });
      if (res.data) {
        let data = cloneDeep(res.data) as Array<Task>;
        data = data.map((t) => {
          t.questionList.map((q) => {
            q.__origScore = q.score;
            return q;
          });
          t.sliceUrls = t.sliceUrls?.map((s) => store.setting.fileServer + s);
          t.sheetUrls = t.sheetUrls?.map((s) => store.setting.fileServer + s);
          t.jsonUrl = store.setting.fileServer + t.jsonUrl;

          return t;
        });
        if (store.currentTask) {
          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]);
          }
        }
      }
    } finally {
      store.globalMask = false;
    }
  }
);

async function updateHistoryTask({
  pageNumber = 1,
  pageSize = 20,
  order = "markerTime",
  sort = "DESC",
  secretNumber = null,
}: {
  pageNumber?: number; // 从1开始
  pageSize?: number;
  order?: MarkHistoryOrderBy;
  sort?: MarkHistorySortField;
  secretNumber?: string | null;
}) {
  loading.value = true;
  const res = await getHistoryTask({
    pageNumber,
    pageSize,
    order,
    sort,
    secretNumber,
  });
  loading.value = false;
  if (res.data) {
    let data = cloneDeep(res.data) as Array<Task>;
    data = data.map((t) => {
      t.questionList.map((q) => {
        q.__origScore = q.score;
        return q;
      });
      t.sliceUrls = t.sliceUrls?.map((s) => store.setting.fileServer + s);
      t.sheetUrls = t.sheetUrls?.map((s) => store.setting.fileServer + s);
      t.jsonUrl = store.setting.fileServer + t.jsonUrl;

      return t;
    });
    store.historyTasks = data;
    replaceCurrentTask(store.historyTasks[0]);
  }
}

function replaceCurrentTask(task: Task | undefined) {
  if (task) {
    task.questionList = task.questionList.map((q) => {
      if (typeof q.__origScore !== "undefined") {
        // 如果是回评的任务，则将旧分数还原
        q.score = q.__origScore;
      }
      return q;
    });
  }
  store.currentTask = task;
}

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

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

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

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

.current-task {
  background-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%);
  translate: 60%;
}

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