<template>
  <div
    v-if="store.setting.uiSetting['score.board.collapse']"
    @mouseover="handleMouseOverWithBoard"
  >
    <div class="tw-self-start tw-cursor-pointer hover:tw-bg-gray-200">
      <a-switch
        v-model:checked="store.setting.uiSetting['score.board.collapse']"
        @mouseover="(e) => e.stopPropagation()"
      />
    </div>
  </div>
  <div
    v-if="store.currentTask"
    class="mark-board-track-container"
    :class="store.setting.uiSetting['score.board.collapse'] && 'hide-board'"
    @mouseover="handleMouseOverWithBoard"
    @mouseout="handleMouseOutWithBoard"
  >
    <div class="tw-my-2 tw-flex">
      <div
        class="tw-self-start tw-cursor-pointer hover:tw-bg-gray-200 tw-mr-20"
      >
        <a-switch
          v-model:checked="store.setting.uiSetting['score.board.collapse']"
        />
      </div>
      <a-dropdown class="tw-self-end">
        <template #overlay>
          <a-menu>
            <a-menu-item key="1" @click="toggleKeyMouse">
              鼠标给分
            </a-menu-item>
          </a-menu>
        </template>
        <a-button>
          键盘给分
          <DownOutlined style="display: inline-flex" />
        </a-button>
      </a-dropdown>
    </div>
    <div>
      <h1 class="tw-text-3xl tw-text-center">
        总分：{{ store.currentMarkResult?.markerScore || 0 }}
      </h1>
    </div>

    <div class="tw-mb-2 tw-flex tw-place-content-center">
      <qm-button
        type="primary"
        shape="round"
        size="large"
        @click="$emit('allZeroSubmit')"
        v-if="store.setting.enableAllZero"
      >
        全零分
      </qm-button>
    </div>

    <div v-if="store.currentTask && store.currentTask.questionList">
      <template
        v-for="(question, index) in store.currentTask?.questionList"
        :key="index"
      >
        <div
          @click="chooseQuestion(question)"
          class="question tw-rounded tw-p-1 tw-mb-2"
          :class="isCurrentQuestion(question) && 'current-question'"
        >
          <div class="tw-flex tw-justify-between">
            <div>
              <div>
                {{ question.title }} {{ question.mainNumber }}-{{
                  question.subNumber
                }}
              </div>
              <div class="tw-text-center tw-text-3xl">
                {{ isCurrentQuestion(question) ? scoreStr : question.score }}
              </div>
            </div>
            <div>
              <div class="tw-text-center">
                间隔{{ question.intervalScore }}分
              </div>
              <div class="tw-flex tw-text-3xl" style="width: 80px">
                <span class="tw-flex-1">{{ question.minScore }}</span>
                <span class="tw-flex-1">~</span>
                <span class="tw-flex-1 tw-text-center">{{
                  question.maxScore
                }}</span>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script lang="ts">
import { Question } from "@/types";
import { isNumber } from "lodash";
import {
  computed,
  defineComponent,
  onMounted,
  onUnmounted,
  ref,
  watch,
} from "vue";
import { store } from "./store";
import { keyMouse } from "./use/keyboardAndMouse";
import { autoChooseFirstQuestion } from "./use/autoChooseFirstQuestion";
import { message } from "ant-design-vue";
import { DownOutlined } from "@ant-design/icons-vue";

