<template>
  <div v-if="questionDetail" class="question-body" :key="examQuestion.questionId">
    <div v-html="questionDetail.text"></div>
    <!-- <div v-html="questionDetail.audio"></div> -->
    <div v-for="({src, name}, index) in questionDetail.audio" :key="name" class="audio-div">
      <audio controls preload="auto" controlsList='nodownload' :key="src" :name="name" :src="src" @play="($event) => played(index, $event)"></audio>
      <span>（剩余播放次数：{{examQuestion.limitedPlayTimes -
        (allAudioPlayTimes.find(a => a.name === name) || { times: 0 }).times}}）</span><br />
    </div>
  </div>

  <div v-else>
    获取试题中...
  </div>
</template>

<script>
import { createNamespacedHelpers } from "vuex";
const { mapState, mapMutations } = createNamespacedHelpers("examingHomeModule");

export default {
  name: "QuestionBody",
  data() {
    return { questionDetail: null, audioPlayTimes: null };
  },
  props: {
    questionBody: String,
    examQuestion: Object
  },
  mounted() {
    this.parseQuestion();
  },
  // updated() {
  //   if (this.questionBody.includes("question-audio")) {
  //     console.log(this.questionBody);
  //     this.bindAudioPlay();
  //   }
  // },
  methods: {
    ...mapMutations(["updateExamQuestion", "updateQuestionAudioPlayTimes"]),
    async parseQuestion() {
      let question = {};
      if (this.questionBody.includes("question-audio")) {
        let audioArray = this.questionBody.match(/<a.*?question-audio.*?\/a>/g);
        if (!this.examQuestion.audioPlayTimes) {
          // 初始化音频播放次数
          this.audioPlayTimes = [];
        } else {
          this.audioPlayTimes = JSON.parse(this.examQuestion.audioPlayTimes);
        }
        question.text = this.questionBody.replace(
          /<a.*?question-audio.*?\/a>/g,
          ""
        );
        // 测试 v-html中含有directive是否生效。结论：不生效
        // question.text += "<span v-html='<text>abc</text>'>empty</span>";
        // audioArray = audioArray.map((v, i) => {
        //   const remainTimes =
        //     this.examQuestion.limitedPlayTimes -
        //     this.examQuestion.audioPlayTimes[i];
        //   if (remainTimes <= 0) {
        //     v = v.replace("<a", "<a disabled"); // disabled不生效，仅仅起标明作用
        //     v = v.replace(/url=/g, "");
        //   }
        //   return `${v}<span>（剩余播放次数：${remainTimes}）</span><br/>`;
        // });
        // question.audio = audioArray
        //   .join("")
        //   .replace(/<a/g, "<audio controls controlsList='nodownload'")
        //   .replace(/url=/g, "src=")
        //   .replace(/a>/g, "audio>");

        // console.log(this.questionBody);
        // console.log(this.questionBody.match(/url="[^"]*"/g));
        // question.audio = this.questionBody
        //   .match(/url="[^"]*"/g)
        //   .map(v => v.replace("url="));

        // /question-audio.*?url="[^"]*"/.exec(this.questionBody)

        question.audio = [];
        let re = /name="([^"]*)".*question-audio.*?url="([^"]*)"/g;
        let array1;
        while ((array1 = re.exec(this.questionBody)) !== null) {
          // console.log(`Found ${array1[0]}. Next starts at ${re.lastIndex}.`);
          // console.log(array1[1]);
          question.audio.push({ name: array1[1], src: array1[2] });
          // console.log(question.audio);
          // expected output: "Found foo. Next starts at 9."
          // expected output: "Found foo. Next starts at 19."
        }

        // setTimeout(this.bindAudioPlay.bind(this), 1000);
      } else {
        question.text = this.questionBody;
        question.audio = [];
      }
      this.questionDetail = question;
    },
    // bindAudioPlay() {
    //   const audios = document.getElementsByTagName("audio");
    //   if (audios.length === 0) {
    //     // setTimeout(this.bindAudioPlay.bind(this), 1000);
    //     return;
    //   }

    //   [...audios].forEach((audio, index) => {
    //     console.log("bind audio: order:" + this.examQuestion.order);
    //     const order = this.examQuestion.order;
    //     const limitedPlayTimes = this.examQuestion.limitedPlayTimes;
    //     let audioPlayTimes = this.examQuestion.audioPlayTimes;

    //     audio.addEventListener("play", () => {
    //       console.log("开始播放");
    //       if (limitedPlayTimes - audioPlayTimes <= 0) {
    //         console.log("无剩余播放次数");
    //       }
    //       audioPlayTimes[index] = audioPlayTimes[index] + 1;
    //       this.updateExamQuestion({
    //         order: order,
    //         audioPlayTimes: audioPlayTimes
    //       });
    //     });
    //     audio.addEventListener("ended", () => {
    //       console.log("结束播放");
    //       this.parseQuestion(); // 不会死循环，因为这个是音频播放触发的
    //     });
    //   });
    // },
    played(index, $event) {
      // $event.target.pause();
      const limitedPlayTimes = this.examQuestion.limitedPlayTimes;
      let audioPlayTimes = this.audioPlayTimes;
      console.log("开始播放");
      // console.log($event.target.attributes.name.value);
      const name = $event.target.attributes.name.value;
      // console.log(name);
      const theAudio = audioPlayTimes.find(a => a.name === name);
      const playedTimes = (theAudio || { times: 0 }).times;
      if (limitedPlayTimes - playedTimes <= 0) {
        console.log("无剩余播放次数");
        $event.target.pause();
        return;
      }

      // var audio = new Audio($event.target.src);
      // audio.play();

      if (theAudio) {
        theAudio.times = playedTimes + 1;
      } else {
        this.audioPlayTimes.push({ name: name, times: 1 });
      }
      this.updateQuestionAudioPlayTimes(name);
    }
  },
  computed: {
    ...mapState(["allAudioPlayTimes"])
  },
  watch: {
    questionBody() {
      this.parseQuestion();
    },
    examQuestion() {
      this.parseQuestion();
    }
  }
};
</script>

<style >
.audio-div {
  display: flex;
  align-items: center;
}
/* .question-body audio {
  width: 180px;
} */
.question-body audio::-webkit-media-controls-timeline,
.question-body audio::-webkit-media-controls-timeline-container {
  display: none;
}
</style>
