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,
    list: [{
        "text": "首页",
        "iconPath": "/images/ic_card_sel.png",
        "selectedIconPath": "/images/ic_card_sel.png",
      },
      {
        "text": "我的",
        "iconPath": "/images/ic_mine_normal.png",
        "selectedIconPath": "/images/ic_mine_sel.png",
      }
    ]
  },
  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.showToast({
      title: '加载中',
      icon: 'loading',
      success: function () {
        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.hideToast({
          success: (res) => {
            self.setData({
              isLoading: false,
              showHide: true
            })
          },
        })
      }
    }).catch(res => {
      self.setData({
        isLoading: false,
        showHide: false
      })
    })
  },
  // 选择图片
  choosePhoto: function (e) {
    var self = this
    var cur = e.currentTarget.dataset.cur
    wx.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'],
      success: function (res) {
        wx.showLoading({
          title: '上传中...',
        })
        app.http.upload(app.urls.doUploadImg, {
          path: res.tempFiles[0].path,
          name: 'image',
          header: {
            token: app.globalData.token
          }
        }).then(res => {
          wx.hideLoading({})
          res = JSON.parse(res)
          console.log(res)
          var change = 'areaList[' + cur + '].templateAreaFile'
          self.setData({
            [change]: res.data
          })
          wx.showToast({
            title: '上传成功',
            duration: 1500
          })
        }).catch(res => {

        })
        // app.restAjax.file(app.restAjax.path('{cardUrl}app/file/uploadimage', [app.tradeUrl]), res.tempFiles[0].path, 'image', {
        //   headers: {
        //     token: app.globalData.token
        //   }
        // }, function (code, data) {
        //   console.log(data)
        //   data = JSON.parse(data)
        //   wx.hideLoading({})
        //   var change = 'areaList[' + cur + '].templateAreaTitle'
        //   self.setData({
        //     [change]: data.data
        //   })
        //   wx.showToast({
        //     title: '上传成功',
        //     duration: 1500
        //   })
        // }, function (code, data) {
        //   app.dialog.msg(data.msg);
        // });
      }
    })
  },
  getPhoneNumber: function (e) {
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)
  },
  // 获取名片信息
  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 => {
      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].templateAreaServerLink == '1') {
          if (area[i].templateAreaFontValue.length > area[i].templateAreaFontLength) {
            area[i].templateAreaFontValue = area[i].templateAreaFontValue.substring(area[i].templateAreaFontLength, -1)
          }
        }
        area[i].templateAreaFontSize = Math.floor(area[i].templateAreaFontSize * 750 / wx.getSystemInfoSync().windowWidth) + 'rpx'
      }
      self.setData({
        cardInfo: res.data,
        areaList: area
      })
    })
    .catch(err => {

    })
    // app.restAjax.get(app.restAjax.path('{cardUrl}app/cardtemplate/getcardtemplatebyid/' + self.data.cardId + queryInfo, [app.cardUrl]), {}, {
    //   headers: {
    //     token: app.globalData.token
    //   }
    // }, function (code, data) {
    //   for (let i = 0; i < self.data.fontFamilyList.length; i++) {
    //     if (data.templateTypeface == self.data.fontFamilyList[i].id) {
    //       self.setData({
    //         useFontFamily: self.data.fontFamilyList[i].name
    //       })
    //     }
    //   }
    //   if (self.data.fromMine) {
    //     self.setData({
    //       areaList: JSON.parse(data.content)
    //     })
    //   }
    //   self.setData({
    //     cardInfo: data
    //   })
    //   var query = wx.createSelectorQuery()
    //   query.select('.card').boundingClientRect()
    //   query.exec(function (res) {
    //     self.setData({
    //       cardHeight: res[0].height
    //     })
    //   })
    // }, function (code, data) {
    //   app.dialog.msg(data.msg);
    // });
  },
  // 获取名片内容区域
  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,
    })
  },
  // 登录
  doLogin: function () {
    var self = this;
    wx.login({
      success(res) {
        app.restAjax.post(app.restAjax.path('{url}wechat/miniapp/sign/default', [app.personIntroUrl]), {
          jsCode: res.code
        }, null, function (code, data) {
          var token = data.data.split('_')[0]
          self.setData({
            token: token,
            bindPhone: data.data.split('_')[1]
          })
          wx.setStorageSync('token', token)
          wx.setStorageSync('bindPhone', data.data.split('_')[1])
          app.globalData.token = token
          self.getUserInfo()
        }, 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
    }, function (code, data) {
      app.dialog.msg(data.msg);
    });
  },
  // 非文字、图片区域换取fileid
  getFileId: function (e) {
    var self = this
    var cur = e.currentTarget.dataset.num
    
    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() {

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})