/**
 *  axios 工具函数层
 */
import axios from "axios";
import router from "@/router";
import store from "@/store";
import { message } from "@/utils/resetMessage";
// 加载条插件
import NProgress from "nprogress";

// 请求超时时间
axios.defaults.timeout = 60 * 1000;

// 设置统一服务器地址
axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL;
// 请求拦截
axios.interceptors.request.use(
  (config) => {
    let token = store.getters["user/token"];
    if (token) {
      config.headers.Authorization = token;
    }
    NProgress.start();
    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({
          content: msg,
          maxCount: 1,
          duration: 1,
        });
        if (msg === "非法用户,不可访问") {
          store.commit("user/reset");
          router.push("/");
        }
      } else if (code === 401 || code === 201 || code == 9001 || code == 9002) {
        message.error({
          content: msg,
          maxCount: 1,
          duration: 1,
        });
        store.commit("user/reset");
        setTimeout(() => {
          location.href = process.env.VUE_APP_API_portal_URL;
        }, 2000);
      }
    }
    NProgress.done();
    return response;
  },
  (error) => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = "错误请求";
          break;
        case 403:
          error.message = "拒绝访问";
          break;
        case 404:
          error.message = "请求错误,未找到该资源";
          break;
        case 405:
          error.message = "请求方法未允许";
          break;
        case 408:
          error.message = "请求超时";
          break;
        case 500:
          error.message = "服务器端出错";
          break;
        case 501:
          error.message = "网络未实现";
          break;
        case 502:
          error.message = "网络错误";
          break;
        case 503:
          error.message = "服务不可用";
          break;
        case 504:
          error.message = "网络超时";
          break;
        case 505:
          error.message = "http版本不支持该请求";
          break;
        default:
          error.message = `连接错误${error.response.status}`;
      }
    } else {
      if (JSON.stringify(error).includes("timeout")) {
        error.message = "服务器响应超时，请刷新当前页";
      } else {
        error.message = "连接服务器失败";
      }
    }
    message.error({
      message: error.message,
      maxCount: 1,
      duration: 1,
    });

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

export default axios;
