//app.js
App({
  onLaunch: function () {
    var that = this;
    console.log("onlaunch---", "onlaunch");
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    wx.login({
      success: function (res) {
        if (res.code) {
          that.getTokenByCode(res.code, true)
        }
      }
    })
  },

  onShow: function (res) {
    console.log("onShow----", res);
    var that = this;
    that.globalData.onshow_count++;
    if (that.globalData.onshow_count > 1) {//除第一次进入小程序之外的打开时
      wx.login({
        success: function (res) {
          if (res.code) {
            that.getTokenByCode(res.code, false)
          }
        }
      })
    }
  },

  getTokenByCode: function (code, relaunch) {
    var that = this;
    var baseUrl = that.globalData.baseUrl;
    wx.request({
      url: baseUrl + 'uaa/v1/auth/tokens',
      data: {
        "grant_type": "wx_app_code",
        "code": code,
        "scope": "global_access:end_user,tenant:wxe91c67adba6ac02d"
      },
      method: "POST",
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log("getTokenByCode", res.data)
        var user = res.data.user;
        var tenant = res.data.tenant;
        that.globalData.tenant_id = tenant.id;
        that.globalData.userInfo = res.data.user;
        that.globalData.wx_open_id = user.wx_open_id;
        that.globalData.Authorization = "Bearer " + res.data.access_token;
        that.globalData.refresh_token = res.data.refresh_token;
        if (user && user.type == "0") {//匿名用户
          wx.redirectTo({
            url: '../../getPhone/getPhone'
          })
        } else if (user && user.type == "1") {//注册用户
          if (relaunch) {
            wx.reLaunch({ //重新加载
              url: '../main/home/home'
              // url: '../../getPhone/getPhone'
            })
          }
        }
      },
      fail: function (res) {
        console.log("login-res-fail", res);
      },
    })
  },
  getUserInfo: function (cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.getUserInfo({
        withCredentials: false,
        success: function (res) {
          console.log("userInfo---", res)
          that.globalData.userInfo = res.userInfo
          typeof cb == "function" && cb(that.globalData.userInfo)
        }
      })
    }
  },

  globalData: {
    onshow_count: 0,
    baseUrl: "http://47.96.75.229:20000/",
    // baseUrl: "https://api.workai.com.cn/",
    OSSUrl: "https://oss.workai.com.cn/",
    userInfo: null,
    hasLogin: false,
    openid: null,
    Authorization: null,
    refresh_token: "",
    tenant_id: "",
    wx_open_id: "",
    newComerOrder: null
  }
})