import Vue from "vue";
// import Store from "@/store";
import axios from "axios";
// @ts-ignore
import { loadProgressBar } from "axios-progress-bar";
import { notifyInvalidTokenThrottled } from "./axiosNotice";
import axiosRetry from "axios-retry";
import { message } from "ant-design-vue";
import { store } from "@/store";

const config = {
  // baseURL: store.env.server || "",
  timeout: 1 * 60 * 1000, // Timeout
  withCredentials: true, // Check cross-site Access-Control
};

const _axiosApp = axios.create(config);
axiosRetry(_axiosApp);

_axiosApp.interceptors.request.use(
  function (config) {
    if (config.setGlobalMask) {
      store.globalMask = true;
    }
    config.baseURL = store.env.server.host;
    config.headers = {
      "auth-info":
        "loginname=" + store.env.loginName + ";password=" + store.env.password,
    };
    return config;
  },
  function (error) {
    if (error.config.setGlobalMask) {
      store.globalMask = false;
    }
    message.error({ content: error, duration: 10 });
    console.log(error);
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axiosApp.interceptors.response.use(
  (response) => {
    if (response.config.setGlobalMask) {
      store.globalMask = false;
    }
    return response;
  },
  (error) => {
    if (error.config?.setGlobalMask) {
      store.globalMask = false;
    }
    const showErrorMessage = !error.config?.noErrorMessage;
    if (!error.response) {
      if (showErrorMessage) {
        // "Network Error" 网络不通，直接返回
        message.error({
          content: "网络连接异常，请检查网络设置。",
          duration: 10,
        });
      }
      return Promise.reject(error);
    }
    // 这里是返回状态码不为200时候的错误处理
    const status = error.response.status;

    // 登录失效 跳转登录页面
    if (status == 403 || status == 401) {
      notifyInvalidTokenThrottled();
      return Promise.reject(error);
    } else if (status == 405) {
      if (showErrorMessage) {
        message.error({ content: "没有权限！", duration: 10 });
      }
      return Promise.reject(error);
    } else if (status == 502) {
      if (showErrorMessage) {
        message.error({ content: "服务器异常(502)！", duration: 10 });
      }
      return Promise.reject(error);
    }

    if (status != 200) {
      const data = error.response.data;
      if (data && data.message) {
        if (showErrorMessage) {
          message.error({ content: data.message, duration: 10 });
        }
      } else {
        if (showErrorMessage) {
          message.error({
            content: "未定义异常: " + JSON.stringify(data, null, 2),
            duration: 10,
          });
        }
      }
      return Promise.reject(error);
    }
  }
);

// _axiosApp.get = cachingGet(_axiosApp, cacheGetUrls);
loadProgressBar(null, _axiosApp);

export const httpApp = _axiosApp;
