// utils/request.js

const BASE_URL = process.env.NODE_ENV === 'production' 
  ? 'https://rw.oytour.com/api/app' 
  : 'https://rw.oytour.com/api/app';

const request = (method, url, data = {}, config = {}) => {
  // 获取用户信息
  let header = {
    'Accept': 'application/json',
    ...config.header
  };
  
  try {
    const userInfoStr = uni.getStorageSync('userInfo');
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr);
      header['Authorization'] = `Bearer ${userInfo.token}`;
    }
  } catch (e) {
    console.error('获取用户信息失败', e);
  }
  
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url,
      method: method.toUpperCase(),
      data,
      header,
      timeout: config.timeout || 60*1000,
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          // 处理错误状态码
          let errorMessage = '请求失败';
          switch (res.statusCode) {
            case 401:
              errorMessage = '未授权，请登录';
              break;
            case 403:
              errorMessage = '拒绝访问';
              break;
            case 404:
              errorMessage = '请求地址不存在';
              break;
            case 500:
              errorMessage = '服务器内部错误';
              break;
            default:
              errorMessage = `请求错误: ${res.statusCode}`;
          }
          
          uni.showToast({
            title: errorMessage,
            icon: 'none',
            duration: 2000
          });
          
          reject(res.data);
        }
      },
      fail: (err) => {
        let errorMessage = '网络错误';
        if (err.errMsg.includes('timeout')) {
          errorMessage = '请求超时';
        }
        
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 2000
        });
        
        reject(err);
      }
    });
  });
};

// 封装常用方法
const http = {
  get(url, params = {}, config = {}) {
    return request('GET', url, params, config);
  },
  post(url, data = {}, config = {}) {
    return request('POST', url, data, config);
  },
  put(url, data = {}, config = {}) {
    return request('PUT', url, data, config);
  },
  delete(url, data = {}, config = {}) {
    return request('DELETE', url, data, config);
  },
  // 文件上传
  upload(url, filePath, name = 'file', formData = {}, config = {}) {
    return new Promise((resolve, reject) => {
      // 获取token
      let header = {};
      try {
        const userInfoStr = uni.getStorageSync('userInfo');
        if (userInfoStr) {
          const userInfo = JSON.parse(userInfoStr);
          header['Authorization'] = `Bearer ${userInfo.token}`;
        }
      } catch (e) {
        console.error('获取用户信息失败', e);
      }
      
      uni.uploadFile({
        url: BASE_URL + url,
        filePath,
        name,
        formData,
        header,
        success: (res) => {
          if (res.statusCode === 200) {
            try {
              const data = JSON.parse(res.data);
              resolve(data);
            } catch (e) {
              resolve(res.data);
            }
          } else {
            reject(res);
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  }
};

export default http;