<template>
  <div
    v-if="questionDetail"
    :key="examQuestion.questionId"
    class="question-body"
  >
    <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"
    >
      <div style="position: relative;" class="audio-div">
        <QuestionAudio
          key="src"
          :name="name"
          :src="src"
          @play="$event => played(index, $event)"
          @ended="() => audioEnded(name)"
          @click="$event => audioClicked(index, $event)"
        />
        <span v-if="examQuestion.limitedPlayTimes">
          （剩余播放次数：{{ getAudioPlayedTimes(name) }}）
        </span>
        <br />
        <div
          v-if="audioInPlay.has(name)"
          style="position: absolute;top: 0;right: 0;bottom: 0;left: 0;"
        ></div>
      </div>
    </div>
  </div>

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

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

export default {
  name: "QuestionBody",
  components: {
    QuestionAudio,
  },
  props: {
    questionBody: { type: String, default: "" },
    examQuestion: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      questionDetail: null,
      audioPlayTimes: null,
      audioInPlay: new Set(),
    };
  },
  computed: {
    ...mapState(["allAudioPlayTimes"]),
  },
  watch: {
    questionBody() {
      this.parseQuestion();
    },
    examQuestion() {
      this.parseQuestion();
    },
  },
  mounted() {
    // console.log(
    //   "Mounted: " + this.examQuestion.questionId + " : " + this.questionBody
    // );
    this.parseQuestion();
  },
  // beforeDestroy() {
  //   console.log(
  //     "Destroy: " + this.examQuestion.questionId + " : " + this.questionBody
  //   );
  // },
  // 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;
        if (/<a.*?question-audio.*?\/a>/.test(this.questionBody)) {
          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;

      // TODO: web audio get data progress, then construct audio element
      // for (let { src, name } of this.questionDetail.audio) {
      // var xmlhttp = new XMLHttpRequest(),
      //   method = "GET",
      //   url = src;

      // xmlhttp.open(method, url, true);
      // xmlhttp.onprogress = function(e) {
      //   //do something
      //   console.log(e);
      // };
      // xmlhttp.send();
      //   fetch(src, { method: "HEAD", mode: "cors" }).then(res => {
      //     console.log(res);
      //     console.log([...res.headers.keys()]);
      //   });
      // }
    },
    // 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(); // 不会死循环，因为这个是音频播放触发的
    //     });
    //   });
    // },
    audioClicked(index, $event) {
      if ($event.target.paused === false) {
        // 正在播放中，不能暂停
        $event.preventDefault();
      }
    },
    audioEnded(name) {
      const s = new Set([...this.audioInPlay]);
      s.delete(name);
      this.audioInPlay = s;
    },
    played(index, $event) {
      const name = $event.target.attributes.name.value;
      if (!this.examQuestion.limitedPlayTimes) {
        const s = new Set([...this.audioInPlay]);
        s.add(name);
        this.audioInPlay = s;
        // 如果没有设置音频播放次数
        return false;
      }
      const limitedPlayTimes = this.examQuestion.limitedPlayTimes;
      console.log("开始播放");

      // console.log(name);
      const theAudio = this.allAudioPlayTimes.find(a => a.name === name);
      const playedTimes = (theAudio || { times: 0 }).times;
      if (limitedPlayTimes - playedTimes <= 0) {
        console.log("无剩余播放次数");
        $event.target.pause();
        return;
      }
      const s = new Set([...this.audioInPlay]);
      s.add(name);
      this.audioInPlay = s;

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

      // if (theAudio) {
      //   theAudio.times = playedTimes + 1;
      // } else {
      //   this.audioPlayTimes.push({ name: name, times: 1 });
      // }
      if ($event.target.paused === false) {
        // 正在播放中
        this.updateQuestionAudioPlayTimes(name);
      }
    },
    getAudioPlayedTimes(name) {
      return Math.max(
        this.examQuestion.limitedPlayTimes -
          (this.allAudioPlayTimes.find(a => a.name === name) || { times: 0 })
            .times,
        0
      );
    },
  },
};
</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>
