/**
 * 获取链接某个参数
 */
export function getQueryString(key, url) {
  const reg = new RegExp(`([?&]+)${key}=([^&#]*)`);
  const href = url || window.location.href;
  const matches = href.substring(1).match(reg);

  return matches ? decodeURIComponent(matches[2]) : "";
}

/**
 * 获取接口前缀
 */
export function getAPI(code = "api") {
  const host = location.host;
  const origin = `${location.protocol}//${host}`;

  const basePath = "/super_cloud"; // 基础部署路径
  const api = `${origin}${basePath}`; // 基础接口
  const main = `${origin}${basePath}/wx/main`; // 服务之窗微信端部署路径
  const flashdeliver = `${origin}${basePath}/wx/flashdeliver`; // 楼闪送微信端部署路径

  switch (code) {
    case "host":
      return host;
    case "origin":
      return origin;
    case "main":
      return main;
    case "flashdeliver":
      return flashdeliver;
    default:
      return api;
  }
}

/**
 * isDefString
 * @param {*} str
 */
export function isDefString(str) {
  return str !== "undefined" && str !== "null";
}

/**
 * 获取服务之窗的缓存
 */
export function getLocalforage(key, def) {
  const str = localStorage.getItem(`localforage/${key}`);
  if (str) {
    try {
      return isDefString(JSON.parse(str)) ? JSON.parse(str) : "";
    } catch (e) {
      return str || null;
    }
  } else {
    // eslint-disable-next-line eqeqeq
    return def != undefined ? def : null;
  }
}

/**
 * 设置服务之窗的缓存
 */
export function setLocalforage(key, data) {
  localStorage.setItem(`localforage/${key}`, JSON.stringify(data));
}
