const app = getApp()
var innerAudioContext = wx.createInnerAudioContext()
Page({
  data: {
    nameTxt: '名片',
    dataList: [],
    curIndex: 0, //用来记录请求次数
    speedStep: 5, //快进快退秒数
    waitFlag: false,
  },
  onLoad(options) {
    this.doLogin()
  },
  // 登录
  doLogin() {
    var self = this;
    wx.showLoading({
      title: '加载中...',
    })
    wx.login({
      success(res) {
        app.http.post(app.urls.wxLogin, {
            data: {
              jsCode: res.code
            }
          })
          .then(res => {
            wx.hideLoading({})
            var token = res.data.data.split('_')[0]
            wx.setStorageSync('token', token)
            wx.setStorageSync('bindPhone', res.data.data.split('_')[1])
            app.globalData.token = token
            self.getMainColumn()
          })
          .catch(err => {
            wx.hideLoading({})
          })
      }
    })
  },
  //获取首页展示的栏目
  getMainColumn() {
    var _self = this
    app.http.get(app.urls.getMainColumn, {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        wx.showLoading({
          title: '加载中...',
        })
        _self.getMainMoment(res.data, 0)
      })
      .catch(err => {
        wx.stopPullDownRefresh({})
      })
  },
  getMainMoment(datas, index) {
    var _self = this
    var count = datas.length
    if (index < count) {
      app.http.get(app.urls.getMainMoment.format({
          configColumnId: datas[_self.data.curIndex].configColumnId
        }), {
          header: {
            token: app.globalData.token
          }
        })
        .then(res => {
          if (res.data.length > 0) {
            var tempItem = {
              name: datas[_self.data.curIndex].configColumnName,
              list: res.data
            }
            _self.data.dataList.push(tempItem)
          }
          _self.setData({
            curIndex: ++_self.data.curIndex
          })
          _self.getMainMoment(datas, _self.data.curIndex)
        })
        .catch(err => {
          _self.setData({
            curIndex: ++_self.data.curIndex
          })
          _self.getMainMoment(datas, _self.data.curIndex)
        })
    } else {
      wx.hideLoading({})
      wx.stopPullDownRefresh({})
      _self.buildMainData()
    }
  },
  //构建主页显示数据
  buildMainData() {
    var _self = this
    _self.data.dataList.forEach(it => {
      it.list.forEach(item => {
        item.list.forEach(iem => {
          switch (iem.dataType) {
            case '2': //图片
              var items = iem.value.split(',')
              var tempList = []
              items.forEach(item => {
                var tempItem = {
                  id: item,
                  path: app.urls.baseImgUrl + item,
                }
                tempList.push(tempItem)
              })
              iem.valueList = tempList
              break
            case '3': //音频
              var items = iem.value.split(',')
              var tempList = []
              items.forEach(item => {
                var tempItem = {
                  id: item, //id
                  path: app.urls.baseImgUrl + item, //地址
                  isPlay: false, //是否播放中
                  duration: 100000, //时长
                  curDuration: 0,
                  curDurationStr: '00:00',
                  totalDurationStr: '00:00'
                }
                tempList.push(tempItem)
              })
              iem.valueList = tempList
              break
            case '4': //视频
              var items = iem.value.split(',')
              var tempList = []
              items.forEach(item => {
                var tempItem = {
                  id: item,
                  path: app.urls.baseImgUrl + item,
                  imgPath: '/images/ic_temp.png'
                }
                tempList.push(tempItem)
              })
              iem.valueList = tempList
              break
            case '6':
              var items = iem.value.split('-')
              var tempList = []
              items.forEach(item => {
                var latlng = item.split(',')
                var tempItem = {
                  name: '',
                  address: '',
                  latitude: latlng[0],
                  longitude: latlng[1],
                }
                tempList.push(tempItem)
              })
              iem.valueList = tempList
              break
          }
        })
      })
    })
    _self.setData({
      curIndex: 0,
      dataList: _self.data.dataList
    })
    console.log(_self.data.dataList)
  },
  onPullDownRefresh() {
    this.setData({
      dataList: []
    })
    this.getMainColumn()
  },
  //预览图片
  viewImg(e) {
    wx.previewImage({
      urls: [e.currentTarget.dataset.url],
    })
  },
  //预览视频
  viewVideo(e) {
    var url = e.currentTarget.dataset.url
    wx.previewMedia({
      sources: [{
        url: url,
        type: 'video'
      }],
    })
  },
  play(e) {
    //进行播放
    const _self = this
    const index = e.currentTarget.dataset.index
    const idx = e.currentTarget.dataset.idx
    const ix = e.currentTarget.dataset.i
    const a = e.currentTarget.dataset.a
    var audio = e.currentTarget.dataset.item
    //先需要停止其他录音文件的播放
    _self.data.dataList.forEach(it => {
      it.list.forEach(item => {
        item.list.forEach(ix => {
          if (ix.dataType == '3') {
            if (ix.valueList) {
              ix.valueList.forEach(ii => {
                if (ii.isPlay) {
                  innerAudioContext.stop()
                }
                ii.isPlay = false
                ii.curDuration = 0
                ii.curDuationStr = '00:00'
              })
            }
          }
        })
      })
    })
    if (!audio.isPlay) {
      innerAudioContext = wx.createInnerAudioContext()
      innerAudioContext.src = _self.data.dataList[index].list[idx].list[ix].valueList[a].path + '.mp3'
      innerAudioContext.autoplay = true
      console.log(_self.data.dataList[index].list[idx].list[ix].valueList[a].path)
    } else {
      innerAudioContext.stop()
    }


    innerAudioContext.onPlay(() => {
      console.log('onPlay')
      _self.data.dataList[index].list[idx].list[ix].valueList[a]['isPlay'] = true
      _self.setData({
        dataList: _self.data.dataList
      })
    });

    innerAudioContext.onCanplay((res) => {
      // if (_self.data.waitFlag) {
      //   innerAudioContext.play()
      //   _self.setData({
      //     waitFlag: false
      //   })
      // }
    })
    innerAudioContext.onStop((res) => {
      console.log('停止播放')
      _self.data.dataList[index].list[idx].list[ix].valueList[a].isPlay = false
      _self.data.dataList[index].list[idx].list[ix].valueList[a].curDuration = 0
      _self.data.dataList[index].list[idx].list[ix].valueList[a].curDurationStr = '00:00'
      _self.setData({
        dataList: _self.data.dataList,
      })
      innerAudioContext.destroy()
    })
    innerAudioContext.onEnded((res) => {
      console.log(res)
      console.log('播放完毕')
      _self.data.dataList[index].list[idx].list[ix].valueList[a].isPlay = false
      _self.data.dataList[index].list[idx].list[ix].valueList[a].curDuration = 0
      _self.data.dataList[index].list[idx].list[ix].valueList[a].curDurationStr = '00:00'
      _self.setData({
        dataList: _self.data.dataList,
      })
      innerAudioContext.destroy()
    })
    innerAudioContext.onError((res) => {
      console.log('播放错误')
      console.log(res)
      _self.data.dataList[index].list[idx].list[ix].valueList[a].isPlay = false
      _self.data.dataList[index].list[idx].list[ix].valueList[a].curDuration = 0
      _self.data.dataList[index].list[idx].list[ix].valueList[a].curDurationStr = '00:00'
      _self.setData({
        dataList: _self.data.dataList,
      })
      innerAudioContext.destroy()
    })
    innerAudioContext.onSeeking(() => {
      // console.log(innerAudioContext.currentTime)
    })
    innerAudioContext.onWaiting(() => {
      // console.log('onWaiting')
      // innerAudioContext.pause()
      // _self.setData({
      //   waitFlag: true
      // })
    })
    innerAudioContext.onTimeUpdate(() => {
      if (innerAudioContext.duration != Infinity) {
        _self.data.dataList[index].list[idx].list[ix].valueList[a].curDuration = parseInt(innerAudioContext.currentTime)
        _self.data.dataList[index].list[idx].list[ix].valueList[a].duration = parseInt(innerAudioContext.duration)
        var curM = parseInt(innerAudioContext.currentTime / 60) //分钟
        var curS = parseInt(innerAudioContext.currentTime % 60) //秒
        var tM = parseInt(innerAudioContext.duration / 60) //分钟
        var tS = parseInt(innerAudioContext.duration % 60) //秒
        var curMStr = curM > 9 ? curM : '0' + curM
        var curSStr = curS > 9 ? curS : '0' + curS
        var totalMStr = tM > 9 ? tM : '0' + tM
        var totalSStr = +tS > 9 ? tS : '0' + tS
        _self.data.dataList[index].list[idx].list[ix].valueList[a].curDurationStr = curMStr + ':' + curSStr
        _self.data.dataList[index].list[idx].list[ix].valueList[a].totalDurationStr = totalMStr + ':' + totalSStr
        _self.setData({
          dataList: _self.data.dataList
        })
      }
    })
  },
  //倒退5秒
  rewind(e) {
    var _self = this
    var index = e.currentTarget.dataset.index
    var item = e.currentTarget.dataset.item
    var idx = e.currentTarget.dataset.idx
    var a = e.currentTarget.dataset.a
    var ix = e.currentTarget.dataset.i
    if (item.isPlay) {
      _self.data.dataList[index].list[idx].list[ix].valueList[a].curDuration = _self.data.dataList[index].list[idx].list[ix].valueList[a].curDuration - _self.data.speedStep
      innerAudioContext.seek(_self.data.dataList[index].list[idx].list[ix].valueList[a].curDuration)
      _self.setData({
        dataList: _self.data.dataList
      })
    }

  },
  //快进5秒
  speed(e) {
    var _self = this
    var index = e.currentTarget.dataset.index
    var item = e.currentTarget.dataset.item
    var idx = e.currentTarget.dataset.idx
    var a = e.currentTarget.dataset.a
    var ix = e.currentTarget.dataset.i
    if (item.isPlay) {
      _self.data.dataList[index].list[idx].list[ix].valueList[a].curDuration = _self.data.dataList[index].list[idx].list[ix].valueList[a].curDuration + _self.data.speedStep
      innerAudioContext.seek(_self.data.dataList[index].list[idx].list[ix].valueList[a].curDuration)
      _self.setData({
        dataList: _self.data.dataList
      })
    }
  },
  slider4change(e) {
    var index = e.currentTarget.dataset.index
    var item = e.currentTarget.dataset.item
    if (item.isPlay) {
      innerAudioContext.seek(e.detail.value)
    }
  },
  testPlay() {
    innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.src = 'http://192.168.0.115:8091/systemcard/route/file/download/true/aae9bede-3499-4b63-8ee3-75a5ae390335'
    innerAudioContext.autoplay = true
  }
})