import $ from './../../utils/Tool';
const app = getApp();
const AUTH = require('../../utils/auth');
import {userSave,getuserPhone} from "../../requests/api";
import router from '../../utils/router';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phonePop:false,
    wxqcode:'',
  },
  getUserInfoFn(res){
    if(res.detail.errMsg==='getUserInfo:ok'){
      $.store.set('userInfo',res.detail.userInfo)
    }
    this.setData({phonePop:true});
  },
  bindGetPhoneNumber(e){
    if (e.detail.errMsg == "getPhoneNumber:ok"){
      let isLogined = AUTH.checkHasLogined();
      if(isLogined){
        var data={};
        data.encryptedData=e.detail.encryptedData;
        data.iv=e.detail.iv;
        data.openid=wx.getStorageSync('openId') || app.globalData.openId;
        getuserPhone(data).then(async result=>{
          if(result.result==="success"){
            $.store.set('phoneNumber',result.phoneNumber);
            await this.creatUser();
            this.goHome();
          }
        })
      }
    }else{
      this.goHome();
    }
  },

  goHome(){
    // let pages = getCurrentPages();
    // let prevPage = pages[ pages.length - 2 ];
    // prevPage.setData({
    //   formAuth:true,
    // })
    router.reLaunch();
  },
  onClose(event){
    if(event.detail==="cancel"){
      this.setData({phonePop:false});
      $.store.set('clickPhone',true)
      this.goHome();
    }
  },
  // 创建用户
  async creatUser(){
    const data={};
    data.phone = $.store.get('phoneNumber');
    data.openId =$.store.get('openId') ||$.storage.get('openId');
    // console.log($.store.get('openId') ,$.storage.get('openId'),"$.storage.get('openId')")
    const {nickName} = $.store.get('userInfo')
    data.nickname=nickName;
    // data.userName=app.globalData.userInfo.nickName;
    console.log(data);
    let res = await userSave(data);
    if(res.result==="success"){
      $.store.set('userId',res.id);
      $.storage.set('userId', res.id);
      // $.store.set('userId',data.openId);
      // $.storage.set('userId', data.openId);
      $.storage.set('logined',true);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onshow(){

  },
})