// 养殖管理小程序
App({
  onLaunch() {
    // 小程序初始化
    console.log('养殖管理小程序初始化');
    
    // 检查登录状态
    this.checkLoginStatus();
    
    // 初始化系统信息
    this.getSystemInfo();
  },
  
  onShow() {
    // 小程序显示
    console.log('养殖管理小程序显示');
  },
  
  onHide() {
    // 小程序隐藏
    console.log('养殖管理小程序隐藏');
  },
  
  onError(msg) {
    // 错误处理
    console.error('小程序发生错误：', msg);
    this.reportError(msg);
  },
  
  globalData: {
    userInfo: null,
    token: null,
    baseUrl: 'https://api.xlxumu.com/app/v1',
    systemInfo: null,
    statusBarHeight: 0,
    navBarHeight: 0
  },
  
  // 获取系统信息
  getSystemInfo() {
    const systemInfo = wx.getSystemInfoSync();
    this.globalData.systemInfo = systemInfo;
    this.globalData.statusBarHeight = systemInfo.statusBarHeight;
    
    // 计算导航栏高度
    const menuButton = wx.getMenuButtonBoundingClientRect();
    this.globalData.navBarHeight = menuButton.height + (menuButton.top - systemInfo.statusBarHeight) * 2;
  },
  
  // 检查登录状态
  checkLoginStatus() {
    try {
      const token = wx.getStorageSync('token');
      const userInfo = wx.getStorageSync('userInfo');
      
      if (token && userInfo) {
        this.globalData.token = token;
        this.globalData.userInfo = userInfo;
        // 验证token有效性
        this.verifyToken(token);
      }
    } catch (e) {
      console.error('检查登录状态失败：', e);
    }
  },
  
  // 验证token
  verifyToken(token) {
    wx.request({
      url: `${this.globalData.baseUrl}/auth/user`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.data.success) {
          this.globalData.userInfo = res.data.data;
          wx.setStorageSync('userInfo', res.data.data);
        } else {
          // token无效，清除本地存储
          this.logout();
        }
      },
      fail: (err) => {
        console.error('验证token失败：', err);
        this.logout();
      }
    });
  },
  
  // 微信登录
  wxLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          if (res.code) {
            // 获取用户信息
            wx.getUserProfile({
              desc: '用于完善用户资料',
              success: (userRes) => {
                // 发送登录请求
                wx.request({
                  url: `${this.globalData.baseUrl}/auth/wechat/login`,
                  method: 'POST',
                  data: {
                    code: res.code,
                    encrypted_data: userRes.encryptedData,
                    iv: userRes.iv
                  },
                  header: {
                    'Content-Type': 'application/json'
                  },
                  success: (loginRes) => {
                    if (loginRes.data.success) {
                      const { token, user } = loginRes.data.data;
                      this.globalData.token = token;
                      this.globalData.userInfo = user;
                      
                      // 保存到本地存储
                      wx.setStorageSync('token', token);
                      wx.setStorageSync('userInfo', user);
                      
                      resolve(loginRes.data.data);
                    } else {
                      reject(loginRes.data.message);
                    }
                  },
                  fail: (err) => {
                    reject(err);
                  }
                });
              },
              fail: (err) => {
                reject('用户拒绝授权');
              }
            });
          } else {
            reject('获取微信登录code失败');
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },
  
  // 登出方法
  logout() {
    this.globalData.userInfo = null;
    this.globalData.token = null;
    wx.removeStorageSync('token');
    wx.removeStorageSync('userInfo');
  },
  
  // 网络请求封装
  request(options) {
    return new Promise((resolve, reject) => {
      const { url, method = 'GET', data = {}, header = {} } = options;
      
      // 添加认证头
      if (this.globalData.token) {
        header['Authorization'] = `Bearer ${this.globalData.token}`;
      }
      
      wx.request({
        url: this.globalData.baseUrl + url,
        method,
        data,
        header: {
          'Content-Type': 'application/json',
          ...header
        },
        success: (res) => {
          if (res.data.success) {
            resolve(res.data);
          } else {
            // 处理token过期
            if (res.data.code === 10002) {
              this.logout();
              wx.navigateTo({
                url: '/pages/auth/login'
              });
            }
            reject(res.data);
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },
  
  // 显示加载提示
  showLoading(title = '加载中...') {
    wx.showLoading({
      title,
      mask: true
    });
  },
  
  // 隐藏加载提示
  hideLoading() {
    wx.hideLoading();
  },
  
  // 显示成功提示
  showSuccess(title) {
    wx.showToast({
      title,
      icon: 'success',
      duration: 2000
    });
  },
  
  // 显示错误提示
  showError(title) {
    wx.showToast({
      title,
      icon: 'error',
      duration: 2000
    });
  },
  
  // 错误上报
  reportError(error) {
    // 上报错误到服务器
    if (this.globalData.token) {
      wx.request({
        url: `${this.globalData.baseUrl}/errors/report`,
        method: 'POST',
        data: {
          error: error.toString(),
          timestamp: Date.now(),
          system_info: this.globalData.systemInfo
        },
        header: {
          'Authorization': `Bearer ${this.globalData.token}`,
          'Content-Type': 'application/json'
        }
      });
    }
  }
});