<template>
  <div v-if="store.currentTask" class="mark-board-track-container">
    <div class="tw-my-2 tw-flex tw-place-content-center">
      <a-dropdown>
        <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 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">
                <!-- {{ showScore(question) }} -->
                {{ question.__updateScore }}
              </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,
  reactive,
  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"],
  components: { DownOutlined },
  setup(props, { emit }) {
    const { toggleKeyMouse } = keyMouse();
    const { chooseQuestion } = autoChooseFirstQuestion();

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

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

    let keyPressTimestamp = 0;
    let keys = reactive([] as Array<String>);
    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") {
        // if (!isNumber(store.currentQuestion.score)) {
        //   // 当前题赋分不通过，Enter无效
        //   return;
        // }
        // 有bug，移除当前题，再回来就出错了
        if (keys.length === 0) {
          message.error({ content: "请输入分数", duration: 100 });
          console.log("请输入分数");
          return;
        }
        const score = parseFloat(keys.join(""));
        if (!isNumber(score)) {
          message.error({ content: "非数字输入", duration: 10 });
          console.log("非数字输入");
          return;
        }
        if (!questionScoreSteps.value.includes(score)) {
          message.error({ content: "输入的分数不在有效间隔内", duration: 10 });
          console.log("输入的分数不在有效间隔内");
          return;
        }
        store.currentQuestion.score = score;
        const idx = indexOfCurrentQuestion() as number;
        if (idx + 1 === store.currentTask?.questionList.length) {
          submit();
        } else {
          chooseQuestion(store.currentTask.questionList[idx + 1]);
        }
        keys = [];
        return;
      }
      if (event.key === "ArrowLeft") {
        const idx = indexOfCurrentQuestion() as number;
        if (idx > 0) {
          chooseQuestion(store.currentTask.questionList[idx - 1]);
        }
        keys = [];
        return;
      }
      if (event.key === "ArrowRight") {
        const idx = indexOfCurrentQuestion() as number;
        if (idx < store.currentTask.questionList.length - 1) {
          chooseQuestion(store.currentTask.questionList[idx + 1]);
        }
        keys = [];
        return;
      }
      // 处理回退删除分数
      if (event.key === "Backspace") {
        if (keys.length > 0) {
          keys.splice(keys.length - 1, 1);
        } else {
          return;
        }
      }
      if (event.key === "Escape") {
        keys = [];
      }

      // TODO: 确认数字按键的间隔
      // if (event.timeStamp - keyPressTimestamp > 1.5 * 1000) {
      //   keys = [];
      // }
      // keyPressTimestamp = event.timeStamp;
      // 此时不再接受任何非数字键
      if (".0123456789".includes(event.key)) {
        keys.push(event.key);
      }
      if (isNaN(parseFloat(keys.join("")))) {
        keys = [];
      }
      // FIXME: for update. 得想个更好的办法来解决不能更新的问题
      store.currentQuestion.__updateScore = keys.join("");
      // console.log(
      //   keys,
      //   keys.join(""),
      //   isCurrentQuestion(store.currentQuestion) && keys.length > 0
      // );
    }
    onMounted(() => {
      document.addEventListener("keydown", numberKeyListener);
    });
    onUnmounted(() => {
      document.removeEventListener("keydown", numberKeyListener);
    });

    const showScore = (question: Question) => {
      return isCurrentQuestion(question) && keys.length > 0
        ? keys.join("")
        : question.score;
    };

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

    return {
      store,
      toggleKeyMouse,
      isCurrentQuestion,
      chooseQuestion,
      keys,
      showScore,
      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;
}
.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>
