import CryptoJS from "crypto-js"; // 引用AES源码js

export function isEmptyObject(value) {
  if (JSON.stringify(value) == "{}") {
    return true;
  } else {
    return false;
  }
}

export function Encrypt() {
  const key = CryptoJS.enc.Utf8.parse('zh#2020#key#331#') // 十六位十六进制数作为密钥
  const token = "zh#2020#token#331#" + Date.parse(new Date()) / 1000;
  const srcs = CryptoJS.enc.Utf8.parse(token);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    // iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
}

export function getDeepValue(key, valueData, type = "") {
  if (key.includes(".")) {
    const keyList = key.split(".");
    if (valueData[keyList[0]]) {
      if (type && valueData[keyList[0]]) {
        return valueData[keyList[0]][keyList[1]][type];
      } else {
        return valueData[keyList[0]][keyList[1]];
      }
    } else {
      return undefined;
    }
  }
  if (type && valueData[key]) {
    return valueData[key][type] || undefined;
  } else {
    return valueData[key] || undefined;
  }
}

export function isChildOf(child, parent) {
  let parentNode;
  if (child && parent) {
    parentNode = child.parentNode;
    while (parentNode) {
      if (parent === parentNode) {
        return true;
      }
      parentNode = parentNode.parentNode;
    }
  }
  return false;
}

export function uploadImg(imgData) {
  return new Promise((resolve, reject) => {
    const HTTP = axios.create({
      baseURL: "/apis", // 这是基础url
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      transformRequest: [
        (data) => {
          // Do whatever you want to transform the data
          let ret = "";
          for (const it in data) {
            ret +=
              encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
          }
          return ret;
        },
      ],
    });
    HTTP.post("//star.xiaojukeji.com/upload/img.node", {
      imgData: imgData,
      innerPublic: true,
    }).then((res) => {
      resolve(res.data.url);
    });
  });
}
export function keepLastIndex(obj, window) {
  if (window.getSelection) {
    // ie11 10 9 ff safari
    obj.focus(); // 解决ff不获取焦点无法定位问题
    const range = window.getSelection(); // 创建range
    range.selectAllChildren(obj); // range 选择obj下所有子内容
    range.collapseToEnd(); // 光标移至最后
  } else if (document.selection) {
    // ie10 9 8 7 6 5
    const range = document.selection.createRange(); // 创建选择对象
    range.moveToElementText(obj); // range定位到obj
    range.collapse(false); // 光标移至最后
    range.select();
  }
}
