'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var axios = require('axios');
var elementPlus = require('element-plus');
var storage = require('./storage.js');

const abortControllerMap = /* @__PURE__ */ new Map();
const service = axios.create({
  baseURL: window.__env__.VITE_API_URL,
  timeout: 1e3 * 60 * 10
  // 设置超时，默认 10 分钟
  // headers: { 'Content-Type': 'application/json' },
});
const accessTokenKey = "access-token";
const refreshAccessTokenKey = `x-${accessTokenKey}`;
const getToken = () => {
  return storage.Local.get(accessTokenKey);
};
const getHeader = () => {
  return { authorization: "Bearer " + getToken() };
};
const clearAccessTokens = () => {
  clearTokens();
  if (window.location.hash.startsWith("#/login")) {
    window.location.hash = window.location.hash.replace(/([?&])token=[^&]*&?/, "$1").replace(/&$/, "");
  } else {
    window.location.reload();
  }
};
const clearTokens = () => {
  storage.Local.remove(accessTokenKey);
  storage.Local.remove(refreshAccessTokenKey);
  storage.Session.clear();
};
const axiosInstance = axios;
let loadingCount = 0;
let loadingInstance = null;
function startLoading() {
  if (loadingCount === 0) {
    loadingInstance = elementPlus.ElLoading.service({
      lock: true,
      text: "\u52A0\u8F7D\u4E2D...",
      background: "rgba(0, 0, 0, 0.7)"
    });
  }
  loadingCount++;
}
function endLoading() {
  if (loadingCount <= 0) return;
  loadingCount--;
  if (loadingCount === 0 && loadingInstance) {
    setTimeout(() => {
      loadingInstance == null ? void 0 : loadingInstance.close();
      loadingInstance = null;
    }, 200);
  }
}
service.interceptors.request.use(
  (config) => {
    var _a;
    const customConfig = config;
    if (customConfig.loading) {
      startLoading();
    }
    const controller = new AbortController();
    config.signal = controller.signal;
    const url = config.url || "";
    abortControllerMap.set(url, controller);
    const accessToken = storage.Local.get(accessTokenKey);
    if (accessToken) {
      config.headers["Authorization"] = `Bearer ${accessToken}`;
      const jwt = decryptJWT(accessToken);
      const exp = getJWTDate(jwt.exp);
      if (/* @__PURE__ */ new Date() >= exp) {
        const refreshAccessToken = storage.Local.get(refreshAccessTokenKey);
        if (refreshAccessToken) {
          config.headers["X-Authorization"] = `Bearer ${refreshAccessToken}`;
        }
      }
      if (((_a = config.method) == null ? void 0 : _a.toLowerCase()) === "get" && config.data) {
        let url2 = config.url + "?" + tansParams(config.data);
        url2 = url2.slice(0, -1);
        config.data = {};
        config.url = url2;
      }
    }
    return config;
  },
  (error) => {
    const customConfig = error.config;
    if ((customConfig == null ? void 0 : customConfig.loading) === true) {
      endLoading();
    }
    return Promise.reject(error);
  }
);
service.interceptors.response.use(
  (res) => {
    const customConfig = res.config;
    if (customConfig.loading === true) {
      endLoading();
    }
    const url = res.config.url || "";
    abortControllerMap.delete(url);
    var status = res.status;
    var serve = res.data;
    if (status === 401) {
      clearAccessTokens();
    }
    if (status >= 400) {
      throw new Error(res.statusText || "Request Error.");
    }
    if (serve && serve.hasOwnProperty("errors") && serve.errors) {
      throw new Error(JSON.stringify(serve.errors || "Request Error."));
    }
    var accessToken = res.headers[accessTokenKey];
    var refreshAccessToken = res.headers[refreshAccessTokenKey];
    if (accessToken === "invalid_token") {
      clearAccessTokens();
    } else if (refreshAccessToken && accessToken && accessToken !== "invalid_token") {
      storage.Local.set(accessTokenKey, accessToken);
      storage.Local.set(refreshAccessTokenKey, refreshAccessToken);
    }
    if (serve.code === 401) {
      clearAccessTokens();
    } else if (serve.code === void 0) {
      return Promise.resolve(res);
    } else if (serve.code !== 200) {
      let message = handleResponse(serve.message, 5);
      elementPlus.ElMessage.error({ dangerouslyUseHTMLString: true, message });
      throw new Error(serve.message);
    }
    return res;
  },
  (error) => {
    const customConfig = error.config;
    if (customConfig.loading === true) {
      endLoading();
    }
    if (error.response) {
      if (error.response.status === 401) {
        clearAccessTokens();
      } else if (error.response.statusCode === 404) {
        elementPlus.ElMessage.error("\u63A5\u53E3\u5F02\u5E38\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458");
      }
    }
    if (error.message.indexOf("timeout") != -1) {
      elementPlus.ElMessage.error("\u7F51\u7EDC\u8D85\u65F6");
    } else if (error.message == "Network Error") {
      elementPlus.ElMessage.error("\u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF");
    } else {
      if (error.response.data) elementPlus.ElMessage.error(error.response.statusText);
      else elementPlus.ElMessage.error("\u63A5\u53E3\u8DEF\u5F84\u627E\u4E0D\u5230");
    }
    return Promise.reject(error);
  }
);
const handleResponse = (input, col = 5) => {
  const messageList = [];
  const errorCodeRegex = /^\[[A-Za-z0-9_]+\]\s*/;
  function process(value) {
    if (value == null) return;
    if (typeof value === "string") {
      const clean = value.replace(errorCodeRegex, "");
      if (clean.trim()) messageList.push(clean.trim());
    } else if (Array.isArray(value)) {
      value.forEach((item) => process(item));
    } else if (typeof value === "object") {
      Object.values(value).forEach((val) => process(val));
    }
  }
  try {
    const parsed = typeof input === "string" ? JSON.parse(input) : input;
    process(parsed);
  } catch (e) {
    process(input);
  }
  col = col < 4 ? 4 : col;
  return messageList.reduce((rows, msg, i) => {
    if (i % col === 0) rows.push([]);
    rows[rows.length - 1].push(msg);
    return rows;
  }, []).map((row) => row.join("; ")).join("<br/>");
};
const cancelRequest = (url) => {
  var _a;
  const urlList = Array.isArray(url) ? url : [url];
  for (const _url of urlList) {
    (_a = abortControllerMap.get(_url)) == null ? void 0 : _a.abort();
    abortControllerMap.delete(_url);
  }
};
const cancelAllRequest = () => {
  for (const [_, controller] of abortControllerMap) {
    controller.abort();
  }
  abortControllerMap.clear();
};
function tansParams(params) {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof value[key] !== "undefined") {
            let params2 = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params2) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
}
function decryptJWT(token) {
  token = token.replace(/_/g, "/").replace(/-/g, "+");
  var json = decodeURIComponent(escape(window.atob(token.split(".")[1])));
  return JSON.parse(json);
}
function getJWTDate(timestamp) {
  return new Date(timestamp * 1e3);
}
function request2(config) {
  return new Promise((resolve, reject) => {
    service(config).then((res) => {
      if (res.data.type == "success") {
        resolve(res.data.result);
      } else {
        elementPlus.ElMessage.success(res.data.message);
      }
    }).catch((res) => {
      elementPlus.ElMessage.error(res);
      reject(res);
    });
  });
}
function reLoadLoginAccessToken(accessInfo) {
  if ((accessInfo == null ? void 0 : accessInfo.accessToken) && (accessInfo == null ? void 0 : accessInfo.refreshToken)) {
    storage.Local.remove("tagsViewList");
    storage.Session.set("token", accessInfo.accessToken);
    storage.Local.set(accessTokenKey, accessInfo.accessToken);
    storage.Local.set(refreshAccessTokenKey, accessInfo.refreshToken);
    setTimeout(() => location.href = "/", 500);
  }
}
function sleep(delay) {
  return new Promise((resolve) => setTimeout(resolve, delay));
}

exports.accessTokenKey = accessTokenKey;
exports.axiosInstance = axiosInstance;
exports.cancelAllRequest = cancelAllRequest;
exports.cancelRequest = cancelRequest;
exports.clearAccessTokens = clearAccessTokens;
exports.clearTokens = clearTokens;
exports.decryptJWT = decryptJWT;
exports.default = service;
exports.getHeader = getHeader;
exports.getJWTDate = getJWTDate;
exports.getToken = getToken;
exports.reLoadLoginAccessToken = reLoadLoginAccessToken;
exports.refreshAccessTokenKey = refreshAccessTokenKey;
exports.request2 = request2;
exports.service = service;
exports.sleep = sleep;
exports.tansParams = tansParams;
