const { getUserInfo } = require('./api/common')
const { isMobile } = require('./utils/validate')
const { checkUpdateVersion } = require('./utils/util')

App({
  onLaunch () {
    const that = this
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync()
    // 胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
    // 导航栏高度 = 状态栏到胶囊的间距（胶囊距上距离-状态栏高度） * 2 + 胶囊高度 + 状态栏高度
    that.globalData.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 +
      menuButtonInfo.height + systemInfo.statusBarHeight
    that.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right
    that.globalData.menuBottom = menuButtonInfo.top - systemInfo.statusBarHeight
    that.globalData.menuHeight = menuButtonInfo.height
    that.fetchUserData()
    checkUpdateVersion()
  },
  globalData: {
    wxMiniversion: 'v0.0.0',
    userInfo: {},
    navBarHeight: 0, // 导航栏高度
    menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
    menuBottom: 0, // 胶囊距底部间距（保持底部间距一致）
    menuHeight: 0 // 胶囊高度（自定义内容可与胶囊高度保证一致）
  },
  async fetchUserData () {
    try {
      const { status, data } = await getUserInfo()
      if (status && Object.prototype.toString.call(data) === '[object Object]' && isMobile(data.user_phone)) {
        const temp = {
          ...data
        }
        // 设置默认昵称
        if (!temp.user_nickname) {
          temp.user_nickname = 'bbs' + temp.user_phone.replace(/(\d{7})(.*)/, '$2')
        }
        if (temp.user_address && temp.user_address.indexOf('/') > -1) {
          temp.user_address = temp.user_address.split('/')
        }
        this.globalData.userInfo = temp
      }
    } catch (e) {}
  }
})
