<script setup lang="ts">
import { store } from "@/store/store";
import { watch } from "vue";
import QuestionAudio from "./QuestionAudio.vue";

const props = defineProps<{ questionBody: string }>();
const examQuestion = $computed(() => store.exam.currentQuestion);

let questionSegements: {
  text: string;
  audios: { src: string; name: string }[];
} | null = $ref(null);

watch(
  () => store.exam.currentQuestion?.order,
  () => parseQuestion(),
  { immediate: true }
);

function parseQuestion() {
  let questionText = "";
  let capAudios: { name: string; src: string }[] = [];
  if (props.questionBody.includes("question-audio")) {
    questionText = props.questionBody.replace(
      /<a.*?name="([^"]*)".*?question-audio.*?url="([^"]*)".*?\/a>/g,
      function (_, name, src) {
        capAudios.push({ name, src });
        return "";
      }
    );
  } else {
    questionText = props.questionBody;
  }

  questionSegements = { text: questionText, audios: capAudios };
}

function played(name: string) {
  if (!store.exam.currentQuestion.limitedPlayTimes) {
    // 如果没有设置音频播放次数，可无限播放
    return false;
  }
  logger({
    cnl: ["server"],
    lvl: "debug",
    pgu: "AUTO",
    act: "开始播放音频",
  });

  // 正在播放中
  store.updateQuestionAudioPlayTimes(name);
}

function getAudioPlayedTimes(name: string) {
  const playedTimes =
    store.exam.allAudioPlayTimes.find((a) => a.audioName === name)?.times ?? 0;
  return Math.max(examQuestion.limitedPlayTimes - playedTimes, 0);
}
</script>

<template>
  <div v-if="questionSegements" class="question-body">
    <div v-html="questionSegements.text" />

    <div
      v-for="(item, index) in questionSegements.audios"
      :key="index"
      style="
        position: relative;
        font-size: 18px;
        word-break: break-word;
        background-color: lightblue;
        border-radius: 4px;
        padding-left: 2px;
        padding-top: 2px;
      "
      class="audio-div"
    >
      <QuestionAudio
        :name="item.name"
        :src="item.src"
        :playCount="
          examQuestion.limitedPlayTimes ? getAudioPlayedTimes(item.name) : 1
        "
        @played="played(item.name)"
      />
      <span v-if="examQuestion.limitedPlayTimes">
        （<span class="tw-text-red-700">请点击播放</span
        >按钮听音作答。已播次数：<span class="tw-text-red-700">{{
          examQuestion.limitedPlayTimes - getAudioPlayedTimes(item.name)
        }}</span
        >，剩余播放次数：<span class="tw-text-red-700"
          >{{ getAudioPlayedTimes(item.name) }} </span
        >）
      </span>
    </div>
  </div>

  <div v-else>试题解析中...</div>
</template>

<style>
.question-body {
  font-size: 18px;
}

.question-body img {
  display: inline-block;
}

.audio-div {
  display: inline-flex;
  align-items: center;
  margin-right: 4px;
  margin-bottom: 4px;
}
</style>
