import axios from "axios";
import serverConfig from "./config";
import { useUserStore } from "@/store/index";
import { ElMessageBox } from "element-plus";

// 创建axios请求实例
const serviceAxios = axios.create({
  baseURL: serverConfig.baseURL,
  timeout: 10000,
  withCredentials: false,
});

// 创建请求拦截
serviceAxios.interceptors.request.use(
  (config) => {
    config.withCredentials = true;

    // 如果开启 token 认证
    if (serverConfig.useTokenAuthorization) {
      const token = useUserStore().userInfo?.token;
      if (token) {
        config.headers["Authorization"] = token;
        config.headers["satoken"] = token;
      }
    }

    // 设置请求头
    if (!config.headers["content-type"]) {
      config.headers["content-type"] = "application/json";
      if (config.method === "post") {
        config.data = JSON.stringify(config.data);
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 创建响应拦截
serviceAxios.interceptors.response.use(
  (res) => {
    const { data } = res;

    // 处理401未授权情况
    if (data.code === 401) {
      showErrorMessage(data.msg);
      return Promise.reject(data);
    }

    // 处理500token失效情况
    if (data.code === 500) {
      alert(data.msg);
      useUserStore().clearProfile();
      window.location.href = "/login";
      return Promise.reject(data);
    }

    if (![200, 201].includes(data.code)) {
      showErrorMessage(data.msg);
      return Promise.reject(data);
    }

    return data;
  },
  (error) => {
    // 处理网络错误
    const errorMessage =
      error.response?.data?.msg || error.message || "网络请求失败";
    showErrorMessage(errorMessage);
    return Promise.reject(error);
  }
);

// 显示错误消息
const showErrorMessage = (message) => {
  ElMessageBox.alert(message, "提示", {
    type: "error",
    confirmButtonText: "确定",
  });
};

export default serviceAxios;
