import { message } from "ant-design-vue";
import axios, { AxiosError, type AxiosRequestConfig } from "axios";
import { routeToLogin } from "@/router";
import type { MessageType } from "ant-design-vue/lib/message";

const urlPrefix = "/";

const httpClient = axios.create({
  baseURL: urlPrefix,
  timeout: 300000,
});


// 添加请求拦截器
httpClient.interceptors.request.use(function (config: AxiosRequestConfig) {
  // 在发送请求之前做些什么
  const token = localStorage.getItem('token');
  if (token && config.headers) {
    config.headers.Authorization = token;
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

let errorMsgHandler: MessageType | null = null;

// 添加响应拦截器
httpClient.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response;
}, function (error: AxiosError) {
  if (error.response?.status == 404) {
    message.error("请求参数错误！");
  } else if (error.response?.status == 401) {
    routeToLogin();
  } else if (error.response?.status == 403) {
    message.error("账号没有权限！");
  } else if (error) {
    if (errorMsgHandler != null) {
      errorMsgHandler()
    }
    errorMsgHandler = message.error(error.message);
    // routeToLogin();
  }

  return Promise.reject(error);
});

export default httpClient;
