<template>
  <div class="bg-music" :class="{ ['icon-playing']: playing }" @click="handleClick" v-show="show">
    <audio :src="url" ref="audioRef" loop @canplay="show = true" @play="handlePlay"></audio>
  </div>
</template>

<script>
export default {
  name: 'BgMusic',
  data() {
    const { origin, pathname } = window.location

    return {
      show: false,
      playing: false,
      url: `${origin}${pathname}/bg.mp3`
    }
  },
  mounted() {
    document.body.addEventListener("click", this.handleClick);
  },
  methods: {
    handleClick() {
      if (!this.show || !this.$refs.audioRef) return;

      if (this.playing) {
        this.$refs.audioRef.pause();
      } else {
        this.$refs.audioRef.play();
      }

      this.playing = !this.playing
    },

    handlePlay() {
      document.body.removeEventListener("click", this.handleClick);
    }
  }
}
</script>

<style lang="less" scoped>
.bg-music {
  position: fixed;
  top: 1em;
  right: 1em;
  z-index: 10;

  width: 2em;
  height: 2em;
  background-image: url('~@/assets/indexImg/play.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;

  &.icon-playing {
    background-image: url('~@/assets/indexImg/paused.png');
    animation: musicrotate 3s linear infinite;
  }

  & > audio {
    max-width: 1px;
    max-height: 1px;
  }
}

@keyframes musicrotate {
  100% {
    transform: rotate(360deg);
  }
}
</style>
