const app = getApp()
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: '',
    imgTempSrc: '',
    currentIndex: 0,
    windowWidth: app.globalData.windowWidth
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this
    this.setData({
      cardId: options.id,
      token: app.globalData.token
    })
    this.getPosterDetail()
  },
  onShow(e) {
    if (this.data.imgTempSrc != '') {
      this.doUploadImg(this.data.imgTempSrc)
    }
  },
  // 删除海报
  deleteCard() {
    var self = this
    wx.showModal({
      cancelColor: '#000',
      title: '提示',
      content: '确定要删除该海报吗?',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...',
          })
          app.http.delete(app.urls.deleteCard.format({
            ids: self.data.cardId
          }), {
            header: {
              token: self.data.token
            }
          }).then(res => {
            wx.hideLoading({})
            if (res.statusCode == '200') {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                success() {
                  setTimeout(() => {
                    let arr = getCurrentPages()
                    let lastPage = (arr.length >= 2) ? arr[arr.length - 2] : undefined
                    var isDel = self.data.cardInfo.cardTemplateUseDefault == '1'
                    lastPage.setData({
                      isRefresh: true,
                      isDelPage: isDel
                    })
                    wx.navigateBack({})
                  }, 500);
                }
              })
            }
          }).catch(res => {

          })
        }
      }
    })

  },
  // 更新海报
  updateCard(e) {
    wx.showLoading({
      title: '修改中...',
    })
    var self = this
    var area = []
    for (let i = 0; i < self.data.areaList.length; i++) {
      var info = {
        cardTemplateUseId: self.data.areaList[i].cardTemplateUseId,
        cardTemplateUseAreaId: self.data.areaList[i].cardTemplateUseAreaId,
        templateAreaFile: self.data.areaList[i].templateAreaFile,
        templateAreaFontValue: self.data.areaList[i].templateAreaFontValue
      }
      area.push(info)
    }

    var postInfo = {
      cardTemplateUseAreaList: area,
      cardTemplateUseDefault: self.data.cardInfo.cardTemplateUseDefault,
      cardTemplateUsePassword: self.data.cardInfo.cardTemplateUsePassword,
      cardTemplateUseSwitch: self.data.cardInfo.cardTemplateUseSwitch,
      cardTemplateUseId: self.data.cardInfo.cardTemplateUseId
    }
    app.http.put(app.urls.updateMyCard.format({
        cardTemplateUseId: self.data.cardId
      }), {
        header: {
          token: app.globalData.token
        },
        data: postInfo
      }).then(res => {
        wx.hideLoading({})
        if (res.statusCode == '200') {
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            success() {
              setTimeout(() => {
                let arr = getCurrentPages()
                let lastPage = (arr.length >= 2) ? arr[arr.length - 2] : undefined
                lastPage.setData({
                  isRefresh: true
                })
                wx.navigateBack({})
              }, 500)
            }
          })
        }
      })
      .catch(err => {

      })
  },

  //输入框失去焦点
  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
    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
      })
    })
  },
  // 获取海报信息
  getPosterDetail() {
    var self = this;
    app.http.get(app.urls.getMyCardDetail.format({
        cardTemplateUseId: self.data.cardId
      }), {
        header: {
          token: app.globalData.token
        },
        data: {}
      }).then(res => {
        var area = res.data.areaList
        var scale = res.data.cardTemplateUseWidth / self.data.windowWidth
        res.data.cardTemplateUseWidth = res.data.cardTemplateUseWidth / scale
        res.data.cardTemplateUseHeight = res.data.cardTemplateUseHeight / scale
        for (let i = 0; i < area.length; i++) {
          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
          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'
          }
        }
        self.setData({
          cardInfo: res.data,
          areaList: area
        })
      })
      .catch(err => {

      })
  },
  // 编辑信息
  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(e) {
    var cur = e.currentTarget.dataset.cur
    var item = 'areaList[' + cur + '].focus'
    this.setData({
      [item]: true
    })
  },
  // 非文字、图片区域换取fileid
  getFileId(index) {
    var self = this
    var cur = index
    var content = self.data.areaList[cur].templateAreaFontValue
    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 => {

      })
  },

})