<script setup lang="ts">
import { store } from "@/store/store";
import { onMounted, onUnmounted } from "vue";
import QuestionBody from "./QuestionBody.vue";

const optionName = "ABCDEFGHIJ".split("");

let isShowAnswer = $ref(false);
function toggleShowAnswer() {
  isShowAnswer = !isShowAnswer;
}

const examQuestion = $computed(() => store.exam.currentQuestion);

const newQuestionOptions = $computed(() => {
  return examQuestion.questionOptionList.map((v, i) => {
    return {
      value: examQuestion.questionOptionList[examQuestion.optionPermutation[i]],
      oldIndex: "" + examQuestion.optionPermutation[i],
      name: optionName[i],
    };
  });
});

const oldIndexToABCD = $computed(() => {
  const ans = examQuestion.studentAnswer;
  return (
    ans &&
    newQuestionOptions
      .filter((v) => ans.includes(v.oldIndex))
      .map((v) => v.name)
      .join("")
  );
});

const rightAnswerTransform = $computed(() => {
  return (
    examQuestion.rightAnswer &&
    newQuestionOptions
      .filter((v) => examQuestion.rightAnswer?.includes(v.oldIndex))
      .map((v) => v.name)
      .join("")
  );
});

onMounted(() => {
  window.addEventListener("keyup", keyup);
});
onUnmounted(() => {
  window.removeEventListener("keyup", keyup);
});
function keyup(e: KeyboardEvent) {
  const { tagName = "" } = document?.activeElement || {};
  if (
    (examQuestion.questionType === "SINGLE_CHOICE" ||
      examQuestion.questionType === "MULTIPLE_CHOICE") &&
    ["BODY", "A", "BUTTON", "DIV"].includes(tagName)
  ) {
    if (
      optionName
        .map((v) => "Key" + v)
        .slice(0, examQuestion.questionOptionList.length)
        .includes(e.code)
    ) {
      _hmt.push(["_trackEvent", "答题页面", "快捷键", "ABCDE"]);
      logger({ cnl: ["server"], lvl: "debug", act: "选择题键盘作答" });
      const keyAns = newQuestionOptions.find((v) => v.name == e.code[3]);
      if (keyAns) {
        answerQuestion(keyAns.oldIndex);
      }
    }
  }
}

function answerQuestion(studentAnswer: string) {
  if (examQuestion.questionType === "SINGLE_CHOICE") {
    examQuestion.studentAnswer = studentAnswer;
  } else {
    // 多选题
    const oldAns = examQuestion.studentAnswer;
    if (oldAns) {
      if (oldAns.includes(studentAnswer)) {
        examQuestion.studentAnswer = oldAns.replace(studentAnswer, "");
      } else {
        examQuestion.studentAnswer = oldAns
          .concat(studentAnswer)
          .split("")
          .sort()
          .join("");
      }
    } else {
      examQuestion.studentAnswer = studentAnswer;
    }
  }
  store.updateExamQuestion({
    order: examQuestion.order,
    studentAnswer: examQuestion.studentAnswer,
  });
}
</script>

<template>
  <div class="question-view">
    <question-body :questionBody="examQuestion.body" />
    <div class="ops">
      <div class="stu-answer">{{ oldIndexToABCD }}</div>
      <div class="score">({{ examQuestion.questionScore }}分)</div>
    </div>
    <div
      v-for="(option, index) in newQuestionOptions"
      :key="index"
      class="option"
      @click="() => answerQuestion(option.oldIndex)"
    >
      <div
        :class="
          examQuestion.studentAnswer?.includes(option.oldIndex) &&
          'row-selected'
        "
        class="tw-flex tw-items-start"
      >
        <div>
          <input
            :type="
              examQuestion.questionType === 'SINGLE_CHOICE'
                ? 'radio'
                : 'checkbox'
            "
            name="question"
            :value="option.oldIndex"
            :checked="examQuestion.studentAnswer?.includes(option.oldIndex)"
          />
        </div>
        <span style="padding: 0 10px">{{ optionName[index] }}: </span>
        <div v-if="option.value" class="question-options">
          <question-body :questionBody="option.value.body" />
        </div>
      </div>
    </div>
    <div v-if="store.examShouldShowAnswer" class="reset">
      <span>
        <n-button type="success" @click="toggleShowAnswer">
          {{ isShowAnswer ? "隐藏" : "显示" }}答案
        </n-button>
      </span>
      <div v-if="isShowAnswer" class="tw-mt-2">
        正确答案：
        <div>{{ rightAnswerTransform }}</div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.question-view {
  display: grid;
  grid-row-gap: 10px;
}

.ops {
  display: flex;
  align-items: flex-end;
}

.stu-answer {
  width: 100px;
  border-bottom: 1px solid black;
  text-align: center;
  height: 20px;
}

.option {
  display: flex;
  cursor: pointer;
  padding-top: 10px;
  border-radius: 5px;
}

.question-options {
  flex: 1;
}

.option:hover {
  background-color: aliceblue;
}

.row-selected {
  background-color: aliceblue;
  width: 100%;
}

.question-options > .question-body {
  text-align: left;
  font-size: 16px !important;
}
</style>
