const util = require("../../../utils/util")

const app = getApp()
Page({
  data: {
    spinShow: false,
    userInfo:{},
  },
  onShow: function () {
    app.getUserInfo( userInfo =>{
      this.setData({userInfo})
    })
  },
  wxLogin( ){
    let that = this
    wx.login({
      success(wxres) {
        if( !wxres.code){
          util.showMsg("登入失败")
        }else{
          that.doLoginByCode( wxres.code )
        }
      }
    })
  },
  getPhoneNumber (e) {
    if( e.detail.errMsg !="getPhoneNumber:ok"){
      util.showMsg("获取手机失败")
      return
    }
    let {iv, encryptedData} = e.detail;
    let that = this
    wx.login({
      success(wxres) {
        that.doGetPhoneNumber( wxres.code, iv, encryptedData )
      }
    })
  },
  doLoginByCode( code ){
    app.formPost( "Auth.WxLoginByCode", {code}).then( (res)=>{
      if( res.code == 200){
        this.setData( {userInfo: res.data})
        app.setUserInfo( res.data )
      }
    })
  },
  doGetPhoneNumber( code, iv, encryptedData ){
    let param = {code, iv, encryptedData }
    app.formPost( "Auth.WxLoginByPhone", param).then( (res)=>{
      if( res.code == 200){
        this.setData( {userInfo: res.data})
        app.setUserInfo( res.data )
      }
    })
  },
  logOut() {
    wx.setStorageSync('userId', '')
    wx.setStorageSync('token', '')
    wx.setStorageSync('@openid', '')
    let userInfo = {}
    this.setData({userInfo})
    app.setUserInfo( userInfo )
    wx.navigateTo({
      url: '/pages/index/index',
    })
  },
  gotoIdentify(){
    wx.navigateTo({
      url: '/pages/user/identify/index',
    })
  }
})