import axios from "axios";
import { ElMessage } from "element-plus";
// import store from '@/store'

const baseURL = import.meta.env.VUE_APP_BASE_URL;

const service = axios.create({
  baseURL: baseURL, // url = base url + request url
  headers: {
    // "X-Requested-With": "XMLHttpRequest",
    // "Content-Type": "application/json",
  },
  timeout: 5000, // request timeout
});
// 拦截前
// request interceptor 
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
//拦截后
// response interceptor
service.interceptors.response.use(
  (response) => {   
    if(response.data.status==250){
      ElMessage.error(response.data.msg || '请求异常，再重试！')
    }
    return response.data;
  },
  (error) => {
    if (error.response.status === 401) {
      // Token 无效或过期，清除 Token 并跳转到登录页面
      const userStore = useUserStore();
      userStore.clearToken();
      router.push("/login");
    }
    return Promise.reject(error);
  }
);

export default service;
