<template>
  <div
    v-if="store.setting && store.setting.subject.name"
    class="tw-flex tw-gap-2 tw-justify-between tw-items-center header-container"
  >
    <a-tooltip>
      <template #title>回评</template>
      <div
        class="tw-flex tw-place-content-center tw-cursor-pointer tw-relative menu"
        :class="[store.historyOpen && 'menu-toggled']"
        @click="store.toggleHistory"
      >
        <span class="tw-inline-flex tw-place-content-center">
          <img
            src="./images/left-menu.svg"
            :class="[store.historyOpen && 'svg-red']"
          />
        </span>
        <div v-if="store.historyOpen" class="triangle"></div>
      </div>
    </a-tooltip>
    <div style="max-width: 12%; margin-left: -20px">
      <a
        class="tw-text-white tw-block tw-overflow-ellipsis tw-overflow-hidden tw-whitespace-nowrap header-big-text"
        :title="store.setting.subject.name"
        href="/mark/subject-select"
        @dragstart.prevent
      >
        {{
          `${store.setting.subject.code ?? ""}-${
            store.setting.subject.name ?? ""
          }`
        }}
      </a>
    </div>
    <div class="tw-flex" style="margin: 0 -20px 0 -40px">
      <a-tooltip>
        <template #title>
          问题卷{{ store.status.problemCount }}
          <br />
          待仲裁{{ store.status.arbitrateCount }}
        </template>
        <img
          src="./images/problems.svg"
          :class="questionMarkShouldChange && 'question-mark-animation'"
          @mouseover="questionMarkShouldChange = false"
        />
      </a-tooltip>
    </div>
    <!-- <div v-if="store.setting.statusValue === 'TRIAL'">试评</div> -->
    <div class="tw-flex tw-gap-1">
      <div style="min-width: 105px">
        <span class="header-small-text">编号</span>
        <span class="highlight-text">
          {{ store.currentTask?.secretNumber ?? "-" }}
        </span>
      </div>
      <div
        v-if="
          store.currentTask &&
          store.currentTask.objectiveScore !== null &&
          !!store.setting?.showObjectiveScore
        "
      >
        <span class="header-small-text">客观分</span>
        <span class="highlight-text">
          {{ store.currentTask.objectiveScore }}
        </span>
      </div>
      <div
        v-if="
          props.showTotalScore &&
          store.currentTask &&
          store.currentTask.objectiveScore !== null
        "
        style="margin-left: 0.5em"
      >
        <span class="header-small-text">成绩</span>
        <span
          class="highlight-text"
          style="margin-left: 0.2em; margin-top: 0.1em"
        >
          {{
            parseFloat(
              (
                ((Math.max(store.currentTask.objectiveScore || 0, 0) * 100 +
                  Math.max(store.currentTask.markResult?.markerScore || 0, 0) *
                    100) |
                  0) /
                100
              ).toFixed(2)
            )
          }}
        </span>
      </div>
    </div>
    <div v-show="store.status.totalCount" class="tw-flex tw-gap-2">
      <span style="display: inline-flex; height: 16px; min-width: 55px">
        <span class="header-small-text">已评</span>
        <transition-group name="count-animation" tag="span">
          <span
            :key="store.status.personCount || 0"
            class="highlight-text"
            style="display: block"
          >
            {{ store.status.personCount }}
          </span>
        </transition-group>
      </span>
      <span v-if="store.setting.topCount">
        <span class="header-small-text">分配</span>
        <span class="highlight-text">{{ store.setting.topCount ?? "-" }}</span>
      </span>
      <span style="display: inline-flex; height: 16px; min-width: 55px">
        <span class="header-small-text">未评</span>
        <transition-group name="count-animation" tag="span">
          <span
            :key="todoCount || 0"
            class="highlight-text"
            style="display: block"
          >
            {{ todoCount }}
          </span>
        </transition-group>
      </span>
      <span style="display: inline-flex; height: 16px; min-width: 60px">
        <span class="header-small-text">进度</span>
        <transition-group name="count-animation" tag="span">
          <span
            :key="progress || '-'"
            class="highlight-text"
            style="display: block"
          >
            {{ progress }}%
          </span>
        </transition-group>
      </span>
    </div>
    <div class="tw-flex tw-place-items-center">
      <a-tooltip>
        <template #title>
          评卷时间段
          <br />
          {{
            store.setting.startTime > 0
              ? $filters.datetimeFilter(store.setting.startTime)
              : "-"
          }}
          <br />~<br />
          {{
            store.setting.endTime > 0
              ? $filters.datetimeFilter(store.setting.endTime)
              : "-"
          }}
        </template>
        <img
          src="./images/time.png"
          style="width: 16px; height: 16px"
          class="svg-red-hover"
        />
      </a-tooltip>
    </div>
    <div class="tw-flex">
      <a-dropdown class="header-bg-color">
        <template v-if="!store.setting.forceMode" #overlay>
          <a-menu>
            <a-menu-item key="1" @click="toggleSettingMode">
              {{ exchangeModeName }}
            </a-menu-item>
          </a-menu>
        </template>
        <a-button
          style="
            color: rgba(255, 255, 255, 0.5);
            border: none;
            display: flex;
            align-items: center;
          "
        >
          <img
            src="./images/trackmode.png"
            style="
              width: 11px;
              height: 12px;
              display: inline;
              margin-right: 2px;
            "
          />
          {{ modeName }}
          <div v-if="!store.setting.forceMode" class="dropdown-triangle"></div>
        </a-button>
      </a-dropdown>
    </div>
    <a-popover
      v-if="!store.isScanImage"
      title="小助手"
      trigger="hover"
      class="tw-cursor-pointer"
    >
      <template #content>
        <table class="assistant-table">
          <tr v-if="store.setting.statusValue !== 'TRIAL'">
            <td>问题卷</td>
            <td>
              <a-button @click="openProblemModal">选择问题类型</a-button>
            </td>
          </tr>
        </table>
      </template>
      <div class="tw-flex tw-items-center">
        <img
          src="./images/assistant.png"
          style="width: 10px; height: 12px; margin-right: 2px"
        />
        <span>小助手</span>
        <div class="dropdown-triangle"></div>
      </div>
    </a-popover>
    <a-popover
      v-if="store.isScanImage"
      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
                type="text"
                style="
                  color: var(--app-primary-button-bg-color);
                  margin-right: -15px;
                  height: 25px;
                "
                @click="openProblemModal"
              >
                选择问题类型
              </a-button>
            </td>
          </tr>
          <tr v-if="store.isScanImage">
            <td>分数/标记大小</td>
            <td>
              <a-slider
                v-model:value="store.setting.uiSetting['score.fontSize.scale']"
                :min="0.5"
                :step="0.1"
                :max="2"
                style="margin: 0"
              />
            </td>
          </tr>
          <tr v-if="store.isScanImage">
            <td>快捷键</td>
            <td>
              <a-switch
                v-model:checked="store.setting.uiSetting['shortCut.modal']"
              />
            </td>
          </tr>
        </table>
      </template>
      <div class="tw-flex tw-items-center assistant-text">
        <img
          src="./images/assistant.png"
          style="width: 10px; height: 12px; margin-right: 2px"
        />
        <span>小助手</span>
        <div class="dropdown-triangle"></div>
      </div>
    </a-popover>
    <div
      class="tw-flex tw-place-content-center tw-cursor-pointer tw-items-center"
      style="max-width: 8%"
      :title="store.setting.groupTitle + '-' + store.setting.groupNumber"
      @click="openSwitchGroupModal"
    >
      <img
        src="./images/group.png"
        style="width: 10px; height: 12px; margin-right: 2px"
      />
      <div class="tw-overflow-ellipsis tw-overflow-hidden tw-whitespace-nowrap">
        {{ "分组:" + store.setting.groupNumber }}
      </div>
      <div v-if="store.groups.length > 1" class="dropdown-triangle"></div>
    </div>
    <div class="tw-flex tw-gap-4">
      <div
        class="tw-flex tw-place-items-center tw-cursor-pointer"
        @click="openProfileModal"
      >
        <!-- <UserOutlined /> -->
        {{ store.setting.userName }}
      </div>
      <div
        class="tw-flex tw-place-items-center tw-cursor-pointer"
        @click="logout"
      >
        <!-- <PoweroffOutlined /> -->
        退出
      </div>
      <a-tooltip placement="bottomRight" :overlayStyle="{ width: '58px' }">
        <template #title>弹出给分板</template>
        <div
          class="tw-flex tw-place-content-center tw-cursor-pointer menu"
          :class="[
            store.isScoreBoardVisible && store.currentTask && 'menu-toggled',
          ]"
          @click="store.toggleScoreBoard"
        >
          <span class="tw-inline-flex tw-place-content-center tw-relative">
            <img
              src="./images/right-menu.svg"
              :class="[store.isScoreBoardVisible && 'svg-red']"
            />
          </span>
          <div
            v-if="store.isScoreBoardVisible && store.currentTask"
            class="triangle"
          ></div>
        </div>
      </a-tooltip>
    </div>
  </div>
  <MarkChangeProfile ref="changeProfileRef" />
  <MarkSwitchGroupDialog ref="switchGroupRef" />
  <MarkProblemDialog ref="problemRef" />
