// 网络请求封装
const BASE_URL = 'http://localhost:8080'; // 开发环境

// 请求拦截器
function request(options) {
  return new Promise((resolve, reject) => {
    // 获取 token
    const token = wx.getStorageSync('token');
    
    wx.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
        ...options.header,
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode === 401) {
          // 未授权，跳转登录
          wx.navigateTo({ url: '/pages/settings/settings' });
          reject(new Error('未授权'));
        } else {
          reject(new Error(res.data.msg || '请求失败'));
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        reject(err);
      },
    });
  });
}

// 上传文件
function uploadFile(options) {
  return new Promise((resolve, reject) => {
    const token = wx.getStorageSync('token');
    
    wx.uploadFile({
      url: BASE_URL + options.url,
      filePath: options.filePath,
      name: options.name || 'file',
      header: {
        'Authorization': token ? `Bearer ${token}` : '',
      },
      formData: options.formData || {},
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(JSON.parse(res.data));
        } else {
          reject(new Error('上传失败'));
        }
      },
      fail: reject,
    });
  });
}

module.exports = {
  request,
  uploadFile,
  BASE_URL,
};
