//app.js
App({
  url: 'https://www.koala-online.cn/compass/if/',
  onLaunch: function () {
    //调用wx用户登陆
    wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          this.checkUserRegisted(res.code, null);
        }
    })

    var config = wx.getStorageSync('config');
    var that = this;
    //获取用户的经纬度信息
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        // console.log(res);
        var latitude = res.latitude;
        var longitude = res.longitude;
        let jingweidu={
          latitude: res.latitude,
          longitude: res.longitude
        };
        wx.setStorage({
          key: 'jingweidu',
          data: jingweidu,
        })
        wx: wx.request({
          url: that.url + 'ajax_get_user_role.php',
          data: {
            unionId: config.unionId,
            latitude: latitude,
            longitude: longitude
          },
          header: { 'content-type': 'application/json' },
          method: 'GET',
          dataType: 'json',
          success: function (res) {
            console.log(res)
            let location = {
              province: res.data.result.province,
              city: res.data.result.city,
              district: res.data.result.district
            }
            wx.setStorage({
              key: 'location',
              data: location,
            })
          },
          fail: function (res) { },
          complete: function (res) { },
        })
      }
    })
    
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },

  //判断用户是否已经注册
  checkUserRegisted:function(code,openid){
    wx.request({
      url: this.url + 'ajax_check_user_registed.php',
      data: {
        openId: openid,
        code: code
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.status=='OK'){
          //保存返回的openId和unionId
          let config = {
            openId: res.data.result.openId,
            unionId: res.data.result.unionId,
          };
          wx.setStorage({
            key: 'config',
            data: config,
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null
  },
})