import { spread } from "@/api/user";
import Cache from "@/utils/cache";

/**
 * 静默授权绑定上下级，使用在已经登录后扫描了别人的推广二维码
 * @param {Object} puid
 */
export function silenceBindingSpread() {
  //#ifdef H5 || APP
  let puid = Cache.get("spread");
  //#endif

  //#ifdef MP
  let puid = getApp().globalData.spid;
  //#endif

  puid = parseInt(puid);
  if (Number.isNaN(puid)) {
    puid = 0;
  }
  if (puid) {
    spread(puid)
      .then((res) => {})
      .catch((res) => {});
    //#ifdef H5
    Cache.clear("spread");
    //#endif

    //#ifdef MP
    getApp().globalData.spid = 0;
    getApp().globalData.code = 0;
    //#endif
  } else {
    Cache.set("spread", 0);
  }
}

export function isWeixin() {
  return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
}

export function getNetworkType() {
  return new Promise((resolve, reject) => {
    uni.getNetworkType({
      success: (res) => {
        // 无网络时 networkType 为 'none'
        if (res.networkType === "none") {
          resolve(1); // 无网络
        } else {
          resolve(0); // 有网络
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

export function parseQuery() {
  const res = {};

  const query = (location.href.split("?")[1] || "")
    .trim()
    .replace(/^(\?|#|&)/, "");

  if (!query) {
    return res;
  }

  query.split("&").forEach((param) => {
    const parts = param.replace(/\+/g, " ").split("=");
    const key = decodeURIComponent(parts.shift());
    const val = parts.length > 0 ? decodeURIComponent(parts.join("=")) : null;

    if (res[key] === undefined) {
      res[key] = val;
    } else if (Array.isArray(res[key])) {
      res[key].push(val);
    } else {
      res[key] = [res[key], val];
    }
  });

  return res;
}

export function weAtob(string) {
  const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  const b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
  string = String(string).replace(/[\t\n\f\r ]+/g, '');
  if (!b64re.test(string)) {
      throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
  }
  string += '=='.slice(2 - (string.length & 3));
  let bitmap;
  let i = 0;
  let r1;
  let r2;
  let result = '';
  for (; i < string.length; ) {
      bitmap =
          (b64.indexOf(string.charAt(i++)) << 18) |
          (b64.indexOf(string.charAt(i++)) << 12) |
          ((r1 = b64.indexOf(string.charAt(i++))) << 6) |
          (r2 = b64.indexOf(string.charAt(i++)));
      result +=
          r1 === 64
              ? String.fromCharCode((bitmap >> 16) & 255)
              : r2 === 64
              ? String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255)
              : String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255, bitmap & 255);
  }
  return result;
};

// #ifdef H5
const VUE_APP_WS_URL =
  process.env.VUE_APP_WS_URL || `ws://${location.hostname}:20001`;
export { VUE_APP_WS_URL };
// #endif

export const VUE_APP_API_URL = "";

export default parseQuery;
