<template>
  <div
    :style="{ display: store.historyOpen ? 'block' : 'none' }"
    class="history-container tw-px-1"
  >
    <div class="tw-p-1 tw-flex tw-justify-between tw-place-items-center">
      <div class="tw-text-xl">回评</div>
      <a-button
        class="tw-content-end"
        shape="circle"
        @click="store.historyOpen = false"
      >
        <template #icon><CloseOutlined /></template>
      </a-button>
    </div>
    <div class="tw-mt-1 tw-mb-1 tw-flex">
      <input
        v-model="secretNumberInput"
        type="text"
        placeholder="查找试卷"
        class="
          tw-w-full
          tw-rounded
          tw-h-8
          tw-border-solid
          tw-border-gray-400
          tw-border-2
          tw-pl-1
          tw-pr-8
        "
        @keyup.enter="updateHistoryTask({ secretNumber: secretNumberInput })"
      />
      <SearchOutlined
        style="margin-left: -30px; font-size: 24px; padding: 3px"
        @click="updateHistoryTask({ secretNumber: secretNumberInput })"
      />
    </div>
    <div class="tw-flex tw-justify-between">
      <div class="tw-cursor-pointer tw-flex">编号</div>
      <div
        @click="toggleOrderBy('markerTime')"
        class="tw-cursor-pointer tw-flex"
      >
        时间
        <CaretUpOutlined
          style="font-size: 20px"
          v-if="order === 'markerTime' && sort === 'ASC'"
        />
        <CaretDownOutlined
          style="font-size: 20px"
          v-if="order === 'markerTime' && sort === 'DESC'"
        />
      </div>
      <div
        @click="toggleOrderBy('markerScore')"
        class="tw-cursor-pointer tw-flex"
      >
        分数
        <CaretUpOutlined
          style="font-size: 20px"
          v-if="order === 'markerScore' && sort === 'ASC'"
        />
        <CaretDownOutlined
          style="font-size: 20px"
          v-if="order === 'markerScore' && sort === 'DESC'"
        />
      </div>
    </div>
    <a-spin :spinning="loading" size="large" tip="Loading...">
      <div v-for="(task, index) of store.historyTasks" :key="index">
        <div
          @click="replaceCurrentTask(task)"
          class="
            tw-flex
            tw-justify-between
            tw-h-6
            tw-place-items-center
            tw-rounded
            tw-cursor-pointer
          "
          :class="store.currentTask === task && 'current-task'"
        >
          <div>{{ task.secretNumber }}</div>
          <div>
            {{ $filters.datetimeFilter(task.markTime) }}
          </div>
          <div style="width: 30px; text-align: center">
            {{ task.markerScore }}
          </div>
        </div>
      </div>
    </a-spin>
    <div class="tw-flex tw-justify-between tw-place-content-center tw-mt-2">
      <a-button @click="previousPage">上一页</a-button>
      <div style="line-height: 30px">第{{ currentPage }}页</div>
      <a-button @click="nextPage">下一页</a-button>
    </div>
  </div>
</template>

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

export default defineComponent({
  name: "MarkHistory",
  components: {
    CloseOutlined,
    SearchOutlined,
    CaretDownOutlined,
    CaretUpOutlined,
  },
  props: {
    shouldReload: { type: Number, required: true },
  },
  setup(props) {
    const secretNumberInput = ref(null);
    const loading = ref(false);
    const currentPage = ref(1);
    const order = ref("markerTime" as MarkHistoryOrderBy);
    const sort = ref("DESC" as MarkHistorySortField);

    watchEffect(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);
      }
    });

    watch(
      () => props.shouldReload,
      async () => {
        await updateHistoryTask({
          secretNumber: secretNumberInput.value,
          order: order.value,
          sort: sort.value,
          pageNumber: currentPage.value,
        });
        // 提交后，渲染第一条
        replaceCurrentTask(store.historyTasks[0]);
      }
    );

    async function updateHistoryTask({
      pageNumber = 1,
      pageSize = 10,
      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;
        // updateHistoryTask({
        //   order: order.value,
        //   sort: sort.value,
        //   pageNumber: currentPage.value,
        // });
      }
    }
    function nextPage() {
      if (store.historyTasks.length >= 10) {
        currentPage.value += 1;
        // updateHistoryTask({
        //   // order: order.value,
        //   // sort: sort.value,
        //   pageNumber: currentPage.value,
        // });
      }
    }

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

    return {
      store,
      loading,
      secretNumberInput,
      updateHistoryTask,
      replaceCurrentTask,
      currentPage,
      previousPage,
      nextPage,
      sort,
      order,
      toggleOrderBy,
    };
  },
});
</script>

<style scoped>
.history-container {
  min-width: 250px;
  border-right: 1px solid grey;
}
.current-task {
  background-color: aqua;
}
</style>
