import axios from "axios";
import { MessageBox, Message } from "element-ui";
import router from "../router/index";
import store from "../store/index"; // 确保路径正确
const service = axios.create({
  // process.env.NODE_ENV === 'development' 来判断是否开发环境
  // easy-mock服务挂了，暂时不使用了
  // baseURL: '',
  // timeout: 5000
  baseURL: "api", //把原来的项目地址，改成api，解决跨域问题
  timeout: 60000,
});

service.interceptors.request.use((config) => {
  if (localStorage.getItem("token")) {
    // console.log("aaaaaaaaaaaaaa", localStorage.getItem("token"));
    config.headers.Authorization = localStorage.getItem("token");
  }
  return config;
});
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200 && !store.state.responseProcessing) {
      store.commit("setResponseProcessing", true); // 设置状态为处理中

      if (res.code === 401) {
        Message({
          showClose: true,
          message: res.msg,
          type: "error",
          duration: 1500,
        });
        localStorage.removeItem("token");
        router.push("/login");
      } else if (res.code === 400) {
        Message({
          showClose: true,
          message: res.msg,
          type: "error",
          duration: 1500,
        });
      } else if (res.code === 500) {
        Message({
          showClose: true,
          message: res.msg || "Error",
          type: "error",
          duration: 1500,
        });
      }

      store.commit("setResponseProcessing", false); // 重置状态
      return Promise.reject(new Error(res.msg || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    Message({
      message: error.message,
      showClose: true,
      type: "error",
      duration: 1500,
    });
    return Promise.reject(error);
  }
);

export default service;
