/**
 *  axios 工具函数层
 */
import axios from "axios";
import { message } from "@/utils/resetMessage";
// import local from "@/utils/local";

const instance = axios.create({
  // 请求超时时间
  timeout: 20 * 1000,
});

// 设置统一服务器地址
// axios.defaults.baseURL = local.getLocal("serverUrl");
// 请求拦截
instance.interceptors.request.use(
  (config) => {
    // let token = local.getLocal('token')
    // if (token) {
    //     config.headers.Authorization = token
    // }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// 响应拦截
instance.interceptors.response.use(
  (response) => {
    if (response.data.code !== undefined && response.data.msg !== undefined) {
      // 取出数据
      let { code, msg } = response.data;
      if (code === -1) {
        message.error({
          message: msg,
        });
      } else if (code === 401) {
        message.error({
          message: msg,
        });
      }
    }
    return response;
  },
  (error) => {
    let path = window.location.hash;
    if (
      error.response &&
      error.response.status &&
      error.response.status != 200 &&
      path == "#/"
    ) {
      setTimeout(() => {
        // 重新发送请求
        return instance(error.config);
      }, 5000);
    } else if (error.request && path == "#/") {
      setTimeout(() => {
        // 重新发送请求
        return instance(error.config);
      }, 5000);
    }
    if (error.message.includes("timeout")) {
      message.error({
        message: "网络不给力呀",
      });
    }
    return Promise.reject(error);
  }
);

export default instance;
