/**
 * 省胜优铺 轻商城 - 微信小程序入口
 * 主色调：#4A7CF7
 * 后端API：https://ssypco.com
 */
const api = require('./utils/api');

App({
  globalData: {
    userInfo: null,
    token: '',
    cartCount: 0,
    // 后端API基地址 - 开发时用局域网IP或localhost，真机调试需改为电脑局域网IP
    baseUrl: 'https://ssypco.com'
  },

  onLaunch() {
    // 从缓存恢复登录状态
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    if (token) {
      this.globalData.token = token;
      this.globalData.userInfo = userInfo;
      // 同步到api工具模块
      api.setToken(token);
    }

    // 获取系统信息
    const sysInfo = wx.getSystemInfoSync();
    this.globalData.systemInfo = sysInfo;
    this.globalData.statusBarHeight = sysInfo.statusBarHeight || 44;
    // 计算导航栏高度（状态栏 + 标题栏）
    const menu = wx.getMenuButtonBoundingClientRect();
    this.globalData.menuHeight = menu.bottom - menu.top + (menu.top - sysInfo.statusBarHeight) * 2;
    this.globalData.navBarHeight = sysInfo.statusBarHeight + this.globalData.menuHeight;
  },

  // 检查登录状态
  checkLogin() {
    return !!this.globalData.token;
  },

  // 跳转登录页（带来源页面）
  requireLogin() {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const url = currentPage ? '/' + currentPage.route : '';
    wx.navigateTo({
      url: '/pages/login/login?redirect=' + encodeURIComponent(url)
    });
    return false;
  }
});
