/**
 *  axios 工具函数层
 */
import axios from "axios";
import { responseErr, loginErr } from "@/config";
import { message } from "@/utils/resetMessage";
// import local from "@/utils/local";
import store from "@/store";
// import router from "@/router";
// 请求超时时间
axios.defaults.timeout = 60 * 1000;

// 设置统一服务器地址
axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL;
// 请求拦截
axios.interceptors.request.use(
  (config) => {
    let token = store.getters.token;
    if (token) {
      config.headers.Authorization = token;
      config.headers.Authtoken = token;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// 响应拦截
axios.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 (loginErr.includes(code)) {
        message.error({
          message: msg,
        });
        setTimeout(() => {
          // router.push("/login");
          store.commit("SET_token", "");
          location.href = process.env.VUE_APP_API_portal_URL;
        }, 2000);
      }
    }
    return response;
  },
  (error) => {
    if (error && error.response) {
      let msg = responseErr[error.response.status];
      error.message = msg || `连接错误${error.response.status}`;
    } else {
      if (JSON.stringify(error).includes("timeout")) {
        error.message = "服务器响应超时，请刷新当前页";
      } else {
        error.message = "连接服务器失败";
      }
    }
    message.error({
      message: error.message,
    });

    return Promise.resolve(error.response);
  }
);

export default axios;
