import axios from "axios";
import { ElMessage } from "element-plus";
// import store from '@/store'
import { useUserStore } from "@/stores/userStore";
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: 1000 * 60 * 5, // request timeout
});
let hasShowExpiredMessage = false
// 拦截前
// 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){
      if(!hasShowExpiredMessage){
        ElMessage.error(response.data.msg || '请求异常，再重试！');
        hasShowExpiredMessage = true;
        const userStore = useUserStore();
        userStore.clearToken();
      window["$router"]?.push("/");
        setTimeout(() => (hasShowExpiredMessage = false), 3000);
      }
    }
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default service;
