// pages/sharePage/sharePage.js
const app = getApp()
var innerAudioContext = wx.createInnerAudioContext()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    curIndex: 0,
    token: '',
    cardTemplateUseId: '',
    cardTemplateDispatchId: '',
    cardInfo: {},
    areaList: [],
    haveCard: false,
    bgImg: '',
    areaList: [],
    cardHeight: '',
    cardInfo: {},
    cardUrl: app.urls.baseImgUrl,
    personIntro: {},
    companyIntro: {},
    shareImg: '',
    phoneTxt: '',
    emailTxt: '',
    wechateTxt: '',
    addressTxt: '',
    viewInfo: {},
    forwardCount: '',
    imgUrl: app.urls.baseImgUrl,
    personId: '',
    shareRecordId: '',
    nameTxt: '名片',
    dataList: [],
    isShowBarCode: false,
    browUserList: [],
    tempUserId: '',
    shareImgUrl: ''
  },
  // 登录
  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])
            self.setData({
              token: token
            })
            app.globalData.token = token
            self.getCardId()
          })
          .catch(err => {
            wx.hideLoading({})
            console.log(err)
          })
      }
    })
  },
  // 保存查看记录
  saveCheckRecord: function () {
    var self = this
    console.log('1123')
    app.http.post(app.urls.checkRecord, {
      header: {
        token: app.globalData.token
      },
      data: {
        cardTemplateUseId: self.data.cardTemplateUseId,
        cardTemplateDispatchId: self.data.cardTemplateDispatchId
      }
    }).then(res => {
      console.log(res)
    }).catch(res => {
      console.log(res)
    })
  },
  // 获取名片
  getCard: function () {
    var self = this
    app.http.get(app.urls.shareCard.format({
      cardTemplateUseId: self.data.cardTemplateUseId
    }), {
      header: {
        token: self.data.token
      },
      data: {}
    }).then(res => {
      console.log(res.data)
      var area = res.data.areaList
      for (let i = 0; i < area.length; i++) {
        if (area[i].templateAreaFontCenter == '1') {
          area[i].templateAreaFontCenter = 'left'
        } else if (area[i].templateAreaFontCenter == '2') {
          area[i].templateAreaFontCenter = 'center'
        } else {
          area[i].templateAreaFontCenter = 'right'
        }
        if (area[i].templateAreaFontBold == '0') {
          area[i].templateAreaFontBold = 'normal'
        } else if (area[i].templateAreaFontBold == '1') {
          area[i].templateAreaFontBold = 'bold'
        } else {
          area[i]['templateAreaFontStyle'] = 'italic'
        }
        if (area[i].templateAreaSource == 'phone') {
          self.setData({
            phoneTxt: area[i].templateAreaFontValue
          })
        } else if (area[i].templateAreaSource == 'wechat') {
          self.setData({
            wechatTxt: area[i].templateAreaFontValue
          })
        } else if (area[i].templateAreaSource == 'email') {
          self.setData({
            emailTxt: area[i].templateAreaFontValue
          })
        } else if (area[i].templateAreaSource == 'address') {
          self.setData({
            addressTxt: area[i].templateAreaFontValue
          })
        } else if (area[i].templateAreaSource == 'name') {
          self.setData({
            nameTxt: area[i].templateAreaFontValue
          })
        }
      }
      self.setData({
        cardInfo: res.data,
        areaList: area,
        dataList: []
      })
      if (res.data) {
        self.toSaveLocalImg(res.data.cardTemplateUseDispatchPhoto)
        self.getBrowCardUserList(res.data.cardTemplateUseId)
        self.setData({
          tempUserId: res.data.creator
        })
        self.getMainColumn(res.data.creator)
      }
    })
  },
  //获取首页展示的栏目
  getMainColumn(id) {
    var _self = this
    app.http.get(app.urls.getMainColumn, {
        header: {
          token: app.globalData.token
        },
        data: {
          cardTemplateUseId: id
        }
      })
      .then(res => {
        wx.showLoading({
          title: '加载中...',
        })
        console.log(res.data)
        _self.getMainMoment(res.data, id, 0)
      })
      .catch(err => {})
  },
  getMainMoment(datas, id, 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
          },
          data: {
            userId: id
          }
        })
        .then(res => {
          if (res.data.length > 0) {
            var tempItem = {
              cId: datas[_self.data.curIndex].configColumnId,
              type: datas[_self.data.curIndex].configColumnType,
              name: datas[_self.data.curIndex].configColumnName,
              mode: datas[_self.data.curIndex].configTableMode,
              list: res.data.slice(0, datas[_self.data.curIndex].configColumnRowCount)
            }
            _self.data.dataList.push(tempItem)
          }
          _self.setData({
            curIndex: ++_self.data.curIndex
          })
          _self.getMainMoment(datas, id, _self.data.curIndex)
        })
        .catch(err => {
          _self.setData({
            curIndex: ++_self.data.curIndex
          })
          _self.getMainMoment(datas, id, _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 = []
              for (var i = 0; i < items.length; i++) {
                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 => {
                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({
      curIndex: 0,
      dataList: _self.data.dataList
    })
  },
  // 加入卡包
  includedCard: function () {
    var self = this
    app.http.post(app.urls.includedCard, {
      header: {
        token: app.globalData.token
      },
      data: {
        cardTemplateUseBagId: "",
        cardTemplateUseId: self.data.cardInfo.cardTemplateUseId,
        cardTemplateUseStar: "",
        cardTemplateUseTag: "",
        cardTemplateUseTop: ""
      }
    }).then(res => {
      if (res.statusCode == '200') {
        wx.showToast({
          title: '加入卡包成功！',
        })
      }
    })
  },
  // 获取名片id
  getCardId: function () {
    var self = this
    app.http.get(app.urls.getCardUseId.format({
      cardTemplateDispatchId: self.data.cardTemplateDispatchId
    }), {
      header: {
        token: self.data.token
      }
    }).then(res => {
      self.setData({
        cardTemplateUseId: res.data.cardTemplateUseDTO.cardTemplateUseId
      })
      self.getCard()
      self.saveCheckRecord()
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      cardTemplateDispatchId: options.cardTemplateDispatchId
    })
    this.doLogin()
  },
  // 拨打电话
  makeCall: function () {
    var self = this
    var phone = self.data.phoneTxt
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone,
      })
    }
  },
  // 复制文本
  copyText: function (e) {
    var self = this
    var text = e.currentTarget.dataset.text
    if (text) {
      wx.setClipboardData({
        data: text,
        success: function () {}
      })
    }
  },
  // 展示名片码
  showBarCode: function () {
    this.setData({
      isShowBarCode: true
    })
  },
  // 隐藏名片码
  hideBarCode: function () {
    this.setData({
      isShowBarCode: false
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var self = this
    wx.showShareMenu({
      withShareTicket: true,
      success: function (res) {
        console.log(res)
      }
    })

    if (res.from == 'button') {
      var postId = self.buildId()
      self.shareRecord(postId)

      var param = '/pages/sharePage/sharePage?cardTemplateDispatchId=' + postId;
      return {
        title: '名片分享',
        path: param,
        imageUrl: self.data.shareImgUrl
      }
      // return返回    title 转发标题    path 路径 imageUrl 自定义图片,可以本地路径  代码包文件路径  支持png jpg 显示长宽比5:4
    }
  },
  //获取浏览当前名片的用户头像列表
  getBrowCardUserList(id) {
    var _self = this
    app.http.get(app.urls.getCardBrowUserList, {
        header: {
          token: app.globalData.token
        },
        data: {
          page: '1',
          rows: '7',
          cardTemplateUseId: id
        }
      })
      .then(res => {
        if (res.data) {
          _self.setData({
            browUserList: res.data.rows
          })
        }
      })
      .catch(err => {
        console.log(err)
      })
  },
  // 转发记录
  shareRecord: function (cardTemplateDispatchId) {
    var self = this
    app.http.post(app.urls.shareRecord, {
      header: {
        token: app.globalData.token
      },
      data: {
        cardTemplateUseId: self.data.cardInfo.cardTemplateUseId,
        cardTemplateDispatchParentId: self.data.cardTemplateDispatchId,
        cardTemplateDispatchId: cardTemplateDispatchId
      }
    }).then(res => {
      console.log(res.data)
      self.setData({
        shareRecordId: res.data.data
      })
    })
  },
  // 生成随机id
  buildId: function () {
    var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    var nums = "";
    for (var i = 0; i < 36; i++) {
      var id = parseInt(Math.random() * 61);
      nums += chars[id];
    }
    return nums
  },
  //预览图片
  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)
    }
  },
  //将分享的Base64图片保存至本地
  toSaveLocalImg(data) {
    var base64 = data
    var imgPath = wx.env.USER_DATA_PATH + '/index' + 'share.png'
    var imageData = base64.replace(/^data:image\/\w+;base64,/, "");
    var fs = wx.getFileSystemManager();
    fs.writeFileSync(imgPath, imageData, "base64");
    this.setData({
      shareImgUrl: imgPath
    })
  },
  goHome() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  //显示详情
  showDetail(e) {
    var type = e.currentTarget.dataset.ctype //需要跳详情
    if (type.indexOf('dda5007c-5fb7-48f2-8537-3cb8ea298242') != -1) {
      //需要跳详情
      var cId = e.currentTarget.dataset.cid
      var uId = e.currentTarget.dataset.id
      wx.navigateTo({
        url: '../moments/momentsdetail/momentsdetail?uId=' + uId + '&cId=' + cId,
      })
    }
  },
  //显示更多栏目数据
  showMore(e) {
    var item = e.currentTarget.dataset.item
    if (item.mode == '2') {
      var userid = e.currentTarget.dataset.userid
      var idx = e.currentTarget.dataset.idx
      wx.navigateTo({
        url: '../../pages/moments/showlist/showlist?id=' + item.cId + '&userId=' + userid + '&index=' + idx
      })
    }
  },
  //tabbar切换
  onChange(e) {
    this.setData({
      active: e.detail
    })
  }
})