import axios from "axios";
// @ts-ignore
import { loadProgressBar } from "axios-progress-bar";
import { notifyInvalidTokenThrottled } from "./axiosNotice";
import { getToken, removeToken, getSessionId } from "../auth/auth";
import axiosRetry from "axios-retry";
import { PLATFORM, DEVICE_ID } from "@/constants/constants";
import { message } from "ant-design-vue";
import CryptoJS from "crypto-js";
import { useMainStore } from "@/store";

let store = null as unknown as ReturnType<typeof useMainStore>;

setTimeout(() => {
  store = useMainStore();
}, 0);

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

const _axiosApp = axios.create(config);
axiosRetry(_axiosApp, { retries: 3, retryDelay: () => 3000 });

function gToken(
  method: "get" | "post",
  url: string,
  token: string,
  time: number
) {
  const Authorization = `Token ${getSessionId()}:${CryptoJS.enc.Base64.stringify(
    CryptoJS.SHA1(method + "&" + url + "&" + time + "&" + token)
  )}`;

  return Authorization;
}

_axiosApp.interceptors.request.use(
  function (config) {
    if (config.setGlobalMask) {
      store.globalMask = true;
    }
    const wk_token = getToken();
    const time = Date.now();
    if (wk_token) {
      const completeURL = new URL("http://nasty.com" + config.url);
      const path = completeURL.pathname;
      // @ts-ignore
      config.headers.common["Authorization"] = gToken(
        config.method?.toLowerCase() === "get" ? "get" : "post",
        path,
        wk_token,
        time
      );
    }
    // @ts-ignore
    config.headers.common["platform"] = PLATFORM;
    // @ts-ignore
    config.headers.common["deviceId"] = DEVICE_ID;
    // @ts-ignore
    config.headers.common["time"] = time;
    return config;
  },
  function (error) {
    if (error.config.setGlobalMask) {
      store.globalMask = false;
    }
    void 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" 网络不通，直接返回
        void message.error({
          content: "网络连接异常，请检查网络设置。",
          duration: 10,
        });
      }
      return Promise.reject(error);
    }
    // 这里是返回状态码不为200时候的错误处理
    const status = error.response.status;

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

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

// eslint-disable-next-line
loadProgressBar(null, _axiosApp);

export const httpApp = _axiosApp;
