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

    <div class="mark-header-part">
      <a-tooltip overlayClassName="mark-tooltip">
        <template #title>
          {{
            markStore.setting.startTime > 0
              ? $filters.datetimeFilter(markStore.setting.startTime)
              : "-"
          }}
          <div style="text-align: center">~</div>
          {{
            markStore.setting.endTime > 0
              ? $filters.datetimeFilter(markStore.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="!markStore.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" />
          {{ markStore.modeName }}
          <CaretDownOutlined
            v-if="!markStore.setting.forceMode"
            class="a-icon"
          />
        </div>
      </a-dropdown>
      <div class="header-text-btn">
        <img class="header-icon" src="@/assets/icons/icon-user.svg" />{{
          markStore.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="markStore.isTrackMode" placement="bottomRight">
        <template #title>弹出给分板</template>
        <div
          :class="[
            'header-menu',
            {
              'is-toggled':
                markStore.isScoreBoardVisible && markStore.currentTask,
            },
          ]"
          @click="markStore.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>
</template>

<script setup lang="ts">
import { watch, watchEffect } from "vue";
import { Modal } from "ant-design-vue";
import { CaretDownOutlined } from "@ant-design/icons-vue";
import { isNumber } from "lodash-es";

import { useMarkStore } from "@/store";
import { doLogout, updateUISetting, clearMarkTask } from "@/api/markPage";

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

const markStore = useMarkStore();

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

async function toggleSettingMode() {
  if (markStore.isTrackMode) {
    markStore.setting.mode = "COMMON";
  } else {
    markStore.setting.mode = "TRACK";
  }
  await updateUISetting(markStore.setting.mode, markStore.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 } = markStore.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(markStore.currentTask.objectiveScore || 0, 0) * 100 +
        Math.max(markStore.currentTask.markResult?.markerScore || 0, 0) * 100) |
        0) /
      100
    ).toFixed(2)
  );
});

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

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

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

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