import axios from 'axios';

// 从 localStorage 中获取地址和端口
const rememberedAddress = localStorage.getItem('rememberedAddress') || '127.0.0.1';
const rememberedPort = localStorage.getItem('rememberedPort') || '8000';

// 动态拼接 baseURL
const baseURL = `http://${rememberedAddress}:${rememberedPort}/api/v1`;

// 创建 axios 实例
const axiosInstance = axios.create({
  baseURL: baseURL,  // 使用动态生成的 baseURL
  timeout: 10000,    // 超时时间
  withCredentials: true, // 使用cookie跨域请求
});

// 请求拦截器
axiosInstance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('alertToken');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response && error.response.status === 401) {
      // localStorage.removeItem('alertToken');
      // window.location.href = '/#/login'; 
    }
    return Promise.reject(error);
  }
);

export default axiosInstance;
