<template>
  <div v-if="store.setting && store.setting.subject.name" class="mark-header">
    <div class="mark-header-part">
      <div
        :class="[
          'header-menu',
          'header-menu-left',
          { 'is-toggled': store.historyOpen },
        ]"
        @click="store.toggleHistory"
      >
        <img class="header-icon" src="@/assets/icons/icon-left-menu.svg" />回评
      </div>
      <div class="header-subject" :title="store.setting.subject.name">
        {{
          `${store.setting.subject.code ?? ""}-${
            store.setting.subject.name ?? ""
          }`
        }}
      </div>
      <a-tooltip overlayClassName="mark-tooltip">
        <template #title>
          问题卷 {{ store.status.problemCount }}
          <br />
          待仲裁 {{ store.status.arbitrateCount }}
        </template>
        <div class="header-programs">
          <img
            class="header-icon"
            src="@/assets/icons/icon-problems.svg"
            @mouseover="questionMarkShouldChange = false"
          />
        </div>
      </a-tooltip>
      <div class="header-secret">
        <div class="header-noun">
          <span>编号：</span>
          <span>
            {{ store.currentTask?.secretNumber ?? "-" }}
          </span>
        </div>
        <div
          v-if="
            store.currentTask &&
            store.currentTask.objectiveScore !== null &&
            !!store.setting?.showObjectScore
          "
          class="header-noun"
        >
          <span>客观分：</span>
          <span>
            {{ store.currentTask.objectiveScore }}
          </span>
        </div>
        <div
          v-if="
            props.showTotalScore &&
            store.currentTask &&
            store.currentTask.objectiveScore !== null
          "
          class="header-noun"
        >
          <span>成绩：</span>
          <span> {{ totalScore }} </span>
        </div>
      </div>
      <div v-show="store.status.totalCount" class="header-total">
        <span class="header-noun">
          <span>已评：</span>
          <transition-group name="count-animation" tag="span">
            <span :key="store.status.personCount || 0">
              {{ store.status.personCount }}
            </span>
          </transition-group>
        </span>
        <span v-if="store.setting.topCount" class="header-noun">
          <span>分配：</span>
          <span>{{ store.setting.topCount ?? "-" }}</span>
        </span>
        <span class="header-noun">
          <span>未评：</span>
          <transition-group name="count-animation" tag="span">
            <span :key="todoCount || 0">
              {{ todoCount }}
            </span>
          </transition-group>
        </span>
        <span class="header-noun">
          <span>进度：</span>
          <transition-group name="count-animation" tag="span">
            <span :key="progress || '-'"> {{ progress }}% </span>
          </transition-group>
        </span>
      </div>
    </div>

    <div class="mark-header-part">
      <a-tooltip overlayClassName="mark-tooltip">
        <template #title>
          {{
            store.setting.startTime > 0
              ? $filters.datetimeFilter(store.setting.startTime)
              : "-"
          }}
          <div style="text-align: center">~</div>
          {{
            store.setting.endTime > 0
              ? $filters.datetimeFilter(store.setting.endTime)
              : "-"
          }}
        </template>
        <div class="header-text-btn">
          <img
            class="header-icon"
            src="@/assets/icons/icon-times.svg"
          />评卷时间段
        </div>
      </a-tooltip>
      <a-dropdown>
        <template v-if="!store.setting.forceMode" #overlay>
          <a-menu>
            <a-menu-item key="1" @click="toggleSettingMode">
              {{ exchangeModeName }}
            </a-menu-item>
          </a-menu>
        </template>

        <div class="header-text-btn">
          <img src="@/assets/icons/icon-track-mode.svg" class="header-icon" />
          {{ modeName }}
          <CaretDownOutlined v-if="!store.setting.forceMode" class="a-icon" />
        </div>
      </a-dropdown>
      <div
        class="header-text-btn"
        :title="store.setting.groupTitle + '-' + store.setting.groupNumber"
        @click="openSwitchGroupModal"
      >
        <img class="header-icon" src="@/assets/icons/icon-group.svg" />{{
          "分组：" + store.setting.groupNumber
        }}
        <CaretDownOutlined v-if="store.groups.length > 1" class="a-icon" />
      </div>
      <div class="header-text-btn">
        <img class="header-icon" src="@/assets/icons/icon-user.svg" />{{
          store.setting.userName
        }}
      </div>
      <div class="header-text-btn header-logout" @click="logout">
        <img class="header-icon" src="@/assets/icons/icon-return.svg" />返回
      </div>

      <a-tooltip v-if="store.isTrackMode" placement="bottomRight">
        <template #title>弹出给分板</template>
        <div
          :class="[
            'header-menu',
            { 'is-toggled': store.isScoreBoardVisible && store.currentTask },
          ]"
          @click="store.toggleScoreBoard"
        >
          <img src="@/assets/icons/icon-right-menu.svg" class="header-icon" />
        </div>
      </a-tooltip>
      <div v-else class="header-menu is-toggled">
        <img src="@/assets/icons/icon-right-menu.svg" class="header-icon" />
      </div>
    </div>
  </div>
  <MarkChangeProfile ref="changeProfileRef" />
  <MarkSwitchGroupDialog ref="switchGroupRef" />
</template>

<script setup lang="ts">
import { doLogout, updateUISetting, clearMarkTask } from "@/api/markPage";
import { watch, watchEffect } from "vue";
import { store } from "@/store/store";
import MarkChangeProfile from "./MarkChangeProfile.vue";
import MarkSwitchGroupDialog from "./MarkSwitchGroupDialog.vue";
import { isNumber } from "lodash-es";
import { Modal } from "ant-design-vue";
import { CaretDownOutlined } from "@ant-design/icons-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, store.setting.uiSetting);

  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 totalScore = $computed(() => {
  return parseFloat(
    (
      ((Math.max(store.currentTask.objectiveScore || 0, 0) * 100 +
        Math.max(store.currentTask.markResult?.markerScore || 0, 0) * 100) |
        0) /
      100
    ).toFixed(2)
  );
});

const logout = async () => {
  await clearMarkTask();
  doLogout();
};

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

// 应该是@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)();
};

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 -
      store.status.problemCount -
      store.status.arbitrateCount
    : "-"
);

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>
