
import config from '@/config.js'; // 引入配置文件
import store from '@/store'

let apiBaseUrl = '';
// console.log(process.env.NODE_ENV)
if (process.env.NODE_ENV === 'development') {//本地开发环境
  const SYSTEM_INFO = uni.getSystemInfoSync();//获取系统信息的同步接口
  apiBaseUrl = SYSTEM_INFO.uniPlatform === 'web' ? config.proxyBaseUrl:config.apiBaseUrl;//读取配置文件的apiBaseUrl变量
} else {//生产/测试环境
  apiBaseUrl = config.apiBaseUrl
}
console.log(process.env.NODE_ENV,apiBaseUrl)
const request = (options) => {
	if(options.url.endsWith('.js')) return;
	
	// console.log("进入requset",options);
  return new Promise((resolve, reject) => {

	// console.log("进入Promise",options);
    let contentType = 'application/json';//默认请求头content-type
    // 根据请求方法和请求数据类型设置请求头content-type  以下方法在安卓里报错
    // if (options.method === 'POST' && options.data instanceof FormData)
    // {
    //   // FormData 请求头content-type
    //   contentType = 'multipart/form-data';

    // } else if (options.method === 'POST' && typeof options.data === 'string')
    // {
    //   // 字符串请求头content-type
    //   contentType = 'application/x-www-form-urlencoded';

    // }
	// console.log("准备请求");
    uni.request({
      url: apiBaseUrl + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'content-type': contentType, 
        ...(options.header || {})
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};
// 请求拦截器
const requestInterceptor = (config) => {
  // 在发送请求之前做些什么
  const token = uni.getStorageSync('token'); // 假设从本地存储获取token
  // 确保 options.header 存在
  if (!config.header) {
    config.header = {};
  }
  if (token) {
    config.header.Authorization = `${token}`; // 添加token请求头
  }
  return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
  // console.log("响应拦截器response",response);
  // 对响应数据做点什么
  switch (response.data.code) {//response.statusCode
    case 200:
      return response.data;
    case 400:
	  return response.data;	
	case 601:
	  return response.data;	
	case 602:
	    return response.data;	
    case 401:
	  store.dispatch('logout',true);
	  uni.redirectTo({
	    url: '/pages/login/index'
	  });	
      throw new Error(response.data.message || '未授权，请重新登录');
    case 403:
      throw new Error(response.data.message || '禁止访问');
    case 404:
      throw new Error(response.data.message || '资源未找到');
    case 500:
	  return response.data;	
      // throw new Error(response.data.message || '服务器内部错误');
    default:
      throw new Error(`未知错误，状态码: ${response.statusCode}`);
  }
};

const requestWithInterceptors = (options) => {
	// console.log("进来了",options);
  const config = requestInterceptor(options);
  // console.log("进来了",config);
  return request(config).then(responseInterceptor);
};
// 封装常用的请求方法
const get = (url, data, header) => {
  return requestWithInterceptors({ url, data, header, method: 'GET' });
};

const post = (url, data, header) => {

  return requestWithInterceptors({ url, data, header, method: 'POST' });
};

const put = (url, data, header) => {
  return requestWithInterceptors({ url, data, header, method: 'PUT' });
};

const del = (url, data, header) => {
  return requestWithInterceptors({ url, data, header, method: 'DELETE' });
};

export default {
  request,
  get,
  post,
  put,
  del
};