//app.js
import { default as commonApi } from "./api/commonApi"
import { default as requestApi } from "./utils/request"
import { default as userApi } from "./api/user"

import { promisifyAll, promisify } from 'miniprogram-api-promise';
const wxp = {}
// promisify all wx's api
promisifyAll(wx, wxp)
App({
  onLaunch: async function () {
    // 展示本地存储能力
    // if(!wx.getStorageSync('token')){
      // const tokenData = await commonApi.getToken();
      // if(tokenData.token){
      //   wx.setStorageSync('token', tokenData.token)
      //   requestApi.HEAD.token = tokenData.token
      // }
    // }
     const self = this
    // 登录
    const auth = await wxp.getSetting()
    if (!auth.authSetting['scope.userInfo']){
      console.log('您还没有授权');
      return
    }
    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
    const info = await wxp.getUserInfo()
    this.globalData.userInfo = info.userInfo
    if (this.userInfoReadyCallback) {
      this.userInfoReadyCallback(res)
    }
    await self.wxLogin(info.userInfo);
  },
  globalData: {
    userInfo: null
  },
  wxLogin:async function(data){
    console.log(data)
    if (!data){
      console.log('你还没有授权')
      return
    }
    let _self = this;
    let res = await wxp.login()
    console.log(res)
    if (!res.code){
      return
    }
    data['code'] = res.code
    console.log(data)
    let info =  await userApi.userLogin(data)
    wx.setStorageSync('token', info.userInfo.token)
    requestApi.HEAD.token = info.userInfo.token
    this.setUserInfo(info.userInfo)
    return info.userInfo
  },
  setUserInfo: function(userInfo){
    wx.setStorage({
      data: userInfo,
      key: 'userInfo',
    });
    this.globalData.userInfo = userInfo
  },
  getWxUserInfo: async function(){
    if (!this.globalData.userInfo){
      try {
        let userInfo = wx.getStorageSync({key: 'userInfo'})
        return userInfo.data
      } catch (error) {
        console.log('缓存中没有用户信息')
        return null
      }
    }else {
      return this.globalData.userInfo
    }
  },
})
