// pages/getuserinfo/index.js
const config = require('../../config/config.js')
const Http = require('../../utils/http.js')
const HttpBasics = require('../../utils/HttpBasics.js')
const Common = require('../../common/common.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse("button.open-type.getPhoneNumber"),
    openId: '',
    session_key: '',
    backToLogin: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var openId = wx.getStorageSync("openId");
    var session_key = wx.getStorageSync("session_key");
    if (openId) {
      that.setData({
        openId: openId
      });
    }
    if (options.path == 'login') {
      that.setData({
        backToLogin: true
      });
      console.log(that.data.backToLogin, 'backToLogin');
    }
    if (session_key) {
      that.setData({
        session_key: session_key
      });
    }
    Common.getMallIcon()
      .then(data => {
        this.setData({
          logo: data.data.mallImgUrl ? data.data.mallImgUrl : '../../static/images/logo.png'
        })
      })
  },

  backHome: function () {
    wx.redirectTo({
      url: '/pages/index/index'
    })
  },
  getPhoneNumber(e) {
    console.log(e)
    var that = this;
    var iv = e.detail.iv;
    var encryptedData = e.detail.encryptedData;
    const data = {
      encryptedData: encryptedData,
      iv: iv,
      openId: that.data.openId,
      appId: config.weapp.appId,
      session_key: that.data.session_key,
    }
    HttpBasics.post({
      url: config.api.getUserPhoneForBuser,
      data
    }).then(res => {
      console.log(res)

      if (that.data.backToLogin) {
        wx.showToast({
          title: '授权成功！请重新登录',
          icon: 'none',
          duration: 2000,
        });
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/index/index',
          })
        }, 2000);
        return
      }

      wx.switchTab({
        url: '/pages/main/main'
      })
      wx.showToast({
        title: '授权成功！',
        icon: 'success',
        duration: 2000,
        mask: false
      });
    }).catch(err => {
      console.log(err, 'err');
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 5000
      });
    })
  }
})