export default defineComponent({
  name: "MarkBoardKeyBoard",
  emits: ["submit", "allZeroSubmit"],
  components: { DownOutlined },
  setup(props, { emit }) {
    const { toggleKeyMouse } = keyMouse();
    const { chooseQuestion } = autoChooseFirstQuestion();

    /**
     * 当前题的输入串，初次是question.score，然后接收输入字符，回车时判断是否合法，合法则赋值给question.score
     * 切换到下一题，则重新开始
     *  */
    let scoreStr = ref("");
    watch(
      () => [store.currentQuestion, store.setting.uiSetting["normal.mode"]],
      () => {
        if (isNumber(store.currentQuestion?.score)) {
          scoreStr.value = "" + store.currentQuestion?.score;
        } else {
          scoreStr.value = "";
        }
      },
      { immediate: true }
    );

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

      const remainScore = Math.round(question.maxScore * 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
      );
    }

    function numberKeyListener(event: KeyboardEvent) {
      // console.log(event);
      if (!store.currentQuestion || !store.currentTask) return;

      function indexOfCurrentQuestion() {
        return store.currentTask?.questionList.findIndex(
          (q) =>
            q.mainNumber === store.currentQuestion?.mainNumber &&
            q.subNumber === store.currentQuestion.subNumber
        );
      }
      // 处理Enter跳下一题或submit
      if (event.key === "Enter") {
        const allScoreMarked = store.currentTask?.questionList.every((q) =>
          isNumber(q.score)
        );
        // 如果所有题已赋分，并且当前题赋分和输入串和当前题分数一致，则可以在任意题提交
        if (
          allScoreMarked &&
          scoreStr.value === "" + store.currentQuestion.score
        ) {
          submit();
          return;
        }

        if (scoreStr.value.length === 0) {
          message.error({ content: "请输入分数", duration: 5 });
          console.log("请输入分数");
          return;
        }

        // 0 分
        // 整数分 (开始不为0)
        // 小数分 (开始和结束不为0，结束必须为1-9
        if (
          !(
            scoreStr.value === "0" ||
            /^[1-9]\d*$/.test(scoreStr.value) ||
            /^[1-9]\d*\.\d*[1-9]$/.test(scoreStr.value)
          )
        ) {
          message.error({ content: "分数格式不正确", duration: 5 });
          console.log("分数格式不正确");
          return;
        }
        const score = parseFloat(scoreStr.value);
        // console.log(score);
        if (!isNumber(score)) {
          message.error({ content: "非数字输入", duration: 5 });
          console.log("非数字输入");
          return;
        }
        if (!questionScoreSteps.value.includes(score)) {
          message.error({ content: "输入的分数不在有效间隔内", duration: 5 });
          return;
        }
        store.currentQuestion.score = score;
        //
        // scoreStr.value = "";
        // console.log("give score", score);
        const idx = indexOfCurrentQuestion() as number;
        if (idx + 1 < store.currentTask?.questionList.length) {
          chooseQuestion(store.currentTask.questionList[idx + 1]);
        }
        return;
      }
      if (event.key === "ArrowLeft") {
        const idx = indexOfCurrentQuestion() as number;
        if (idx > 0) {
          chooseQuestion(store.currentTask.questionList[idx - 1]);
        }
        return;
      }
      if (event.key === "ArrowRight") {
        const idx = indexOfCurrentQuestion() as number;
        if (idx < store.currentTask.questionList.length - 1) {
          chooseQuestion(store.currentTask.questionList[idx + 1]);
        }
        return;
      }
      // 处理回退删除分数
      if (event.key === "Backspace") {
        if (scoreStr.value.length > 0) {
          scoreStr.value = scoreStr.value.slice(0, -1);
        } else {
          return;
        }
      }
      if (event.key === "Escape") {
        scoreStr.value = "";
      }

      // 此时不再接受任何非数字键
      if (".0123456789".includes(event.key)) {
        scoreStr.value += event.key;
      }
    }
    onMounted(() => {
      document.addEventListener("keydown", numberKeyListener);
    });
    onUnmounted(() => {
      document.removeEventListener("keydown", numberKeyListener);
    });

    const collapseSideBar = () => {
      store.setting.uiSetting["score.board.collapse"] = !!!store.setting
        .uiSetting["score.board.collapse"];
    };

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

    return {
      store,
      collapseSideBar,
      handleMouseOverWithBoard,
      handleMouseOutWithBoard,
      toggleKeyMouse,
      isCurrentQuestion,
      chooseQuestion,
      scoreStr,
      questionScoreSteps,
      submit,
    };
  },
});
</script>

<style scoped>
.mark-board-track-container {
  max-width: 250px;
  min-width: 250px;
  border-left: 1px solid grey;
  padding-left: 6px;
  padding-right: 6px;
  max-height: calc(100vh - 41px);
  overflow: scroll;
}
.hide-board {
  margin-right: -250px;
}
.show-board {
  position: absolute;
  background-color: white;
  right: 250px;
}
.question {
  min-width: 80px;
  border: 1px solid grey;
}
.current-question {
  border: 1px solid yellowgreen;
  background-color: lightblue;
}
.single-score {
  width: 30px;
  height: 30px;
  display: grid;
  place-content: center;

  border: 1px solid black;
  border-radius: 5px;
}
.current-score {
  border: 1px solid yellowgreen;
  background-color: lightblue;
}
</style>
