<template>
  <div v-if="questionDetail" class="question-body" :key="examQuestionId">
    <div v-html="questionDetail.text"></div>
    <div v-html="questionDetail.audio"></div>
  </div>
</template>

<script>
export default {
  name: "QuestionBody",
  data() {
    return { questionDetail: null };
  },
  props: {
    questionBody: String,
    examQuestionId: String
  },
  mounted() {
    const audio = document.getElementsByTagName("audio")[0];

    audio &&
      audio.addEventListener("play", () => {
        console.log("开始播放");

        //FIXME: error
        this.$http
          .post("/api/exam_question_playtimes", {
            questionId: this.examQuestionId
            // mediaName: mediaName
          })
          .then(
            function() {
              console.log("保存播放次数成功");
            },
            function() {
              console.log("保存播放次数失败");
            }
          );
      });

    this.parseQuestion();
  },
  methods: {
    async parseQuestion() {
      let question = {};
      if (this.questionBody.includes("question-audio")) {
        const audioArray = this.questionBody.match(
          /<a.*?question-audio.*?\/a>/g
        );
        question.text = this.questionBody.replace(
          /<a.*?question-audio.*?\/a>/g,
          ""
        );
        question.audio = audioArray
          .join("")
          .replace(/<a/g, "<audio controls controlsList='nodownload'")
          .replace(/url=/g, "src=")
          .replace(/a>/g, "audio>");

        this.$http
          .get("/api/exam_question_playtimes", {
            params: {
              questionId: this.examQuestionId
            }
          })
          .then(res => {
            //FIXME: audio playtimes
            console.log(res.data);
          });
      } else {
        question.text = this.questionBody;
        question.audio = "";
      }
      this.questionDetail = question;
    }
  },
  computed: {},
  watch: {
    questionBody() {
      this.parseQuestion();
    }
  }
};
</script>

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