// pages/auth/index.js
import Wx from '../../utils/Wx.js'
import api from '../../utils/Api.js'
const {
  $Toast
} = require('../../iview/base/index');
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

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

  },

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

  },

  handleWxAuth: function(event) {
    Wx.login().then(res => {
      api.login({
        code: res.code,
        signature: event.detail.signature,
        rawData: event.detail.rawData,
        encryptedData: event.detail.encryptedData,
        iv: event.detail.iv,
        scene: app.options.query && app.options.query.scene ? decodeURIComponent(app.options.query.scene) : ''
      }).then(res => {
        if (!res.code) {
          app.globalData.userInfo = res.user
          wx.setStorageSync('token', res.token)
          $Toast({
            content: '授权登录成功',
            type: 'success'
          });
          setTimeout(()=>{
            wx.navigateBack({
              delta: 1
            })
          }, 1000);
        } else {
          $Toast({
            content: '微信授权失败，请重试',
            type: 'error'
          });
        }
      })
    })
  },

  handlePhoneAuth: function(event) {
    Wx.login().then(res => {
      let encryptedData = event.detail.encryptedData
      let iv = event.detail.iv
      this.decodePhoneData(res.code, encryptedData, iv)
    })
  },

  /**
   * 解密手机号数据
   */
  decodePhoneData: function(code, encryptedData, iv) {
    let that = this
    api.getPhoneNumber({
      code: code,
      encryptedData: encryptedData,
      iv: iv
    }).then(res => {
      if (!res.code) {
        $Toast({
          content: '手机号授权成功',
          type: 'success'
        });
        let userInfo = app.globalData.userInfo
        app.globalData.userInfo = {
          ...userInfo,
          ...res.data
        }
      } else {
        $Toast({
          content: '手机号授权失败',
          type: 'error'
        });
      }
    })
  }
})