import axios from "axios";
import { message } from "ant-design-vue";
import { getToken } from "./token";

// 创建axios实例

const instance = axios.create({
  baseURL: process.env.VUE_APP_MODE,
  // 设置相应的时间
  timeout: 10000,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  },
});

// 请求拦截器
instance.interceptors.request.use(

  function (config: any) {
    const token:String = getToken();

    // 这里判断localStorage里面是否存在token，如果有则在请求头里面设置
    if (token) {
    config.headers.Authorization = token;
    config.headers['token'] = token;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应式拦截器
instance.interceptors.response.use(
  function (response) {
      if(response.data.state != 1){
        message.error( response.data.data);
      }else{
        return response.data
      }
  },
  function (error) {
    message.error('登录超时');
    localStorage.removeItem('session_id')
    localStorage.removeItem('uid')
    window.location.href = window.location.host
    return Promise.reject(error);
  }
);

export default instance;
