<template>
  <div
    class="
      tw-flex tw-gap-2 tw-justify-between tw-items-center
      header-container
      tw-px-1
    "
    v-if="store.setting && store.setting.subject.name"
  >
    <div style="max-width: 10%">
      <a
        class="
          tw-text-white
          tw-underline
          tw-block
          tw-overflow-ellipsis
          tw-overflow-hidden
          tw-whitespace-nowrap
        "
        :title="store.setting.subject.name"
        href="/mark/subject-select"
        >{{
          `${store.setting.subject.code ?? ""}-${
            store.setting.subject.name ?? ""
          }`
        }}</a
      >
    </div>
    <div v-if="store.setting.statusValue === 'TRIAL'">试评</div>
    <div class="tw-flex tw-gap-1">
      <div>
        编号<span class="highlight-text">{{
          store.currentTask?.secretNumber
        }}</span>
      </div>
      <div
        v-if="store.currentTask && store.currentTask.objectiveScore !== null"
      >
        客观分<span class="highlight-text">{{
          store.currentTask.objectiveScore
        }}</span>
      </div>
    </div>
    <ul v-show="store.status.totalCount" class="tw-flex tw-gap-2 tw-mb-0">
      <li>
        已评<span class="highlight-text">{{
          store.status.personCount ?? "-"
        }}</span>
      </li>
      <li v-if="store.setting.topCount">
        分配<span class="highlight-text">{{
          store.setting.topCount ?? "-"
        }}</span>
      </li>
      <li>
        未评<span class="highlight-text">{{
          store.status.totalCount - store.status.markedCount ?? "-"
        }}</span>
      </li>
      <li
        :title="`问题卷${store.status.problemCount}\n待仲裁${store.status.arbitrateCount}`"
      >
        <QuestionCircleOutlined class="icon-font icon-font-size-20" />
      </li>
      <li>
        进度<span class="highlight-text">{{ progress ?? "-" }}%</span>
      </li>
    </ul>
    <ul class="tw-flex tw-gap-2 tw-mb-0">
      <li @click="upScale" title="放大">
        <ZoomInOutlined
          class="icon-font icon-font-size-20 tw-cursor-pointer"
          :style="{
            color: greaterThanOneScale ? 'red' : 'white',
          }"
        />
      </li>
      <li @click="downScale" title="缩小">
        <ZoomOutOutlined
          class="icon-font icon-font-size-20 tw-cursor-pointer"
          :style="{
            color: lessThanOneScale ? 'red' : 'white',
          }"
        />
      </li>
      <li @click="normalScale" title="适应">
        <FullscreenOutlined
          class="icon-font icon-font-size-20 tw-cursor-pointer"
        />
      </li>
    </ul>
    <div>
      <a-dropdown class="header-bg-color">
        <template #overlay v-if="!store.setting.forceMode">
          <a-menu>
            <a-menu-item
              key="1"
              @click="toggleSettingMode"
              style="font-size: 16px"
            >
              {{ exchangeModeName }}
            </a-menu-item>
          </a-menu>
        </template>
        <a-button
          style="font-size: 16px; color: white !important; border: none"
        >
          {{ modeName }}
          <DownOutlined
            v-if="!store.setting.forceMode"
            style="display: inline-flex"
          />
        </a-button>
      </a-dropdown>
    </div>
    <div @click="toggleHistory" title="回看">
      <SnippetsOutlined
        class="icon-font icon-font-size-20 tw-cursor-pointer"
        :style="{
          color: store.historyOpen ? 'red' : 'white',
        }"
      />
    </div>
    <div
      class="tw-flex tw-place-items-center"
      :title="
        '评卷时间段：' +
        (store.setting.startTime > 0
          ? $filters.datetimeFilter(store.setting.startTime)
          : '-') +
        ' ~ ' +
        (store.setting.endTime > 0
          ? $filters.datetimeFilter(store.setting.endTime)
          : '-')
      "
    >
      <ClockCircleOutlined class="icon-font icon-font-size-20" />
    </div>
    <a-popover title="小助手" trigger="hover" class="tw-cursor-pointer">
      <template #content>
        <table class="assistant-table">
          <tr v-if="store.setting.subject.paperUrl">
            <td>试卷</td>
            <td>
              <a-switch
                v-model:checked="store.setting.uiSetting['paper.modal']"
              />
            </td>
          </tr>
          <tr v-if="store.setting.subject.answerUrl">
            <td>答案</td>
            <td>
              <a-switch
                v-model:checked="store.setting.uiSetting['answer.modal']"
              />
            </td>
          </tr>
          <tr>
            <td>全卷</td>
            <td><a-switch v-model:checked="store.allPaperModal" /></td>
          </tr>
          <tr v-if="store.setting.sheetView">
            <td>原图</td>
            <td>
              <a-switch v-model:checked="store.sheetViewModal" />
            </td>
          </tr>
          <tr>
            <td>缩略图</td>
            <td>
              <a-switch
                v-model:checked="store.setting.uiSetting['minimap.modal']"
              />
            </td>
          </tr>
          <tr>
            <td>特殊标记</td>
            <td>
              <a-switch
                v-model:checked="store.setting.uiSetting['specialTag.modal']"
              />
            </td>
          </tr>
          <tr v-if="store.setting.statusValue !== 'TRIAL'">
            <td>问题卷</td>
            <td><a-button @click="openProblemModal">选择问题类型</a-button></td>
          </tr>
        </table>
      </template>
      <div class="tw-flex">
        小助手
        <DownOutlined
          style="font-size: 12px; display: inline-block"
          class="tw-self-center tw-ml-1"
        />
      </div>
    </a-popover>
    <div
      @click="openSwitchGroupModal"
      class="tw-flex tw-place-content-center tw-cursor-pointer"
      style="max-width: 8%"
      :title="store.setting.groupTitle + '-' + store.setting.groupNumber"
    >
      <div
        class="
          tw-overflow-ellipsis tw-overflow-hidden tw-whitespace-nowrap tw-mr-1
        "
      >
        {{ "分组:" + store.setting.groupNumber }}
      </div>
      <DownOutlined
        v-if="store.groups.length > 1"
        style="font-size: 12px; display: inline-block"
        class="tw-self-center"
      />
    </div>
    <div
      class="tw-flex tw-place-items-center tw-cursor-pointer"
      @click="openProfileModal"
    >
      <UserOutlined class="icon-font icon-with-text" />{{
        store.setting.userName
      }}
    </div>
    <div
      class="tw-flex tw-place-items-center tw-cursor-pointer"
      @click="logout"
    >
      <PoweroffOutlined class="icon-font icon-with-text" />
      退出
    </div>
  </div>
  <MarkChangeProfile ref="changeProfileRef" />
  <MarkSwitchGroupDialog ref="switchGroupRef" />
  <MarkProblemDialog
    @should-reload-history="$emit('should-reload-history')"
    ref="problemRef"
  />
