import { ComponentClass } from 'react'
import Taro, { Component } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import './index.scss'

type PageOwnProps = {
  className?: string
  voiceUrl: any
  voiceName: any
}


type IProps = PageOwnProps

interface Index {
  props: IProps;
}

class Index extends Component {
  static options = {
    addGlobalClass: true
  }

  state = {
    playing: false,
    audioTime: null,
    playTime: '00:00'
  }

  innerAudioContext

  formatTime(second) {
    const seconds = (Math.floor(second % 60) + '').padStart(2, '0');
    const mins = (Math.floor(second % 3600 / 60) + '').padStart(2, '0')

    return `${mins}:${seconds}`
  }
  componentWillMount() {
    if (process.env.TARO_ENV === 'weapp' && this.props.voiceUrl) {
      this.innerAudioContext = Taro.createInnerAudioContext()
      this.innerAudioContext.autoplay = false
      this.innerAudioContext.src = this.props.voiceUrl
      this.innerAudioContext.onPlay(e => {
        this.setState({
          audioTime: this.formatTime(this.innerAudioContext.duration)
        })
      })
      this.innerAudioContext.onTimeUpdate(e => {
        this.setState({
          playTime: this.formatTime(this.innerAudioContext.currentTime)
        })
        this.setState({
          audioTime: this.formatTime(this.innerAudioContext.duration)
        })
      })
      this.innerAudioContext.onStop(e => {
        this.setState({
          playTime: '00:00'
        })
      })
      this.innerAudioContext.onError((res) => {
        Taro.showToast({
          title: res.errMsg,
          icon: 'none'
        })
      })

    }

  }
  play = () => {
    if (this.state.playing) {
      // 暂停
      this.innerAudioContext.stop()
      this.setState({
        playing: false
      })
    } else {
      // 播放
      this.innerAudioContext.play()
      this.setState({
        playing: true
      })
    }
  }
  render() {

    return (
      <View className={'sd-audio-player ' + (this.props.className || '')}>
        <View className='sd-audio-player-info'>
          <View className='sd-audio-player-name'>
            {this.props.voiceName}
          </View>
          <View className='sd-audio-player-time'>
            <View>{this.state.playTime}</View>
            <View>{this.state.audioTime || ''}</View>
          </View>
        </View>
        <Image
          onClick={this.play}
          className='sd-audio-player-play-icon'
          src={'http://ft-image.oss-cn-beijing.aliyuncs.com/' + (this.state.playing ? '120' : '109') + '.png'} ></Image>
      </View>
    )
  }
}

export default Index as ComponentClass<PageOwnProps>