import { Icon } from 'vant'
import { defineComponent, onUnmounted, reactive, watch } from 'vue'
import styles from './index.module.less'
import { Howl } from 'howler'
import iconAudio from './images/icon-audio.png'
import iconPlay from './images/icon-play.png'
import iconPause from './images/icon-pause.png'
import { eventUnit } from '../../unit'

// 音频播放
export default defineComponent({
  name: 'unit-audio',
  props: {
    src: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const state = reactive({
      audioStatus: 'stopped',
      duration: 0
    })
    // https://github.com/Tonejs/Tone.js/issues/784 部分ios上可能存在问题
    const htick: any = new Howl({
      src: props.src + '?t=' + +new Date(),
      format: ['mp3']
      // sprite: {
      //   blast: [0, 3000],
      //   laser: [4000, 1000],
      //   winner: [6000, 5000]
      // }
    })
    // console.log(htick)

    htick.on('load', (val: any) => {
      console.log(htick.duration())
      state.duration = Math.ceil(htick.duration())
    })

    eventUnit.on('unitAudioStop', () => {
      htick.stop()
      state.audioStatus = 'stopped'
    })

    onUnmounted(() => {
      htick.off('load')
    })
    return () => (
      <div class={styles.unitAudio}>
        <div class={styles.htmlAudio}>
          <div class={styles.htmlTimes}>
            <Icon class={styles.iconAudio} name={iconAudio} />
            <span>{state.duration}"</span>
          </div>

          {/* pause-circle */}
          {/* 'play-circle' : 'pause-circle' */}
          <Icon
            name={state.audioStatus === 'stopped' ? iconPause : iconPlay}
            class={styles.audioStatus}
            onClick={(e: any) => {
              e.stopPropagation()
              if (state.audioStatus === 'stopped') {
                eventUnit.emit('unitAudioStop')
                htick.play()
                state.audioStatus = 'paused'
              } else if (state.audioStatus === 'paused') {
                htick.pause()
                state.audioStatus = 'stopped'
              }
            }}
          />
        </div>
        {/* <audio controls class={styles.nativeAudio} id={state.id}>
          <source src={props.src} type="audio/mpeg" />
          您的浏览器不支持该音频格式。
        </audio> */}
      </div>
    )
  }
})
