<template>
  <div
    v-if="store.currentTask"
    class="mark-board-track-container"
    :class="[store.setting.uiSetting['score.board.collapse'] ? 'hide' : 'show']"
  >
    <div
      class="
        tw-flex tw-rounded tw-justify-between tw-p-2 tw-pl-5
        top-container
        tw-mb-4
      "
    >
      <div class="tw-flex tw-flex-col">
        <div>总分</div>
        <div class="total-score">
          {{ store.currentMarkResult?.markerScore }}
        </div>
      </div>

      <div
        class="
          tw-flex tw-flex-col tw-place-content-center tw-items-center tw-gap-1
        "
      >
        <a-popconfirm
          v-if="store.setting.enableAllZero && !store.setting.forceSpecialTag"
          title="确定给全零分？"
          ok-text="确定"
          cancel-text="取消"
          @confirm="$emit('allZeroSubmit')"
        >
          <a-button type="primary" shape="round" size="medium">
            全零分
          </a-button>
        </a-popconfirm>

        <qm-button type="primary" shape="round" size="medium" @click="submit">
          提交
        </qm-button>
      </div>
    </div>

    <div
      style="
        height: calc(100vh - 56px - 200px);
        overflow: hidden;
        user-select: none;
        position: relative;
      "
    >
      <div
        v-if="store.currentTask && store.currentTask.questionList"
        class="
          tw-flex
          tw-gap-2
          tw-flex-wrap
          tw-justify-between
          tw-overflow-auto
          tw-content-start
        "
        style="min-height: 20% !important; max-height: 80% !important"
        :style="{ height: `${topPercent}%` }"
      >
        <template
          v-for="(question, index) in store.currentTask?.questionList"
          :key="index"
        >
          <div
            @click="chooseQuestion(question)"
            class="question tw-rounded tw-cursor-pointer tw-relative"
            :class="isCurrentQuestion(question) && 'current-question'"
          >
            <div>
              {{ question.title }} {{ question.mainNumber }}-{{
                question.subNumber
              }}
            </div>
            <div class="tw-font-medium tw-text-2xl score">
              <!-- 特殊的空格符号 -->
              {{ question.score ?? " " }}
            </div>
            <div
              v-if="isCurrentQuestion(question)"
              class="current-score-indicator"
            ></div>
          </div>
        </template>
      </div>

      <div
        style="
          width: 100%;
          height: 4px;
          border: 2px solid grey;
          cursor: row-resize;
        "
        ref="dragSpliter"
      ></div>
      <div
        class="tw-flex tw-flex-wrap tw-mt-5 tw-overflow-auto tw-content-start"
        style="padding-bottom: 40px; gap: 8px"
        :style="{ height: `${100 - topPercent}%` }"
      >
        <div
          v-for="(s, i) in questionScoreSteps"
          :key="i"
          @click="chooseScore(s)"
          class="single-score tw-cursor-pointer tw-font-bold"
          :class="isCurrentScore(s) && 'current-score'"
        >
          {{ s }}
          <div v-if="isCurrentScore(s)" class="current-score-indicator"></div>
        </div>
      </div>
    </div>
    <div
      class="tw-flex tw-justify-between tw-mt-4"
      style="position: relative; bottom: 0px; right: 0px; width: 230px"
    >
      <qm-button
        type="primary"
        shape="round"
        size="large"
        :clickTimeout="300"
        @click="clearLatestMarkOfCurrentQuetion"
      >
        回退
      </qm-button>

      <qm-button
        type="primary"
        shape="round"
        size="large"
        :clickTimeout="300"
        @click="clearAllMarksOfCurrentQuetion"
      >
        清除本题
      </qm-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Question } from "@/types";
import { isNumber } from "lodash";
import { computed, onMounted, onUnmounted, watch } from "vue";
import { store } from "./store";
import { autoChooseFirstQuestion } from "./use/autoChooseFirstQuestion";
import { message } from "ant-design-vue";
import { dragSplitPane } from "./use/splitPane";

const emit = defineEmits(["submit", "allZeroSubmit"]);
const { dragSpliter, topPercent } = dragSplitPane();

const { chooseQuestion } = autoChooseFirstQuestion();

const questionScoreSteps = computed(() => {
  const question = store.currentQuestion;
  if (!question) return [];

  const remainScore =
    Math.round(question.maxScore * 100 - (question.score || 0) * 100) / 100;
  const steps = [];
  for (
    let i = 0;
    i <= remainScore;
    i = Math.round(i * 100 + question.intervalScore * 100) / 100
  ) {
    steps.push(i);
  }
  if (
    Math.round(remainScore * 100) % Math.round(question.intervalScore * 100) !==
    0
  ) {
    steps.push(remainScore);
  }

  return steps;
});

function isCurrentQuestion(question: Question) {
  return (
    store.currentQuestion?.mainNumber === question.mainNumber &&
    store.currentQuestion?.subNumber === question.subNumber
  );
}
watch(
  () => store.currentQuestion,
  () => {
    store.currentScore = undefined;
  }
);

function isCurrentScore(score: number) {
  return store.currentScore === score;
}
function chooseScore(score: number) {
  if (store.currentScore === score) {
    store.currentScore = undefined;
  } else {
    store.currentScore = score;
    store.currentSpecialTag = undefined;
  }
}