</template>

<script lang="ts">
import { doLogout, getHistoryTask } from "@/api/markPage";
import { computed, defineComponent, ref, watchEffect } from "vue";
import { store } from "./store";
import {
  ZoomInOutlined,
  ZoomOutOutlined,
  FullscreenOutlined,
  SnippetsOutlined,
  UserOutlined,
  PoweroffOutlined,
  ClockCircleOutlined,
  QuestionCircleOutlined,
  DownOutlined,
} from "@ant-design/icons-vue";
import { ModeEnum } from "@/types";
import MarkChangeProfile from "./MarkChangeProfile.vue";
import MarkSwitchGroupDialog from "./MarkSwitchGroupDialog.vue";
import MarkProblemDialog from "./MarkProblemDialog.vue";
import { isNumber } from "lodash";
import { Modal } from "ant-design-vue";

export default defineComponent({
  name: "MarkHeader",
  components: {
    ZoomInOutlined,
    ZoomOutOutlined,
    FullscreenOutlined,
    SnippetsOutlined,
    UserOutlined,
    DownOutlined,
    PoweroffOutlined,
    ClockCircleOutlined,
    QuestionCircleOutlined,
    MarkChangeProfile,
    MarkSwitchGroupDialog,
    MarkProblemDialog,
  },
  emits: ["should-reload-history"],
  setup() {
    const modeName = computed(() =>
      store.setting.mode === ModeEnum.TRACK ? "轨迹模式" : "普通模式"
    );
    const exchangeModeName = computed(() =>
      store.setting.mode === ModeEnum.TRACK ? "普通模式" : "轨迹模式"
    );
    async function toggleSettingMode() {
      if (store.setting.mode === ModeEnum.TRACK) {
        store.setting.mode = ModeEnum.COMMON;
      } else {
        store.setting.mode = ModeEnum.TRACK;
      }
      // if (store.currentMarkResult) {
      //   store.currentMarkResult.scoreList = [];
      //   store.currentMarkResult.trackList = [];
      // }
      // if (store.currentTask) {
      //   store.currentTask.questionList.forEach((q) => (q.score = null));
      // }
      // store.currentQuestion = undefined;
      // store.currentScore = undefined;

      const body = document.querySelector("body");
      if (body) body.innerHTML = "重新加载中...";
      // 等待一秒后，重新加载页面
      await new Promise((resolve) => setTimeout(resolve, 1000));
      window.location.reload();
    }
    const progress = computed(() => {
      const { totalCount, markedCount } = store.status;
      if (totalCount <= 0) return 0;
      let p = markedCount / totalCount;
      if (p < 0.01 && markedCount >= 1) p = 0.01;
      p = Math.floor(p * 100);
      return p;
    });

    const upScale = () => {
      const s = store.setting.uiSetting["answer.paper.scale"];
      if (s < 3)
        store.setting.uiSetting["answer.paper.scale"] = +(s + 0.2).toFixed(1);
    };
    const downScale = () => {
      const s = store.setting.uiSetting["answer.paper.scale"];
      if (s > 0.2)
        store.setting.uiSetting["answer.paper.scale"] = +(s - 0.2).toFixed(1);
    };
    const normalScale = () => {
      store.setting.uiSetting["answer.paper.scale"] = 1;
    };
    const toggleHistory = () => {
      store.historyOpen = !store.historyOpen;
    };
    const greaterThanOneScale = computed(() => {
      return store.setting.uiSetting["answer.paper.scale"] > 1;
    });
    const lessThanOneScale = computed(() => {
      return store.setting.uiSetting["answer.paper.scale"] < 1;
    });

    async function updateHistoryTask({
      pageNumber = 1,
      pageSize = 10,
      order = "markerTime",
      sort = "DESC",
      secretNumber = null,
    }: {
      pageNumber: number; // 从1开始
      pageSize: number;
      order: "markerTime" | "markerScore";
      sort: "ASC" | "DESC";
      secretNumber: string | null;
    }) {
      const res = await getHistoryTask({
        pageNumber,
        pageSize,
        order,
        sort,
        secretNumber,
      });
      if (res.data) {
        store.historyTasks.push(res.data);
      }
    }

    const logout = () => {
      doLogout();
    };

    const changeProfileRef = ref(null);

    const openProfileModal = () => {
      // @ts-ignore
      changeProfileRef.value?.showModal();
    };

    const switchGroupRef = ref(null);

    const openSwitchGroupModal = () => {
      // @ts-ignore
      switchGroupRef.value?.showModal();
    };

    const problemRef = ref(null);

    const openProblemModal = () => {
      // @ts-ignore
      problemRef.value?.showModal();
    };

    watchEffect(() => {
      if (
        isNumber(store.setting.topCount) &&
        store.setting.topCount > 0 &&
        store.setting.topCount === store.status.personCount
      ) {
        Modal.confirm({
          centered: true,
          mask: true,
          zIndex: 6000,
          maskStyle: { opacity: 0.97 },
          content: `分配任务份已完成，是否继续？`,
          okText: "继续",
          cancelText: "退出",
          onCancel: () => {
            logout();
          },
          onOk: () => {},
        });
      }
    });

    return {
      store,
      modeName,
      exchangeModeName,
      toggleSettingMode,
      progress,
      upScale,
      downScale,
      normalScale,
      greaterThanOneScale,
      lessThanOneScale,
      updateHistoryTask,
      toggleHistory,
      logout,
      changeProfileRef,
      openProfileModal,
      switchGroupRef,
      openSwitchGroupModal,
      problemRef,
      openProblemModal,
    };
  },
});
</script>

<style scoped>
.header-bg-color {
  background-color: #5d6d7d;
}
.header-container {
  position: relative;
  font-size: 16px;
  height: 40px;

  background-color: #5d6d7d;
  color: white;
}
.highlight-text {
  color: #ffe400;
}
.icon-font {
  display: block;
}
.icon-font-size-20 {
  font-size: 20px;
}
.line-height-20 {
  line-height: 20px;
}
.icon-with-text {
  font-size: 18px;
  line-height: 18px;
}
.header-bg-color.ant-btn:hover {
  background-color: #5d6d7d !important;
}
.assistant-table {
  border-collapse: separate;
  border-spacing: 0 0.5em;
}
</style>
