import { MessagePlugin } from "tdesign-vue-next";
import axios from "axios";
import { getCookie } from "@/services/cookie";
import router from "./router";

// axios 配置
axios.defaults.timeout = 60000;
axios.defaults.withCredentials = false;

const requestDebounceMap = new Map();
const requestThrottleSet = new Set();

// http request 拦截器
axios.interceptors.request.use(
  (config: any) => {
    config.headers.Authorization =
      "Bearer " + (localStorage.token || getCookie("token") || "");

    if (config.params) {
      // 防抖， 比如输入搜索
      if (config.params.debounce > 0) {
        const url = config.method + config.url;

        const cache: any = requestDebounceMap.get(url);
        if (cache) {
          clearTimeout(cache.timer);
          cache.reject();
        }

        delete config.params.debounce;
        delete config.params.throttle;

        return new Promise((resolve, reject) => {
          const newCache: any = { reject };
          newCache.timer = setTimeout(() => {
            requestDebounceMap.delete(url);
            resolve(config);
          }, config.params.debounce);
          requestDebounceMap.set(url, newCache);
        });
      }
      // 节流，避免短时间重复请求，比如点击确定
      else if (config.params.throttle > 0) {
        const url = config.method + config.url;
        // 已经存在，取消重复请求
        if (requestThrottleSet.has(url)) {
          return Promise.reject("Repeated request.");
        }
        requestThrottleSet.add(url);
        setTimeout(() => {
          requestThrottleSet.delete(url);
        }, config.params.throttle);
      }

      delete config.params.debounce;
      delete config.params.throttle;
    }

    return config;
  },
  (err: any) => Promise.reject(err)
);

// http response 拦截器
axios.interceptors.response.use(
  (response: any) => {
    if (response && response.data && response.data.error) {
      MessagePlugin.error(response.data.error);
      return;
    }
    if (response) {
      return response.data;
    }
    return;
  },
  (error: any) => {
    if (error && !error.response) {
      return;
    }
    if (error && error.response) {
      if (error.response.config.url === "/api/account/profile") {
        return;
      }

      if (
        error.response.status !== 401 &&
        error.response &&
        error.response.data &&
        error.response.data.error
      ) {
        MessagePlugin.error(error.response.data.error);
        return;
      }

      switch (error.response.status) {
        case 401:
          sessionStorage.setItem("cb", encodeURIComponent(location.href));
          router.replace({ path: "/login" });
          break;
        case 403:
          MessagePlugin.error("请求错误，不合法的请求！");

          break;
        case 404:
          if (error.response.config.url.indexOf("/data/") !== 0) {
            MessagePlugin.error("访问数据不存在，请检查后重试！");
          }
          break;
        case 500:
          MessagePlugin.error("请求服务错误，请稍后重试！");
          break;
        case 504:
          MessagePlugin.error("网络超时，请检测你的网络！");
          break;
        default:
          MessagePlugin.error("未知网络错误！");
          break;
      }
    }
    // return error.response ? error.response.data : error;
  }
);

export default axios;