let keyPressTimestamp = 0;
let keys: string[] = [];
function numberKeyListener(event: KeyboardEvent) {
  // console.log(event);
  if (!store.currentQuestion) return;

  function indexOfCurrentQuestion() {
    return store.currentTask?.questionList.findIndex(
      (q) =>
        q.mainNumber === store.currentQuestion?.mainNumber &&
        q.subNumber === store.currentQuestion.subNumber
    );
  }

  // tab 循环答题列表
  if (event.key === "Tab") {
    const idx = indexOfCurrentQuestion() as number;
    if (idx >= 0 && store.currentTask) {
      const len = store.currentTask.questionList.length;
      chooseQuestion(store.currentTask.questionList[(idx + 1) % len]);
      event.preventDefault();
    }
    return;
  }

  if (event.timeStamp - keyPressTimestamp > 1 * 1000) {
    keys = [];
  }
  keyPressTimestamp = event.timeStamp;
  keys.push(event.key);
  if (isNaN(parseFloat(keys.join("")))) {
    keys = [];
  }
  if (event.key === "Escape") {
    keys = [];
    store.currentScore = undefined;
    store.currentSpecialTag = undefined;
    return;
  }
  const score = parseFloat(keys.join(""));
  if (isNumber(score) && questionScoreSteps.value.includes(score)) {
    chooseScore(score);
  }
}

function submitListener(e: KeyboardEvent) {
  if (import.meta.env.DEV && e.ctrlKey && e.key === "Enter") {
    submit();
  }
}
onMounted(() => {
  document.addEventListener("keydown", numberKeyListener);
  document.addEventListener("keydown", submitListener);
});
onUnmounted(() => {
  document.removeEventListener("keydown", numberKeyListener);
  document.removeEventListener("keydown", submitListener);
});

const handleMouseOverWithBoard = () => {
  if (store.setting.uiSetting["score.board.collapse"]) {
    const container = document.querySelector(".mark-board-track-container");
    if (container) {
      container.classList.add("show-board");
    }
  }
};

const handleMouseOutWithBoard = () => {
  if (store.setting.uiSetting["score.board.collapse"]) {
    const container = document.querySelector(".mark-board-track-container");
    if (container) {
      container.classList.remove("show-board");
    }
  }
};

function clearLatestMarkOfCurrentQuetion() {
  if (!store.currentMarkResult || !store.currentQuestion) return;

  const ts = store.currentMarkResult?.trackList.filter(
    (q) =>
      q.mainNumber === store.currentQuestion?.mainNumber &&
      q.subNumber === store.currentQuestion?.subNumber
  );
  if (ts.length === 0) {
    return;
  }
  if (ts.length === 1) {
    // 即将清除最后一条记录，置为0，因为watch trackList 算分要考虑不同模式的回评，无法自动
    store.currentQuestion.score = null;
  }
  const maxNumber = Math.max(...ts.map((q) => q.number));
  const idx = store.currentMarkResult.trackList.findIndex(
    (q) =>
      q.mainNumber === store.currentQuestion?.mainNumber &&
      q.subNumber === store.currentQuestion?.subNumber &&
      q.number === maxNumber
  );
  if (idx >= 0) {
    store.removeScoreTracks = store.currentMarkResult.trackList.splice(idx, 1);
  }
}

function clearAllMarksOfCurrentQuetion() {
  if (!store.currentMarkResult || !store.currentQuestion) return;

  store.removeScoreTracks = store.currentMarkResult?.trackList.filter(
    (q) =>
      q.mainNumber === store.currentQuestion?.mainNumber &&
      q.subNumber === store.currentQuestion?.subNumber
  );
  store.currentMarkResult.trackList = store.currentMarkResult?.trackList.filter(
    (q) =>
      !(
        q.mainNumber === store.currentQuestion?.mainNumber &&
        q.subNumber === store.currentQuestion?.subNumber
      )
  );
  store.currentQuestion.score = null;
}

function submit() {
  const errors: any = [];
  store.currentTask?.questionList.forEach((question, index) => {
    if (!isNumber(question.score)) {
      errors.push({
        question,
        index,
        error: `${question.mainNumber}-${question.subNumber} 没有赋分不能提交。`,
      });
    }
  });
  if (errors.length === 0) {
    emit("submit");
  } else {
    console.log(errors);
    message.error({
      content: errors.map((e: any) => `${e.error}`).join("\n"),
      duration: 10,
    });
  }
}
</script>

<style scoped>
.mark-board-track-container {
  max-width: 290px;
  min-width: 290px;
  padding: 20px;
  max-height: calc(100vh - 56px - 0px);
  overflow: auto;
  z-index: 1001;
  transition: margin-right 0.5s;
  --big-score-color: #283e76;
  --high-light-score-color: #5d65ff;
  --the-color: #7584ac;
  color: var(--the-color);
}
.mark-board-track-container.show {
  margin-right: 0;
}
.mark-board-track-container.hide {
  margin-right: -290px;
}

/* .hide-board {
  display: none;
} */
/* .show-board {
  position: absolute;
  background-color: white;
  right: 0px;
  display: block;
} */
.top-container {
  background-color: white;
}
.total-score {
  color: var(--big-score-color);
  font-size: 32px;
}
.question {
  min-width: 110px;
  max-width: 110px;
  min-height: 72px;
  padding: 10px;
  /* border: 1px solid grey; */
  background-color: white;
}
.current-question .score {
  /* border: 1px solid yellowgreen;
  background-color: lightblue; */
  color: var(--high-light-score-color);
}
.single-score {
  position: relative;
  width: 32px;
  height: 32px;
  font-size: 12px;
  display: grid;
  place-content: center;
  background-color: white;

  border-radius: 30px;
}
.current-score {
  /* border: 1px solid yellowgreen; */
  color: #5d65ff;
}
.current-score-indicator {
  position: absolute;
  top: 0;
  left: 0;
  width: 5px;
  height: 5px;
  background-color: #5c69f6;
}
</style>