</template>

<script setup lang="ts">
import { doLogout, updateUISetting } from "@/api/markPage";
import { watch, watchEffect } from "vue";
import { store } from "@/store/store";
import MarkChangeProfile from "./MarkChangeProfile.vue";
import MarkSwitchGroupDialog from "./MarkSwitchGroupDialog.vue";
import MarkProblemDialog from "./MarkProblemDialog.vue";
import { isNumber } from "lodash-es";
import { Modal } from "ant-design-vue";

const props = defineProps<{ showTotalScore?: boolean }>();

const modeName = $computed(() =>
  store.setting.mode === "TRACK" ? "轨迹模式" : "普通模式"
);

const exchangeModeName = $computed(() =>
  store.setting.mode === "TRACK" ? "普通模式" : "轨迹模式"
);

async function toggleSettingMode() {
  if (store.isTrackMode) {
    store.setting.mode = "COMMON";
  } else {
    store.setting.mode = "TRACK";
  }
  await updateUISetting(store.setting.mode);

  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 (typeof totalCount !== "number" || 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 logout = () => {
  doLogout();
};

let changeProfileRef = $ref<InstanceType<typeof MarkChangeProfile>>();

// TODO: 应该是@typescript-eslint/no-unsafe-call不完美的搞法，导致了下面的调用会出错
type ShowModalFunc = () => void;

const openProfileModal = () => {
  (changeProfileRef.showModal as ShowModalFunc)();
};

let switchGroupRef = $ref<InstanceType<typeof MarkSwitchGroupDialog>>();

const openSwitchGroupModal = () => {
  (switchGroupRef.showModal as ShowModalFunc)();
};

let problemRef = $ref<InstanceType<typeof MarkProblemDialog>>();

const openProblemModal = () => {
  (problemRef.showModal as ShowModalFunc)();
};

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,
    });
  }
});

