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)

// 防止 401 重复处理的标志
let isHandling401 = false;

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 isLoginPage = () => {
  const pages = getCurrentPages();
  if (pages.length === 0) return false;
  const currentPage = pages[pages.length - 1];
  return currentPage.route === 'pages/login/index';
};

const clearUserInfoAndRedirect = () => {
  // 清除用户信息
  uni.removeStorageSync('token');
  uni.removeStorageSync('userInfo');
  uni.removeStorageSync('schoolsList');
  
  // 清除store中的信息
  store.commit('userStore/SET_TOKEN', '');
  store.commit('userStore/SET_USER_INFO', {});
  store.commit('userStore/SET_SCHOOLSLIST', '');
  
  // 跳转到登录页
  if (!isLoginPage()) {
    uni.reLaunch({
      url: '/pages/login/index'
    });
  }
};

const responseInterceptor = (response) => {
  if (response.data.code === 401) {
    // 如果已经在处理 401，直接抛出错误，防止重复调用 sign_out
    if (isHandling401) {
      throw new Error(response.data.message || response.data.msg || '未授权，请重新登录');
    }
    
    isHandling401 = true;
    
    // 清除用户信息并跳转到登录页
    clearUserInfoAndRedirect();
    
    // 延迟重置标志位，避免连续请求都触发401
    setTimeout(() => {
      isHandling401 = false;
    }, 2000);
    
    throw new Error(response.data.message || response.data.msg || '未授权，请重新登录');
  }

  if (response.data.code === 500 || response.data.code === 503) {
    uni.showToast({
      title: response.data.message || response.data.msg || '服务器繁忙，请稍后重试',
      icon: 'none',
      duration: 3000
    });
    throw new Error(response.data.message || response.data.msg || '服务器内部错误');
  }

  if (response.data.code === 200 || response.data.code === 400 || response.data.code === 601 || response.data.code === 602) {
    return response.data;
  }

  if (response.data.code === 403) {
    throw new Error(response.data.message || response.data.msg || '禁止访问');
  }

  if (response.data.code === 404) {
    throw new Error(response.data.message || response.data.msg || '资源未找到');
  }

  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
};