<template>
  <span>
    <audio
      v-show="shouldShowAudio"
      :key="src"
      controls
      preload="auto"
      controlsList="nodownload"
      :name="name"
      :src="src"
      style="width: 290px"
      v-on="$listeners"
    ></audio>

    <span v-if="!shouldShowAudio" style="color: blueviolet;">
      音频下载中{{ downloadPercent }}%
    </span>
  </span>
</template>

<script>
export default {
  name: "QuestionAudio",
  props: {
    src: {
      type: String,
      required: true,
    },
    name: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      done: false,
      downloadPercent: 0,
    };
  },
  computed: {
    shouldShowAudio() {
      let chromeVersion = window.navigator.userAgent
        .split(" ")
        .find(v => v.startsWith("Chrome/"));
      if (chromeVersion) {
        chromeVersion = +chromeVersion.replace("Chrome/", "").split(".")[0];
      }
      return (
        chromeVersion < 76 ||
        this.done ||
        !navigator.serviceWorker ||
        !navigator.serviceWorker.controller ||
        // 在某些情况下，caches 没有定义，这时候不做cache. 暂时注释
        // !window.caches ||
        this.downloadPercent === 100
      );
    },
  },
  async created() {
    this.cacheInterval = setInterval(() => {
      if (!this.done && window.caches) {
        window.caches
          .open("audios")
          .then(caches => caches.match(this.src))
          .then(e => e && (this.done = true));
      }
    }, 100);

    this.handleMSG = event => {
      // console.log("Client 1 Received Message: " + event.data);
      if (event.data[0] === this.src)
        this.downloadPercent = Math.floor(
          (event.data[1] / event.data[2]) * 100
        );
    };
    navigator.serviceWorker.addEventListener("message", this.handleMSG);

    let chromeVersion = window.navigator.userAgent
      .split(" ")
      .find(v => v.startsWith("Chrome/"));
    if (chromeVersion) {
      chromeVersion = +chromeVersion.replace("Chrome/", "").split(".")[0];
    }
    if (chromeVersion >= 76) {
      if (!window.caches) {
        window._hmt.push([
          "_trackEvent",
          "音频播放",
          "chromeVersion >= 76 && window.caches 为空",
        ]);
      }
    }
  },
  beforeDestroy() {
    clearInterval(this.cacheInterval);
    navigator.serviceWorker.removeEventListener("message", this.handleMSG);
  },
};
</script>
