<template>
  <message-bubble :isMine="isMine" :message="message">
    <div class="sound-element-wrapper" :title="playStatus === 'playing' ? '单击暂停' : '单击播放'" @click="handleClick">
      <i class="iconfont icon-voice"></i>
      {{ second + '"' }}
    </div>
  </message-bubble>
</template>

<script>
  import MessageBubble from '@/components/message/message-bubble.vue'

  export default {
    name: 'SoundElement',
    props: {
      payload: {
        type: Object,
        required: true
      },
      message: {
        type: Object,
        required: true
      },
      isMine: {
        type: Boolean
      }
    },
    components: {
      MessageBubble
    },
    data() {
      return {
        amr: null,
        audio: null,
        isAMR: false,
        playStatus: 'stopped' // 'playing' | 'paused' | 'stopped'
      }
    },
    computed: {
      url() {
        return this.payload.sourceUrl
      },
      second() {
        return this.payload.duration
      }
    },
    methods: {
      handleClick() {
        console.log(this.payload.sourceUrl)
        if (this.playStatus === 'playing') {
          this.pause()
        } else if (this.playStatus === 'paused') {
          this.resume()
        } else {
          this.play()
        }
      },
      play() {
        this.cleanup()

        // 默认使用 HTML5 audio 播放
        this.audio = new Audio(this.url)
        console.log(this.audio)
        this.audio.addEventListener('error', this.tryPlayAMR)
        this.audio.addEventListener('ended', this.cleanup)
        this.audio.play()
          .then(() => {
            this.playStatus = 'playing'
          })
          .catch(() => {
            // 播放失败 fallback 到 tryPlayAMR
          })
      },
      pause() {
        if (this.isAMR && this.amr) {
          this.amr.pause()
        } else if (this.audio) {
          this.audio.pause()
        }
        this.playStatus = 'paused'
      },
      resume() {
        if (this.isAMR && this.amr) {
          this.amr.play()
        } else if (this.audio) {
          this.audio.play()
        }
        this.playStatus = 'playing'
      },
      tryPlayAMR() {
        this.isAMR = true
        const isIE = /MSIE|Trident|Edge/.test(window.navigator.userAgent)
        if (isIE) {
          this.$store.commit('showMessage', {
            message: '您的浏览器不支持该格式的语音消息播放，请尝试更换浏览器，建议使用：谷歌浏览器',
            type: 'warning'
          })
          return
        }

        if (!window.BenzAMRRecorder) {
          const script = document.createElement('script')
          script.addEventListener('load', this.playAMR)
          script.src = '/BenzAMRRecorder.js'
          document.head.appendChild(script)
          return
        }

        this.playAMR()
      },
      playAMR() {
        if (!this.amr && window.BenzAMRRecorder) {
          this.amr = new window.BenzAMRRecorder()
          this.amr.onEnded(() => {
            this.cleanup()
          })
        }

        if (this.amr.isInit()) {
          this.amr.play()
          this.playStatus = 'playing'
        } else {
          this.amr.initWithUrl(this.url).then(() => {
            this.amr.play()
            this.playStatus = 'playing'
          })
        }
      },
      cleanup() {
        if (this.audio) {
          this.audio.pause()
          this.audio = null
        }
        if (this.amr) {
          this.amr.stop()
        }
        this.playStatus = 'stopped'
      }
    },
    beforeDestroy() {
      this.cleanup()
    }
  }
</script>

<style lang="stylus" scoped>
  .sound-element-wrapper {
    padding: 0px 10px;
    cursor: pointer;
  }
</style>
