// app.js
import {
  userLogin,
  getMyInfo
} from '~/api/user'
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  store
} from '~/store/index'
let storeBindings
App({
  onLaunch() {
    this.checkIsIos()
    this.getNavbarInfo()

  },
  async onShow(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      actions: ['setUser']
    })
    let shareUid = options.query.uid || ''
    let uid = wx.getStorageSync('uid')
    if (uid) {
      let userInfo = await getMyInfo()
      this.setUser(userInfo.user)
      if (getApp().callBack) {
        getApp().callBack();
      }
    } else {
      this.login(shareUid)
    }
  },
  login(shareUid) {
    wx.login({
      success: async (res) => {
        if (res.code) {
          // 获取openid
          let data = {
            code: res.code,
            shareUid
          }
          let userRes = await userLogin(data)
          this.setUser(userRes.data)
          wx.setStorageSync('uid', userRes.data.uid)
          wx.setStorageSync('user', userRes.data)
          this.globalData.userInfo = userRes.data
          if (getApp().callBack) {
            getApp().callBack(userRes);
          }
        }
      }
    })
  },
  checkIsIos: function () {
    wx.getSystemInfo({
      success: (res) => {
        if (res.system.search('iOS') != -1) {
          this.globalData.isIOS = true
        }
        let {
          scene
        } = wx.getLaunchOptionsSync()
        // 1023	安卓系统桌面图标,1104微信聊天主界面下拉,「我的小程序」栏(基础库2.2.4-2.29.0版本废弃,2.29.1版本起生效) 
        this.globalData.desktopTips = this.globalData.isIOS ? scene != 1104 : scene != 1023
      }
    })
  },
  getNavbarInfo() {
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    // 胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    // 导航栏高度 = 状态栏高度 + 44
    this.globalData.navBarHeight = systemInfo.statusBarHeight + 44;
    this.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
    this.globalData.menuTop = menuButtonInfo.top;
    this.globalData.menuHeight = menuButtonInfo.height;
  },
  globalData: {
    userInfo: null,
    isIOS: false, // 判断设备是否为苹果
    desktopTips: false,
    navBarHeight: 0, // 导航栏高度
    menuRight: 0, // 胶囊距右方间距(方保持左、右间距一致)
    menuTop: 0, // 胶囊距底部间距(保持底部间距一致)
    menuHeight: 0, // 胶囊高度(自定义内容可与胶囊高度保证一致)
  }
})