<template>
  <div class="lx-music">
    <img v-if="isPlay" class="pause move" @click="pause" :src="imgMusic.play">
    <img v-else class="play"  @click="play" :src="imgMusic.pause">
    <audio v-bind="$attrs" ref='audio' :src="src"></audio>
  </div>
</template>

<script>
let ua = navigator.userAgent.toLocaleLowerCase(),
  LINGXI = /lingxi/.test(ua),
  WEIXIN = /micromessenger/.test(ua);
  
export default {
  name: 'lxMusic',
  props: {
    src: {
      type: String,
      default: 'https://daoket.gitee.io/ai/res/500miles.mp3'
    },
    imgMusic: {
      type: Object,
      default() {
        return  {
          play: require('./music-play.png'),
          pause: require('./music-pause.png')
        }
      }
    }
  },
  data() {
    return{
       isPlay: true,
    }
  },
  mounted() {
    let self = this
    let audio = self.$refs.audio
    if (audio.autoplay) {
      autoPlay()
    } else {
      self.isPlay = false
    }
    function autoPlay() {
      if (WEIXIN) {
        wxAutoPlay()
      } else if (LINGXI) {
        lxAutoPlay()
      }
    }
    function wxAutoPlay() {
      document.addEventListener("WeixinJSBridgeReady", () => {
        audio.play()
      }, false)
    }
    function lxAutoPlay() {
      try {
        let lx = lx || {}
        lx.playVoice({
          resId: self.bgMusic, //根据type来区分取值, 1.网络文件取值音频文件Url, 2.本地文件Id
          type: '1' // 1.网络文件, 2.本地文件
        });
      } catch (error) {
        console.log(error)
      }
    }
  },
  methods: {
    play() {
      this.isPlay = true
      this.$refs.audio.play()
    },
    pause() {
      this.isPlay = false
      this.$refs.audio.pause()
    },
  },
}
</script>