// pages/moments/showlist/showlist.js
const app = getApp()
var innerAudioContext = wx.createInnerAudioContext()
Page({
  data: {
    currentIndex: 0,
    tabList: [],
    curId: '', //当前栏目ID
    tempUserId: '', //当前栏目用户ID
    dataList: [], //当前数据
    speedStep: 5, //快进快退秒数
    waitFlag: false,
    topHeight: app.globalData.CustomBar,
    currentTab: '', //当前选中的栏目
    count: 3,
  },

  onLoad(options) {
    this.setData({
      curId: options.id,
      tempUserId: options.userId,
    })
    this.getTabs()
  },
  getTabs() {
    var _self = this
    wx.showLoading({
      title: '加载中...',
    })
    app.http.get(app.urls.getMainColumn, {
        header: {
          token: app.globalData.token
        },
        data: {
          cardTemplateUseId: _self.data.tempUserId
        }
      })
      .then(res => {
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].configColumnId == _self.data.curId) {
            _self.setData({
              currentTab: res.data[i],
              currentIndex: i
            })
          }
        }
        wx.hideLoading({})
        _self.setData({
          tabList: res.data
        })
        _self.getMainMoment(_self.data.curId)
      })
      .catch(err => {
        wx.hideLoading({})
      })
  },
  //切换标签
  onChange(e) {
    var index = e.detail.index
    var id = this.data.tabList[index].configColumnId
    var _self = this
    _self.setData({
      currentIndex: index,
      currentTab: this.data.tabList[index]
    })
    //重新请求数据
    _self.getMainMoment(id)
  },
  getMainMoment(id) {
    wx.showLoading({
      title: '加载中...',
    })
    var _self = this
    app.http.get(app.urls.getMainMoment.format({
        configColumnId: id
      }), {
        header: {
          token: app.globalData.token
        },
        data: {
          userId: _self.data.tempUserId
        }
      })
      .then(res => {
        wx.hideLoading({})
        _self.buildMainData(res.data)
      })
      .catch(err => {
        wx.hideLoading({})
      })
  },
  buildMainData(datas) {
    var _self = this
    datas.forEach(it => {
      it.list.forEach(iem => {
        switch (iem.dataType) {
          case '2': //图片
            var photoIds = iem.value.split('@')
            if (photoIds.length > 1) {
              //展示方式
              iem.dataMode = photoIds[1]
            } else {
              iem.dataMode = '1'
            }
            var items = photoIds[0].split(',')
            var tempList = []
            items.forEach(item => {
              if (item.length > 0) {
                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 => {
              if (item.length > 0) {
                var ss = item.split('&')
                var totalStr = '00:00'
                if (ss.length > 1) {
                  var dur = ss[1]
                  var tM = parseInt(dur / 60) //分钟
                  var tS = parseInt(dur % 60) //秒
                  var totalMStr = tM > 9 ? tM : '0' + tM
                  var totalSStr = +tS > 9 ? tS : '0' + tS
                  totalStr = totalMStr + ':' + totalSStr
                }
                var tempItem = {
                  id: ss[0], //id
                  path: app.urls.baseImgUrl + ss[0], //地址
                  isPlay: false, //是否播放中
                  duration: 100000, //时长
                  curDuration: 0,
                  curDurationStr: '00:00',
                  totalDurationStr: totalStr
                }
                tempList.push(tempItem)
              }
            })
            iem.valueList = tempList
            break
          case '4': //视频
            var items = iem.value.split(',')
            var tempList = []
            for (var i = 0; i < items.length; i++) {
              if (items[i].length > 0) {
                var ss = items[i].split('&')
                var videoUrl = app.urls.baseImgUrl + ss[0]
                var imgUrl = app.urls.baseImgUrl + ss[1]
                var tempItem = {
                  path: videoUrl,
                  imgPath: imgUrl
                }
                tempList.push(tempItem)
              }
            }
            iem.valueList = tempList
            break
          case '6':
            var items = iem.value.split('-')
            var tempList = []
            items.forEach(item => {
              if (item.length > 0) {
                var latlng = item.split(',')
                var tempItem = {
                  name: '',
                  address: '',
                  latitude: latlng[0],
                  longitude: latlng[1],
                }
                tempList.push(tempItem)
              }
            })
            iem.valueList = tempList
            break
          case '8': //单选
            iem.dictionariesList.forEach(ss => {
              if (iem.value.indexOf(ss.dataId) != -1) {
                iem.selValue = ss.dataName
              }
            })
            break
          case '9': //多选
            iem.dictionariesList.forEach(ss => {
              if (iem.value.indexOf(ss.dataId) != -1) {
                ss.isSel = true
              } else {
                ss.isSel = false
              }
            })
            break
        }
      })
    })
    _self.setData({
      dataList: datas
    })
  },
  //预览图片
  viewImg(e) {
    var imgPaths = []
    var imgs = e.currentTarget.dataset.values
    this.setData({
      isNeedRefresh: false
    })
    imgs.forEach(it => {
      imgPaths.push(it.path)
    })
    wx.previewImage({
      urls: imgPaths,
      current: e.currentTarget.dataset.cur
    })
    // 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 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 => {
        if (item.dataType == '3') {
          if (item.valueList) {
            item.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[ix].valueList[a].path + '.mp3'
      innerAudioContext.autoplay = true
    } else {
      innerAudioContext.stop()
    }
    innerAudioContext.onPlay(() => {
      console.log('onPlay')
      _self.data.dataList[index].list[ix].valueList[a]['isPlay'] = true
      _self.setData({
        dataList: _self.data.dataList
      })
    });

    innerAudioContext.onCanplay((res) => {})
    innerAudioContext.onStop((res) => {
      _self.data.dataList[index].list[ix].valueList[a].isPlay = false
      _self.data.dataList[index].list[ix].valueList[a].curDuration = 0
      _self.data.dataList[index].list[ix].valueList[a].curDurationStr = '00:00'
      _self.setData({
        dataList: _self.data.dataList,
      })
      innerAudioContext.destroy()
    })
    innerAudioContext.onEnded((res) => {
      _self.data.dataList[index].list[ix].valueList[a].isPlay = false
      _self.data.dataList[index].list[ix].valueList[a].curDuration = 0
      _self.data.dataList[index].list[ix].valueList[a].curDurationStr = '00:00'
      _self.setData({
        dataList: _self.data.dataList,
      })
      innerAudioContext.destroy()
    })
    innerAudioContext.onError((res) => {
      _self.data.dataList[index].list[ix].valueList[a].isPlay = false
      _self.data.dataList[index].list[ix].valueList[a].curDuration = 0
      _self.data.dataList[index].list[ix].valueList[a].curDurationStr = '00:00'
      _self.setData({
        dataList: _self.data.dataList,
      })
      innerAudioContext.destroy()
    })
    innerAudioContext.onSeeking(() => {})
    innerAudioContext.onWaiting(() => {})
    innerAudioContext.onTimeUpdate(() => {
      if (innerAudioContext.duration != Infinity) {
        _self.data.dataList[index].list[ix].valueList[a].curDuration = parseInt(innerAudioContext.currentTime)
        _self.data.dataList[index].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[ix].valueList[a].curDurationStr = curMStr + ':' + curSStr
        _self.data.dataList[index].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 a = e.currentTarget.dataset.a
    var ix = e.currentTarget.dataset.i
    if (item.isPlay) {
      _self.data.dataList[index].list[ix].valueList[a].curDuration = _self.data.dataList[index].list[ix].valueList[a].curDuration - _self.data.speedStep
      innerAudioContext.seek(_self.data.dataList[index].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 a = e.currentTarget.dataset.a
    var ix = e.currentTarget.dataset.i
    if (item.isPlay) {
      _self.data.dataList[index].list[ix].valueList[a].curDuration = _self.data.dataList[index].list[ix].valueList[a].curDuration + _self.data.speedStep
      innerAudioContext.seek(_self.data.dataList[index].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)
    }
  },
  onUnload(res) {
    if (innerAudioContext) {
      innerAudioContext.stop()
    }
  },
  showDetail(e) {
    if (this.data.currentTab.configColumnType.indexOf('dda5007c-5fb7-48f2-8537-3cb8ea298242') != -1) {
      //需要跳详情
      var cId = this.data.currentTab.configColumnId
      var uId = e.currentTarget.dataset.uid
      wx.navigateTo({
        url: '/packagecard/moments/momentsdetail/momentsdetail?uId=' + uId + '&cId=' + cId,
      })
    }
  }
})