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 => {
  if (response.status === 200) {
    if (response.data.StatusCode === 401) {
      ElMessageBox.alert('登录已过期，请重新登录，点击确认将退出系统。', '提示', {
        confirmButtonText: '确认',
        callback: () => {
          window.open(import.meta.env.VITE_HOME_URL + '?access=exit', '_self')
        },
      })
      return Promise.reject(new Error(`请求失败，状态码: ${response.data.StatusCode}`));
    }
    return response.data;
  } else {
    return Promise.reject(new Error(`请求失败，状态码: ${response.status}`));
  }

}, async (error) => {
  if (error.response && 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;