// 基础配置
const baseConfig = {
  // baseUrl: 'http://192.168.0.6:8000',
  baseUrl: 'https://jyzp.365jft.com/jfb-recruit',
  timeout: 10000, // 10秒超时
  header: {
    'Content-Type': 'application/json'
  }
}
// 请求拦截器
const requestInterceptor = (options) => {
  // 可以在这里添加公共请求头，如token
  const token = uni.getStorageSync('jy-recruit-token');
  if (token) {
    options.header = {
      ...options.header,
      'Authorization': `Bearer ${token}`
    };
  }
  
  // 添加公共参数
  options.data = {
    ...options.data,
    // 例如添加设备信息、版本号等
    // appVersion: '1.0.0'
  };
  
  return options;
};

// 响应拦截器
const responseInterceptor = (response) => {
  const { data, statusCode } = response;
  
  // 根据后端约定的状态码处理
  if (statusCode === 200) {
    // 假设后端返回格式为 { code, data, message }
    if (data.isSuccess) {
      return data; // 直接返回业务数据
    } else if (data.code === 401) {
      // 未授权，跳转到登录页
      // uni.navigateTo({ url: '/pages/login/login' });
      return Promise.reject(new Error(data.message || '未授权'));
    } else {
      // 其他业务错误
      uni.showToast({
        title: data.message || '请求失败',
        icon: 'none',
        duration: 3000
      });
      return Promise.reject(new Error(data.message || '请求失败'));
    }
  } else {
    // HTTP状态码错误
    uni.showToast({
      title: `网络错误: ${statusCode}`,
      icon: 'none',
      duration: 3000
    });
    return Promise.reject(new Error(`HTTP错误: ${statusCode}`));
  }
};

// 封装request方法
const request = (options = {}) => {
  // 处理URL
  options.url = options.url.startsWith('http') ? options.url : `${baseConfig.baseUrl}${options.url}`;
  
  // 设置默认方法为GET
  options.method = options.method || 'GET';
  
  // 应用请求拦截器
  options = requestInterceptor(options);
  
  // 发起请求
  return new Promise((resolve, reject) => {
    options.success = (response) => {
      try {
        const result = responseInterceptor(response);
        resolve(result);
      } catch (error) {
        reject(error);
      }
    };
    
    options.fail = (error) => {
      uni.showToast({
        title: '网络请求失败',
        icon: 'none',
        duration: 3000
      });
      reject(error);
    };
    
    uni.request(options);
  });
};

// 简化常用请求方法
const http = {
  get(url, data = {}, options = {}) {
    return request({
      url,
      data,
      method: 'GET',
      ...options
    });
  },
  
  post(url, data = {}, options = {}) {
    return request({
      url,
      data,
      method: 'POST',
      ...options
    });
  },
  
  put(url, data = {}, options = {}) {
    return request({
      url,
      data,
      method: 'PUT',
      ...options
    });
  },
  
  delete(url, data = {}, options = {}) {
    return request({
      url,
      data,
      method: 'DELETE',
      ...options
    });
  }
};

export default http;
