const app = getApp()
const innerAudioContext = wx.createInnerAudioContext()
Page({
  data: {
    nameTxt: '名片',
    dataList: [],
    curIndex: 0, //用来记录请求次数
    speedStep: 5, //快进快退秒数
    waitFlag: false,
    avatarUrl: app.globalData.userInfo.avatarUrl,
    areaList: [],
    cardHeight: '',
    cardInfo: {},
    cardUrl: app.urls.baseImgUrl,
    personIntro: {},
    companyIntro: {},
    shareImg: '',
    phoneTxt: '未录入',
    emailTxt: '未录入',
    wechateTxt: '未录入',
    addressTxt: '未录入',
    viewInfo: {},
    forwardCount: '',
    imgUrl: app.urls.baseImgUrl,
    shareRecordId: '',
    isShowBarCode: false,
    browUserList: [],
    shareImgUrl: '',
    tempUserId: '', //当前名片用户的ID
    cardTemplateDispatchId: '', //用来标记是否是分享过来的
    cardTemplateUseId: '', //分享过来的名片id
    isShowCard: false, //用来显示我浏览过的名片
    otherCardList: [], //卡包名片
    isPlayAudio: false, //标识当前是否在播放音乐
    audioId: '',
    uId: '', //海报过来的UserId
    count: 3,
    isMine: 1, //1 自己 2 其他
    isDefault: true,
    animationData: {},
    isShowBtn: false,
    isShowPhone: false,
    isBindPhone: false,
    isNeedRefresh: true,
    isShowComment: false, //是否显示评论弹框
    posterId: '', //分享过来的海报ID
    posterImg: '', //分享过来的海报图片
    isShowPoster: false,
    defaultBtnIcon: '/images/ic_share_img.png',
    shareTitle: '您好,这是我的电子名片,请查看.'
  },
  onLoad(options) {
    var self = this
    self.checkPermission()
    if (options.cardTemplateDispatchId) {
      this.setData({
        cardTemplateDispatchId: options.cardTemplateDispatchId,
        isMine: 2
      })
    }
    if (options.cardTemplateUseId) {
      //展示图片
      self.setData({
        posterId: options.cardTemplateUseId,
        uId: options.userId
      })
    }
    self.buildId()
    self.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]
            var isBind = res.data.data.split('_')[1]
            self.setData({
              isBindPhone: isBind == 0
            })
            wx.setStorageSync('token', token)
            wx.setStorageSync('bindPhone', isBind)
            app.globalData.token = token
            //保存用户名和头像
            self.doSaveUserInfo()
            self.getInfo() //获取用户基本信息
            if (self.data.isMine == 2) {
              if (self.data.cardTemplateDispatchId != '') {
                self.getCardId() //获取分享过来的名片
              }
            } else {
              self.getDefault() //获取自己的名片
            }
            self.getOtherCard(2)
            self.getBtnIcon() //获取首页按钮图片
            if (self.data.posterId != '') {
              self.getPosterImg()
            }
          })
          .catch(err => {
            wx.hideLoading({})
          })
      }
    })
  },
  //获取分享的海报
  getPosterImg() {
    var _self = this
    app.http.get(app.urls.getMyCardDetail.format({
        cardTemplateUseId: _self.data.posterId
      }), {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        var img = _self.data.imgUrl + res.data.cardTemplateUsePhotoUrl
        console.log(img)
        _self.setData({
          posterImg: img,
          isShowPoster: true
        })
      })
      .catch(err => {

      })
  },
  //首页按钮图片
  getBtnIcon() {
    var _self = this
    app.http.get(app.urls.getIndexIcon, {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        if (res.data.data) {
          _self.setData({
            defaultBtnIcon: _self.data.imgUrl + res.data.data
          })
        }
      })
      .catch(err => {
        // console.error(err)
      })
  },
  //保存用户头像及微信昵称
  doSaveUserInfo() {
    try {
      var names = wx.getStorageSync('name')
      var icon = wx.getStorageSync('userIcon')
      var _self = this
      if (names) {
        app.http.put(app.urls.doSaveUserInfo, {
            header: {
              token: app.globalData.token
            },
            data: {
              avatarUrl: icon,
              nickName: names
            }
          })
          .then(res => {})
          .catch(err => {
            console.log(err)
          })
      }
    } catch (err) {
      console.log(err)
    }
  },
  //获取首页展示的栏目
  getMainColumn(id) {
    var _self = this
    _self.setData({
      dataList: []
    })
    app.http.get(app.urls.getMainColumn, {
        header: {
          token: app.globalData.token
        },
        data: {
          creator: id
        }
      })
      .then(res => {
        wx.showLoading({
          title: '加载中...',
        })
        _self.getMainMoment(res.data, id, 0)
      })
      .catch(err => {
        wx.stopPullDownRefresh({})
      })
  },
  //获取首页基础数据 电话 微信号 地址 邮箱
  getMainBaseUserInfo(userid) {
    var _self = this
    app.http.get(app.urls.getMainMoment.format({
        configColumnId: 'de7b5e22-64f9-4c60-a1f9-6ac004dfb9a8'
      }), {
        header: {
          token: app.globalData.token
        },
        data: {
          userId: userid
        }
      })
      .then(res => {
        if (res.data.length > 0) {
          _self.setData({
            isShowBtn: true
          })
          res.data[0].list.forEach(it => {
            switch (it.name) {
              case 'phone':
                _self.setData({
                  phoneTxt: it.value
                })
                break
              case 'wechat':
                _self.setData({
                  wechateTxt: it.value
                })
                break
              case 'email':
                _self.setData({
                  emailTxt: it.value
                })
                break
              case 'address':
                _self.setData({
                  addressTxt: it.value
                })
                break
              case 'cardtitle':
                wx.setStorageSync('cardtitle', it.value)
                _self.setData({
                  shareTitle: it.value.length > 0 ? it.value : '您好,这是我的电子名片,请查看.'
                })
                break
              case 'postertitle':
                wx.setStorageSync('postertitle', it.value)
                break
            }
          })
        } else {
          _self.setData({
            isShowBtn: false
          })
        }
      })
      .catch(err => {
        console.log(err)
      })
  },
  onClose() {
    this.setData({
      isShowPoster: false
    })
  },
  //获取首页栏目数据
  getMainMoment(datas, userid, 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: userid
          }
        })
        .then(res => {
          if (res.data.length > 0) {
            // collectSwitch: datas[_self.data.curIndex].configColumnCollect, //收藏开关
            // commentSwitch: datas[_self.data.curIndex].configColumnComment, //评论开关
            // shareSwitch: datas[_self.data.curIndex].configColumnDispatch, //转发开关
            // likeSwitch: datas[_self.data.curIndex].configColumnLike, //点赞开关
            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, userid, _self.data.curIndex)

        })
        .catch(err => {
          _self.setData({
            curIndex: ++_self.data.curIndex
          })
          if (datas[_self.data.curIndex]) {
            _self.getMainMoment(datas, userid, _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 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 != '') {
                  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 != '') {
                  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] != '') {
                  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 != '') {
                  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
    })
  },
  //显示更多栏目数据
  showMore(e) {
    this.setData({
      isNeedRefresh: false
    })
    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: '/packagecard/moments/showlist/showlist?id=' + item.cId + '&userId=' + userid + '&index=' + idx,
      })
    }
  },
  onPullDownRefresh() {
    if (app.globalData.token != '') {
      this.setData({
        isNeedRefresh: true,
      })
      if (this.data.isMine == 2) {
        if (this.data.cardTemplateUseId != '') {
          this.setData({
            dataList: [],
            cardInfo: null,
            areaList: null
          })
          this.getCard()
        }
      } else {
        this.getDefault()
      }
      this.getOtherCard(2)
      this.getBtnIcon()
    } else {
      this.doLogin()
    }
  },
  //预览图片
  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
    })
  },
  //预览视频
  viewVideo(e) {
    var url = e.currentTarget.dataset.url
    this.setData({
      isNeedRefresh: false
    })
    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
    console.log(_self.data.isPlayAudio)
    if (_self.data.isPlayAudio) {
      //有播放的
      //先需要停止其他录音文件的播放
      _self.data.dataList.forEach(it => {
        it.list.forEach(item => {
          item.list.forEach(ix => {
            if (ix.dataType == '3') {
              if (ix.valueList) {
                ix.valueList.forEach(ii => {
                  ii.isPlay = false
                  ii.curDuration = 0
                  ii.curDuationStr = '00:00'
                })
              }
            }
          })
        })
      })
      _self.setData({
        dataList: _self.data.dataList
      })
      innerAudioContext.stop()
      if (_self.data.audioId != audio.id) {
        wx.showLoading({
          title: '加载中...',
        })
        setTimeout(function () {
          wx.hideLoading({})
          innerAudioContext.src = _self.data.dataList[index].list[idx].list[ix].valueList[a].path + '.mp3'
          innerAudioContext.startTime = 0
          innerAudioContext.autoplay = true
          _self.data.dataList[index].list[idx].list[ix].valueList[a]['isPlay'] = true
          _self.setData({
            dataList: _self.data.dataList,
            isPlayAudio: true,
            audioId: audio.id
          })
        }, 1500)
      }
    } else {
      //没有播放的
      innerAudioContext.src = _self.data.dataList[index].list[idx].list[ix].valueList[a].path + '.mp3'
      innerAudioContext.startTime = 0
      innerAudioContext.autoplay = true
      innerAudioContext.play()
      _self.data.dataList[index].list[idx].list[ix].valueList[a]['isPlay'] = true
      _self.setData({
        dataList: _self.data.dataList,
        isPlayAudio: true,
        audioId: audio.id
      })
    }
    innerAudioContext.onPlay(() => {

    });

    innerAudioContext.onCanplay((res) => {})
    innerAudioContext.onStop((res) => {
      console.log('onStop===')
      _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,
        isPlayAudio: false
      })
    })
    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,
        isPlayAudio: false
      })
    })
    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,
        isPlayAudio: false
      })
    })
    innerAudioContext.onSeeking(() => {
      // console.log(innerAudioContext.currentTime)
    })
  },

  // 跳转模板列表
  //判断是否绑定手机
  //绑定过
  goList: function () {
    //TODO 测试
    wx.navigateTo({
      url: '/packagecard/cardList/cardList',
    })
  },
  // 获取个人简介
  getPersonIntro: function () {
    var self = this
    app.restAjax.get(app.restAjax.path('{personIntroUrl}app/userexpand/get/' + app.globalData.userInfo.userId, [app.personIntroUrl]), {}, {
      headers: {
        token: app.globalData.token
      }
    }, function (code, data) {
      self.setData({
        personIntro: data
      })
    }, function (code, data) {
      app.dialog.msg(data.msg);
    });
  },
  // 获取用户信息
  getUserInfo: function () {
    var self = this
    app.restAjax.get(app.restAjax.path('{loginUrl}app/user/get-app-user', [app.personIntroUrl]), {}, {
      headers: {
        token: app.globalData.token
      }
    }, function (code, data) {
      app.globalData.userInfo = data
      self.getList()

    }, function (code, data) {
      app.dialog.msg(data.msg);
    });
  },
  //获取
  getInfo() {
    app.http.get(app.urls.getUserBaseInfo, {
        header: {
          token: app.globalData.token
        }
      })
      .then(res => {
        wx.setStorageSync('usercode', res.data.userCode)
        wx.setStorageSync('userId', res.data.userId)
      })
      .catch(err => {
        console.log(err)
      })
  },
  // 获取默认名片
  getDefault: function () {
    var self = this
    app.globalData.showUserId = ''
    self.setData({
      cardInfo: {},
      areaList: []
    })
    app.http.get(app.urls.getDefaultCard.format({
      userId: self.data.uId
    }), {
      header: {
        token: app.globalData.token
      }
    }).then(res => {
      var area = res.data.areaList
      area.forEach(it => {
        if (it.templateAreaSource == 'name') {
          self.setData({
            nameTxt: it.templateAreaFontValue
          })
        }
      })
      self.setData({
        cardInfo: res.data,
        isDefault: res.data.cardTemplateUseSystem == '1',
        areaList: area,
        dataList: []
      })
      if (res.data) {
        self.toSaveLocalImg(res.data.cardTemplateUseDispatchPhoto)
        self.getBrowCardUserList(res.data.cardTemplateUseId)
        self.setData({
          tempUserId: res.data.creator,
          cardTemplateUseId: res.data.cardTemplateUseId
        })
        app.globalData.userId = res.data.creator
        self.getMainColumn(res.data.creator)
        self.getMainBaseUserInfo(res.data.creator)
      }
    }).catch(res => {
      wx.stopPullDownRefresh({})
    })
  },
  //获取浏览当前名片的用户头像列表
  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)
      })
  },
  // 存入通讯录
  addContact: function () {
    var self = this
    wx.addPhoneContact({
      firstName: self.data.nameTxt,
      mobilePhoneNumber: self.data.phoneNum
    })
  },
  // 加入卡包
  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 => {
        console.log(res.data)
        wx.showToast({
          title: '加入卡包成功！',
        })
      })
      .catch(err => {

      })
  },
  // 拨打电话
  makeCall: function () {
    var self = this
    var phone = self.data.phoneTxt
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone,
      })
    }
  },
  // 获取浏览数
  getViewCount: function () {
    var self = this
    app.restAjax.get(app.restAjax.path('{cardUrl}app/templateviewrecord/getByTemplateUseId/' + self.data.cardInfo.cardPersonId, [app.cardUrl]), {}, {
      headers: {
        token: app.globalData.token
      }
    }, function (code, data) {
      self.setData({
        viewInfo: data
      })
    }, function (code, data) {
      if (data.msg) {
        app.dialog.msg(data.msg);
      }
    });
  },
  // 获取转发数
  getForwardCount: function () {
    var self = this
    app.restAjax.get(app.restAjax.path('{cardUrl}app/templateforwardingrecord/count', [app.cardUrl]), {
      templateUseId: self.data.cardInfo.cardPersonId
    }, {
      headers: {
        token: app.globalData.token
      }
    }, function (code, data) {
      self.setData({
        forwardCount: data.data
      })
    }, function (code, data) {
      app.dialog.msg(data.msg);
    });
  },
  // 复制文本
  copyText: function (e) {
    var self = this
    var text = e.currentTarget.dataset.text
    if (text) {
      wx.setClipboardData({
        data: text,
        success: function () {}
      })
    }
  },
  // 获取头像
  checkPermission() {
    var _self = this
    try {
      var names = wx.getStorageSync('name')
      var icon = wx.getStorageSync('userIcon')

      if (names) {
        this.setData({
          name: names,
          userIcon: icon
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '小程序需要您微信头像以及昵称用于展示,请授权.',
          showCancel: false,
          success(res) {
            if (res.confirm) {
              _self.getUserProfile(3)
            }
          }
        })
      }
    } catch (error) {
      wx.showToast({
        title: '获取信息失败',
        icon: 'error'
      })
    }
  },
  //获取手机号进行绑定
  getPhoneNumber(e) {
    var _self = this
    var iv = e.detail.iv
    var encryptedData = e.detail.encryptedData
    console.log(encryptedData)
    if (encryptedData) {
      wx.showLoading({
        title: '绑定中...',
      })
      app.http.put(app.urls.doUpdatePhone, {
          header: {
            token: app.globalData.token
          },
          data: {
            iv: iv,
            encryptedData: encryptedData
          }
        })
        .then(res => {
          wx.hideLoading({})
          //保存绑定状态
          wx.setStorageSync('token', res.data.data)
          wx.setStorageSync('bindPhone', 0)
          _self.setData({
            isBindPhone: true
          })
          app.globalData.token = res.data.data
          wx.showToast({
            title: '绑定成功',
            success(e) {
              wx.navigateTo({
                url: '/packagecard/cardList/cardList',
              })
            }
          })
        })
        .catch(err => {})
    }
  },
  getUserProfile(e) {
    let _self = this
    wx.getUserProfile({
      desc: '获取微信头像以及昵称用于展示',
      success: (res) => {
        wx.setStorage({
          data: res.userInfo.nickName,
          key: 'name',
        })
        wx.setStorage({
          data: res.userInfo.avatarUrl,
          key: 'userIcon',
        })
        _self.setData({
          name: res.userInfo.nickName,
          userIcon: res.userInfo.avatarUrl
        })
        app.globalData.userIcon = res.userInfo.avatarUrl
        app.globalData.userInfo = res.userInfo
        _self.selectComponent('#head').refreshCart()
      },
      fail(err) {
        //判断是否绑定手机号
        wx.showToast({
          title: '获取信息失败',
          icon: 'error',
        })
      }
    })
  },
  // 生成随机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
  },
  // 展示名片码
  showBarCode: function () {
    // TODO 测试
    // wx.navigateTo({
    //   url: '/packagecard/moments/publish/momentpublish',
    // })
    this.setData({
      isNeedRefresh: false
    })
    var _self = this
    wx.navigateTo({
      url: '/packagecard/sharePage/cardcode?cardImg=' + _self.data.cardInfo.cardTemplateUsePhotoUrl + '&id=' + _self.data.cardInfo.cardTemplateUseBarcode,
    })
  },
  // 隐藏名片码
  hideBarCode: function () {
    this.setData({
      isShowBarCode: false
    })
    wx.showTabBar()
  },
  // 转发记录
  shareRecord: function (cardTemplateDispatchId) {
    var self = this
    app.http.post(app.urls.shareRecord, {
      header: {
        token: app.globalData.token
      },
      data: {
        cardTemplateUseId: self.data.cardInfo.cardTemplateUseId,
        cardTemplateDispatchParentId: '',
        cardTemplateDispatchId: cardTemplateDispatchId
      }
    }).then(res => {
      self.setData({
        shareRecordId: res.data.data
      })
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var self = this
    self.setData({
      isNeedRefresh: false
    })
    wx.showShareMenu({
      withShareTicket: true,
      success: function (res) {
        console.log(res)
      }
    })
    var type = res.target.dataset.sharetype
    if (type && type == '2') {
      //转发个人动态

    } else {
      var postId = self.buildId()
      self.shareRecord(postId)
      var param = '/pages/index/index?cardTemplateDispatchId=' + postId;
      return {
        title: self.data.shareTitle,
        path: param,
        imageUrl: self.data.shareImgUrl
      }
    }
  },
  //将分享的Base64图片保存至本地
  toSaveLocalImg(data) {
    var _self = this
    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
    })
  },
  //显示详情
  showDetail(e) {
    this.setData({
      isNeedRefresh: false
    })
    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: '/packagecard/moments/momentsdetail/momentsdetail?uId=' + uId + '&cId=' + cId,
      })
    }
  },

  /**分享过来的数据**/

  // 获取名片id
  getCardId: function () {
    var self = this
    app.http.get(app.urls.getCardUseId.format({
      cardTemplateDispatchId: self.data.cardTemplateDispatchId
    }), {
      header: {
        token: app.globalData.token
      }
    }).then(res => {
      self.setData({
        cardTemplateUseId: res.data.cardTemplateUseDTO.cardTemplateUseId
      })
      self.getCard()
      self.saveCheckRecord()
    })
  },
  // 获取名片
  getCard() {
    var self = this
    app.http.get(app.urls.shareCard.format({
        cardTemplateUseId: self.data.cardTemplateUseId
      }), {
        header: {
          token: app.globalData.token
        }
      }).then(res => {
        app.globalData.showUserId = res.data.creator
        wx.stopPullDownRefresh({})
        var area = res.data.areaList
        area.forEach(it => {
          if (it.templateAreaSource == 'name') {
            self.setData({
              nameTxt: it.templateAreaFontValue
            })
          }
        })
        self.setData({
          cardInfo: res.data,
          areaList: area,
          dataList: []
        })

        if (res.data) {
          self.toSaveLocalImg(res.data.cardTemplateUseDispatchPhoto) //保存分享的图片
          self.getBrowCardUserList(res.data.cardTemplateUseId) //获取浏览数量
          app.globalData.userId = res.data.creator //保存当前名片的用户ID
          self.setData({
            tempUserId: res.data.creator
          })
          self.getMainColumn(res.data.creator) //获取当前用户的栏目
          self.getMainBaseUserInfo(res.data.creator)
        }
      })
      .catch(err => {
        wx.stopPullDownRefresh({})
      })
  },

  // 保存查看记录
  saveCheckRecord: function () {
    var self = this
    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)
    })
  },
  onHide(e) {
    this.setData({
      isShowCard: false,
      isShowPhone: false
    })
    if (innerAudioContext) {
      innerAudioContext.stop()
    }
  },
  //显示浏览历史
  showCardHistory(e) {
    var _self = this
    if (_self.data.otherCardList.length > 0) {
      this.setData({
        isShowCard: true
      })
    } else {
      this.getOtherCard(1)
    }
  },
  // 获取浏览历史
  getOtherCard(type) {
    var self = this
    self.setData({
      otherCardList: []
    })
    app.http.get(app.urls.getBrowseHistoryList, {
        header: {
          token: app.globalData.token
        },
        data: {
          page: 1,
          rows: 7,
          homePage: 1
        }
      }).then(res => {
        var curArr
        if (res.data.rows.length > 0) {
          self.buildOtherCardList(res.data.rows)
        }
        if (type == 1) {
          self.setData({
            isShowCard: true
          })
        }
      })
      .catch(err => {})
  },
  changeCard(e) {
    var item = e.currentTarget.dataset.item
    var type = e.currentTarget.dataset.type
    var _self = this
    if (type == 1) {
      this.setData({
        cardTemplateDispatchId: '',
        cardTemplateUseId: '',
        isShowCard: false,
        isMine: 1,
        isDefault: false,
        uId: ''
      })
      this.getDefault()
    } else if (type == 2) {
      this.setData({
        cardTemplateUseId: '',
        isShowCard: false,
        isMine: 2,
        isDefault: true
      })
      this.getCard()
    } else {
      this.setData({
        cardTemplateUseId: item.cardTemplateUseId,
        isShowCard: false,
        isMine: 2,
        isDefault: true
      })
      this.getCard()
    }
  },
  //重新构建浏览历史数据
  buildOtherCardList(row) {
    var temp
    var _self = this
    row.forEach(it => {
      var list = it.cardTemplateUseDTO.areaList
      temp = {}
      list.forEach(item => {
        if (item.templateAreaSource == 'name') {
          temp['name'] = item.templateAreaFontValue
        } else if (item.templateAreaSource == 'phone') {
          temp['phone'] = item.templateAreaFontValue
        } else if (item.templateAreaSource == 'address') {
          temp['address'] = item.templateAreaFontValue
        } else if (item.templateAreaSource == 'department') {
          temp['department'] = item.templateAreaFontValue
        }
      })
      temp['cardTemplateUseId'] = it.cardTemplateUseId
      _self.data.otherCardList.push(temp)
    })
    _self.setData({
      otherCardList: _self.data.otherCardList
    })
  },
  onShow(e) {
    if (app.globalData.token != '') {
      if (this.data.isMine != 2) {
        if (this.data.isNeedRefresh) {
          wx.startPullDownRefresh({})
        }
      }
    }
    this.setData({
      isNeedRefresh: true
    })
  },
  onCloseDialog() {
    this.setData({
      isShowComment: false
    })
  },
  //显示评论
  showComment(e) {
    this.setData({
      isShowComment: true
    })
  },
  //点赞
  doLike(e) {

  },
  //收藏
  doCollect(e) {

  }
})