const app = getApp()
var CryptoJS = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    preview: '',
    showHide: false,
    isLoading: false,
    isMain: '',
    cardPersonId: '',
    choose_index: 0,
    active: 0,
    cardUrl: app.urls.baseImgUrl,
    areaList: [],
    cardInfo: {},
    bgImg: '',
    fontFamilyList: [],
    useFontFamily: '',
    cardId: '',
    cardHeight: '',
    shareTicket: '',
    encryptedData: '',
    iv: '',
    isFromOut: false,
    token: '',
    oldToken: '',
    fromMine: false,
    imgTempSrc: '',
    currentIndex: 0,
    windowWidth: app.globalData.windowWidth,
    scale: 1
  },
  tabChange(e) {
    this.setData({
      active: e.detail
    })
    if (this.data.active == 0) {
      //首页
      // wx.redirectTo({
      //   url: '/pages/index/index',
      // })
    } else if (this.data.active == 1) {
      //  服务
      if (app.globalData.servicePageType == 1) {
        wx.redirectTo({
          url: '/pages/shop/catalog/bannerlist/bannerlist',
        })
      } else if (app.globalData.servicePageType == 2) {
        wx.redirectTo({
          url: '/pages/shop/catalog/column/column',
        })
      } else if (app.globalData.servicePageType == 3) {
        wx.redirectTo({
          url: '/pages/shop/catalog/list/list',
        })
      } else if (app.globalData.servicePageType == 4) {
        wx.redirectTo({
          url: '/pages/shop/bespeak/bespeak',
        })
      }
    } else {
      //我的
      wx.redirectTo({
        url: '/pages/mine/index/index',
      })
    }
  },
  // 生成我的名片
  createMyCard: function () {
    var self = this
    wx.showLoading({
      title: '生成中...',
      success() {
        self.setData({
          isLoading: true
        })
      }
    })
    var content = {
      pictureTemplateId: self.data.cardId,
      cardTemplateUseAreaList: []
    }
    for (let i = 0; i < self.data.areaList.length; i++) {
      if (self.data.areaList[i].templateAreaType != '1') {
        var info = {
          cardTemplateUseId: "",
          picturesTemplateAreaId: self.data.areaList[i].picturesTemplateAreaId,
          templateAreaFile: self.data.areaList[i].templateAreaFile,
          templateAreaFontValue: self.data.areaList[i].templateAreaFontValue
        }
        content.cardTemplateUseAreaList.push(info)
      }
    }
    app.http.post(app.urls.creatCard, {
      data: content,
      header: {
        token: self.data.token
      }
    }).then(res => {
      if (res.statusCode == '200') {
        wx.hideLoading({
          success: (res) => {
            self.setData({
              isLoading: false,
            })
            wx.showModal({
              content: '恭喜您名片创建成功,如需查看请到(我的 → 我的卡包)',
              cancelText: '继续创建',
              confirmText: '返回列表',
              cancelColor: '#333333',
              confirmColor: '#333333',
              success(res) {
                if (res.confirm) {
                  self.backList()
                } else {
                  self.continueCreate()
                }
              }
            })
          },
        })
      }
    }).catch(res => {
      self.setData({
        isLoading: false,
        showHide: false
      })
    })
  },
  //输入框失去焦点
  inputBlur(e) {
    var _self = this
    // templateAreaFontLength
    var value = e.detail.value
    var index = e.currentTarget.dataset.num
    var item = e.currentTarget.dataset.item
    //计算限制长度
    //最大长度
    var maxLength = item.templateAreaFontLength
    if (value != '' && maxLength > 0) {
      value = value.substr(0, maxLength)
      //重新设置
      _self.data.areaList[index].templateAreaFontValue = value
      _self.data.areaList[index].focus = false
      _self.setData({
        areaList: _self.data.areaList
      })
    }
    //生成二维码图片
    if (item.templateAreaServerLink != '1') {
      _self.getFileId(index)
    }
  },
  // 选择图片
  choosePhoto: function (e) {
    var self = this
    var cur = e.currentTarget.dataset.cur
    var item = e.currentTarget.dataset.item
    console.log(cur)
    self.setData({
      currentIndex: cur
    })
    //宽高比
    var scale = item.templateAreaWidth / item.templateAreaHeight
    wx.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'],
      success: function (res) {
        wx.navigateTo({
          url: '/packagecard/common/corpperimg/cropperimg?imgSrc=' + res.tempFiles[0].path + '&scale=' + scale,
        })
      }
    })
  },
  doUploadImg(path) {
    var _self = this
    wx.showLoading({
      title: '上传中...',
    })
    app.http.upload(app.urls.doUploadImg, {
      path: path,
      name: 'image',
      header: {
        token: app.globalData.token
      }
    }).then(res => {
      wx.hideLoading({})
      res = JSON.parse(res)
      var change = 'areaList[' + _self.data.currentIndex + '].templateAreaFile'
      _self.setData({
        [change]: res.data
      })
      wx.showToast({
        title: '上传成功',
        duration: 1500
      })
      _self.setData({
        imgTempSrc: '',
        currentIndex: 0
      })
    }).catch(res => {
      _self.setData({
        imgTempSrc: '',
        currentIndex: 0
      })
    })
  },
  // 获取名片信息
  getNameCard: function () {
    var self = this;
    var queryInfo = ''
    if (self.data.fromMine) {
      queryInfo = '?cardPersonId=' + self.data.cardPersonId
    }
    app.http.get(app.urls.getCardDetail.format({
        cardTemplateId: self.data.cardId
      }), {
        header: {
          token: app.globalData.token
        },
        data: {}
      }).then(res => {
        var area = res.data.areaList
        var scale = res.data.picturesTemplateWidth / self.data.windowWidth
        res.data.picturesTemplateWidth = res.data.picturesTemplateWidth / scale
        res.data.picturesTemplateHeight = res.data.picturesTemplateHeight / scale
        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'
          }
          area[i].templateAreaFontSize = area[i].templateAreaFontSize / scale + 'px'
          area[i].templateAreaHeight = area[i].templateAreaHeight / scale
          area[i].templateAreaWidth = area[i].templateAreaWidth / scale
          area[i].templateAreaDown = area[i].templateAreaDown / scale
          area[i].templateAreaTop = area[i].templateAreaTop / scale
          area[i].templateAreaRight = area[i].templateAreaRight / scale
          area[i].templateAreaLeft = area[i].templateAreaLeft / scale
        }
        self.setData({
          cardInfo: res.data,
          areaList: area
        })
      })
      .catch(err => {

      })

  },
  // 获取名片内容区域
  getNameCradArea: function () {
    var self = this;
    var arr = []
    app.restAjax.get(app.restAjax.path('{cardUrl}app/cardtemplatearea/listcardtemplateareabytemplateid/' + self.data.cardId, [app.tradeUrl]), {}, {
      headers: {
        token: app.globalData.token
      }
    }, function (code, data) {
      for (let i = 0; i < data.length; i++) {
        data[i]['focus'] = false
        if (data[i].templateAreaType != '1') {
          arr.push(data[i])
        } else {
          var font = parseInt(data[i].templateAreaFontSize.replace('px', ''))
          font = Math.floor(font * 750 / wx.getSystemInfoSync().windowWidth) + 'rpx'
          data[i].templateAreaFontSize = font
          arr.push(data[i])
        }
      }
      self.setData({
        areaList: arr
      })
    }, function (code, data) {
      app.dialog.msg(data.msg);
    });
  },
  // 编辑信息
  editInfo: function (e) {
    var cur = e.currentTarget.dataset.num
    var text = e.detail.value
    var item = 'areaList[' + cur + '].templateAreaFontValue'
    this.setData({
      [item]: text
    })
  },
  // 点击内容区域获取input焦点
  giveFocus: function (e) {
    console.log(e.currentTarget.dataset.cur)
    var cur = e.currentTarget.dataset.cur
    var item = 'areaList[' + cur + '].focus'
    this.setData({
      [item]: true
    })
  },
  // 继续创建
  continueCreate: function () {
    this.setData({
      showHide: false
    })
  },
  // 返回模板列表
  backList: function () {
    wx.navigateBack({
      delta: 1,
    })
  },
  // 获取用户信息
  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
    }, function (code, data) {
      app.dialog.msg(data.msg);
    });
  },
  // 非文字、图片区域换取fileid
  getFileId: function (e) {
    var self = this
    var cur = e
    var content = self.data.areaList[cur].templateAreaFontValue
    console.log(content)
    var areaId = self.data.areaList[cur].picturesTemplateAreaId
    app.http.get(app.urls.getFileId.format({
        picturesTemplateAreaId: areaId
      }), {
        header: {
          token: app.globalData.token
        },
        data: {
          content: content
        }
      }).then(res => {
        console.log(res.data)
        var change = 'areaList[' + cur + '].templateAreaFile'
        self.setData({
          [change]: res.data.data
        })
      })
      .catch(err => {

      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this
    this.setData({
      cardId: options.id,
      token: app.globalData.token,
    })
    this.getNameCard()
  },
  postRecord: function (res) {
    var self = this
    app.restAjax.post(app.restAjax.path('{loginUrl}app/cardtemplateforwardingrecord/savecardtemplateforwardingrecord', [app.tradeUrl]), {
      encryptedData: res.encryptedData,
      iv: res.iv,
      templateUseId: self.data.cardId,
      templateFromUserId: self.data.oldToken,
      templateToUserId: self.data.token
    }, {
      headers: {
        token: self.data.token
      }
    }, function (code, data) {
      console.log('1' + data)
    }, function (code, data) {
      app.dialog.msg(data.msg);
    });
  },
  openPage() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log(this.data.imgTempSrc)
    if (this.data.imgTempSrc != '') {
      this.doUploadImg(this.data.imgTempSrc)
    }
  },

})