<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>
      <div
        v-if="showSearch && store.getStatusValueName !== '试评'"
        class="tw-flex-1 tw-flex"
      >
        <a-select
          ref="select"
          v-model:value="searchType"
          style="width: 75px; margin-right: 4px; font-size: 12px"
          @change="searchTypeChange"
        >
          <a-select-option value="1">编号</a-select-option>
          <a-select-option value="2">分数</a-select-option>
        </a-select>
        <a-input-search
          v-model:value="secretNumberInput"
          style="font-size: 13px"
          class="tw-flex-1 search-value"
          placeholder="查找试卷"
          allowClear
          @keyup.enter="searchHistoryTask"
          @keypress.stop=""
          @keydown.stop=""
          @search="searchHistoryTask"
        >
          <!-- <template #suffix>
            <SearchOutlined style="color: rgba(0, 0, 0, 0.45)" />
          </template> -->
        </a-input-search>
      </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: 72px">
        <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
      v-if="!hasLimit"
      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, computed } 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, preDrawImageHistory } from "@/utils/utils";
import { message } from "ant-design-vue";
const remarkCount = computed(() => {
  return store.setting?.remarkCount;
});
const limitPageSize = computed(() => {
  return typeof remarkCount.value == "number" ? remarkCount.value : 20;
});
const hasLimit = computed(() => {
  console.log("remarkCount.value:", remarkCount.value);
  return typeof remarkCount.value == "number";
});
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 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);
  }
);
const searchTypeChange = (val) => {
  console.log(val);
};
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) {
      // 恢复以前的行为，取回评失败则评卷任务为空
      await replaceCurrentTask(undefined);
    } finally {
      // store.globalMask = false;
      if (store.setting?.examType !== "SCAN_IMAGE") {
        store.globalMask = false;
      }
    }
    await replaceCurrentTask(store.historyTasks[0]);
  } else {
    await 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,
        pageSize: limitPageSize.value,
      });
      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;
  let params = {
    pageNumber,
    pageSize: limitPageSize.value,
    order,
    sort,
    subjectCode,
    groupNumber,
    markerId,
    markerScore,
  };
  let key = searchType == "1" ? "secretNumber" : "markerScore";
  params[key] = secretNumber;
  // const res = await getHistory({
  //   pageNumber,
  //   pageSize,
  //   order,
  //   sort,
  //   secretNumber,
  //   subjectCode,
  //   groupNumber,
  //   markerId,
  //   markerScore,
  // });
  const res = await getHistory(params);
  loading = false;
  if (res?.data) {
    let data = cloneDeep(res.data);
    data = data.map(addFileServerPrefixToTask);
    store.historyTasks = data;
    replaceCurrentTask(store.historyTasks[0]).catch((err) => {
      console.log(err);
      void message.error("切换至回评任务失败");
    });
  }
  if (!res?.data || !res?.data.length) {
    store.globalMask = false;
  }
}

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

  if (store.isScanImage && !!task) {
    await preDrawImageHistory(task);
  }
  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;
  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 .search-value :deep(.ant-input::-webkit-input-placeholder) {
  font-size: 12px;
}
.history-container :deep(.ant-input-affix-wrapper) {
  padding: 4px 6px;
}
.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>
