import Storage from "good-storage";
import Config from "@/config/index.js";

export function currentUrlToParams(key = null) {
  let paramsUrl = window.location.href.split("?");
  if (paramsUrl.length < 2) return key ? null : {};
  let paramsArr = paramsUrl[1].split("&");
  let paramsData = {};
  paramsArr.forEach(r => {
    let data = r.split("=");
    paramsData[data[0]] = decodeURIComponent(data[1]);
  });
  if (key) return paramsData.hasOwnProperty(key) ? paramsData[key] : null;
  return paramsData;
}

/**
 * 将对象转换为?a=5&b=7形式
 * @param obj
 * @param firstStr
 * @returns {string|string}
 */
export function obj2StrParams(obj, firstStr = "?") {
  let params = firstStr;

  for (let p in obj) {
    params += p + "=" + obj[p] + "&";
  }
  return params.substring(0, params.length - 1);
}
/*
获取当前url
http://192.168.49.71:8081/ => http://192.168.49.71:8081/
http://192.168.49.71:8081/mm/ => http://192.168.49.71:8081/mm/
http://192.168.49.71:8081/mm/index.html => http://192.168.49.71:8081/mm/
http://192.168.49.71:8081/mm/ff/login.html?id=55 => http://192.168.49.71:8081/mm/ff/

页面名字不能能匹配除\w 的地址，也就是说你的页面名字名字必须由a-z、A-Z、0-9，以及下划线组成才可以。
*/
export function getCurrentUrl() {
  let allUrl = window.location.href;
  let match = allUrl.match(/(\S+\/)\w+.html/i);
  return match && Array.isArray(match) && match.length > 1 ? match[1] : allUrl;
}

/**
 * 重置对象（会修改原始对象）
 * @param object
 * @param defaultVal
 */
export function resetObject(object, defaultVal = {}) {
  for (let k in object) {
    if (defaultVal.hasOwnProperty(k)) {
      object[k] = defaultVal[k];
    } else {
      if (Array.isArray(object[k])) object[k] = [];
      if ("string" == typeof object[k]) object[k] = "";
      if ("number" == typeof object[k]) object[k] = null;
      if ("boolean" == typeof object[k]) object[k] = false;
    }
  }
}

/**
 * 对象赋值（会修改原始对象）
 * @param object
 * @param valObject
 */
export function fillerLeft(object, valObject = {}) {
  for (let k in object) {
    if (valObject.hasOwnProperty(k)) {
      object[k] = valObject[k];
    }
  }
}

/**
 * 获取用户信息
 * @param key
 * @returns {null|*|undefined|{}}
 */
export function getUserInfo(key = null) {
  let userInfo = Storage.get(Config.userInfoKey) || {};
  if (key) return userInfo.hasOwnProperty(key) ? userInfo[key] : null;
  return userInfo || {};
}

/**
 * 设置用户信息
 * @param user
 * @returns {*}
 */
export function setUserInfo(user) {
  Storage.set(Config.userInfoKey, user);
  return user;
}

/**
 * 获取Token
 * @returns {*|undefined}
 */
export function getToken() {
  return Storage.get(Config.tokenKey);
}

/**
 * 设置Token
 * @param token
 * @returns {*|undefined}
 */
export function setToken(token) {
  return Storage.set(Config.tokenKey, token);
}

/**
 * 移除Token
 * @returns {*}
 */
export function removeToken() {
  return Storage.remove(Config.tokenKey);
}

/**
 * 数组->树
 */
export function toTree(list, propsConfig = {}) {
  const treeList = list || [];
  const out = [];
  const config = {
    rootId: propsConfig.rootId || null,
    idKey: propsConfig.idKey || "id",
    pidKey: propsConfig.pidKey || "pid",
    selectID: propsConfig.selectID || undefined,
    disabled: propsConfig.disabled || null
  };
  for (let index = 0, len = treeList.length; index < len; index++) {
    const element = treeList[index];
    element.spread =
      element.id === config.selectID || config.rootId === element.id;
    !element.children && (element.children = []);
    for (let i = 0, lens = treeList.length; i < lens; i++) {
      const sunItem = treeList[i];
      config.disabled !== null && (sunItem.disabled = config.disabled);
      if (element[config.idKey] !== sunItem[config.pidKey]) continue;
      element.children.push(sunItem);
    }
    !element.children.length && delete element.children;
    if (element[config.idKey] !== config.rootId) continue;
    out.push(element);
  }
  return out;
}

/**
 * string转base64
 * @param {*} a
 * @param {*} fn
 */

function utf8_encode(input) {
  input = input.replace(/\r\n/g, "\n");
  let utftext = "";
  for (let n = 0; n < input.length; n++) {
    let c = input.charCodeAt(n);
    if (c < 128) {
      utftext += String.fromCharCode(c);
    } else if (c > 127 && c < 2048) {
      utftext += String.fromCharCode((c >> 6) | 192);
      utftext += String.fromCharCode((c & 63) | 128);
    } else {
      utftext += String.fromCharCode((c >> 12) | 224);
      utftext += String.fromCharCode(((c >> 6) & 63) | 128);
      utftext += String.fromCharCode((c & 63) | 128);
    }
  }
  return utftext;
}

export function encode(input) {
  let _keyStr =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  let output = "";
  let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  let i = 0;
  input = utf8_encode(input);
  while (i < input.length) {
    chr1 = input.charCodeAt(i++);
    chr2 = input.charCodeAt(i++);
    chr3 = input.charCodeAt(i++);
    enc1 = chr1 >> 2;
    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
    enc4 = chr3 & 63;
    if (isNaN(chr2)) {
      enc3 = enc4 = 64;
    } else if (isNaN(chr3)) {
      enc4 = 64;
    }
    output =
      output +
      _keyStr.charAt(enc1) +
      _keyStr.charAt(enc2) +
      _keyStr.charAt(enc3) +
      _keyStr.charAt(enc4);
  }
  return output;
}

/**
 * string转base64 end
 */
