import axios from "axios";
import { showMessage } from '@/common/message'
import { ElMessageBox } from 'element-plus';


const baseURL = import.meta.env.MODE === 'development' ? '' : import.meta.env.VITE_API_URL_JKFZJC;

const service = axios.create({
  baseURL: baseURL,
  withCredentials: true, // 必须携带 Cookie
  headers: {
    'Content-Type': 'application/json' // 避免触发复杂预检
  }
});
service.interceptors.request.use(
  async (config) => {

    const tokenStr = sessionStorage.getItem('token');
    const token = tokenStr ? tokenStr : '';
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

//响应拦截器--从服务器响应之后--得到的结果，优先处理
service.interceptors.response.use(
  response => {
    const handle401Error = () => {
      ElMessageBox.alert('登录已过期，请重新登录，点击确认将退出系统。', '提示', {
        confirmButtonText: '确认',
        showClose: false,
        callback: () => {
          window.open(import.meta.env.VITE_HOME_URL + '?access=exit', '_self');
        },
      });
      return Promise.reject(new Error(`请求失败，状态码: 401`));
    };

    if (response.status !== 200) {
      return Promise.reject(new Error(`请求失败，状态码: ${response.status}`));
    }

    if (response.data.StatusCode === 401 || 
        (response.data.Message && response.data.Message.includes('401'))) {
      return handle401Error();
    }

    return response.data;
  },
  async error => {
    if (error.response?.status === 401) {
      ElMessageBox.alert('登录已过期，请重新登录，点击确认将退出系统。', '提示', {
        confirmButtonText: '确认',
        callback: () => {
          window.open(import.meta.env.VITE_HOME_URL + '?access=exit', '_self');
        },
      });
    }
    showMessage('error', error.message || "请求错误");
    return Promise.reject(error);
  }
);



export default service;