const todoCount = $computed(() =>
  typeof store.status.totalCount === "number"
    ? store.status.totalCount - store.status.markedCount
    : "-"
);

let questionMarkShouldChange = $ref(false);
watch(
  () => [store.status.problemCount, store.status.arbitrateCount],
  () => {
    if (!store.status.problemCount && !store.status.arbitrateCount) return;
    questionMarkShouldChange = true;
    setTimeout(() => {
      questionMarkShouldChange = false;
    }, 11 * 1000);
  }
);
</script>

<style scoped>
.header-bg-color {
  background-color: var(--header-bg-color);
}

.header-container {
  position: relative;
  height: 56px;
  line-height: 16px;

  background-color: var(--header-bg-color);
  color: rgba(255, 255, 255, 0.5);
}

.menu {
  width: 56px;
  height: 56px;
  padding: 20px;
}

.menu:hover,
.menu-toggled {
  background-color: rgba(255, 255, 255, 0.2);
}

.header-container span {
  vertical-align: middle;
}

.header-big-text {
  font-size: 20px;
  line-height: 30px;
}

.header-small-text {
  font-size: var(--app-secondary-font-size);
}

.highlight-text {
  color: white;
  font-size: var(--app-title-font-size);
}

.header-bg-color.ant-btn:hover {
  background-color: var(--app-ant-select-bg-override-color) !important;
}

.assistant-table {
  z-index: 5500;
  border-collapse: separate;
  border-spacing: 0 1em;
  color: var(--app-bold-text-color);
  width: 240px;
}

.assistant-table tr td:nth-child(2) {
  text-align: right;
}

.svg-red {
  filter: invert(27%) sepia(51%) saturate(2878%) hue-rotate(346deg)
    brightness(104%) contrast(97%);
}

.svg-red-hover:hover {
  filter: invert(27%) sepia(51%) saturate(2878%) hue-rotate(346deg)
    brightness(104%) contrast(97%);
}

.triangle {
  background-color: white;
  width: 10px;
  height: 10px;
  clip-path: polygon(0 100%, 100% 100%, 50% 0);

  position: absolute;
  bottom: -2px;
}

.dropdown-triangle {
  background-color: #8c8d9b;
  width: 7px;
  height: 5px;
  clip-path: polygon(0 0, 100% 0, 50% 100%);
  margin-left: 4px;
}

.count-animation-enter-active,
.count-animation-leave-active {
  transition: all 1.2s ease-in-out;
}

.count-animation-enter-from,
.count-animation-leave-to {
  opacity: 0;
  transform: translateY(18px);
}

.question-mark-animation {
  animation: pluse 2s ease-in-out infinite alternate;
}

@keyframes pluse {
  0% {
    scale: 0.7;
  }

  100% {
    scale: 1.3;
  }
}
</style>
