/**
 * 判断对象类型
 * @param {*} obj 对象
 */
export function objTypeOf(obj) {
  const toString = Object.prototype.toString;
  const map = {
    "[object Boolean]": "boolean",
    "[object Number]": "number",
    "[object String]": "string",
    "[object Function]": "function",
    "[object Array]": "array",
    "[object Date]": "date",
    "[object RegExp]": "regExp",
    "[object Undefined]": "undefined",
    "[object Null]": "null",
    "[object Object]": "object",
    "[object Blob]": "blob",
  };
  return map[toString.call(obj)];
}

/**
 * 深拷贝
 * @param {Object/Array} data 需要拷贝的数据
 */
export function deepCopy(data) {
  return JSON.parse(JSON.stringify(data));
}

/**
 * 将目标对象中有的属性值与源对象中的属性值合并
 * @param {Object} target 目标对象
 * @param {Object} sources 源对象
 */
export function objAssign(target, sources) {
  let targ = deepCopy(target);
  for (let k in targ) {
    targ[k] = Object.prototype.hasOwnProperty.call(sources, k)
      ? sources[k]
      : targ[k];
  }
  return targ;
}

/**
 * 文件流下载
 * @param {Object} option 文件下载设置
 */
export function download(option) {
  let defOpt = {
    type: "get",
    url: "",
    data: "",
    fileName: "",
    header: "",
  };
  let opt = objAssign(defOpt, option);

  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open(opt.type.toUpperCase(), opt.url, true);
    xhr.responseType = "blob";

    // header set
    if (opt.header && objTypeOf(opt.header) === "object") {
      for (let key in opt.header) {
        xhr.setRequestHeader(key, opt.header[key]);
      }
    }

    xhr.onload = function () {
      if (this.readyState === 4 && this.status === 200) {
        if (this.response.size < 1024) {
          reject("文件不存在!");
          return;
        }

        var blob = this.response;
        let pdfUrl = "";
        let uRl = window.URL || window.webkitURL;
        if (uRl && uRl.createObjectURL) {
          pdfUrl = uRl.createObjectURL(blob);
        } else {
          reject("浏览器不兼容！");
        }
        let a = document.createElement("a");
        a.download = opt.fileName;
        a.href = pdfUrl;
        document.body.appendChild(a);
        a.click();
        a.parentNode.removeChild(a);
        resolve(true);
      } else {
        reject("请求错误！");
      }
    };

    if (opt.type.toUpperCase() === "POST") {
      let fromData = new FormData();
      for (let key in opt.data) {
        fromData.append(key, opt.data[key]);
      }
      xhr.send(fromData);
    } else {
      xhr.send();
    }
  });
}

/**
 * 获取随机code,默认获取16位
 * @param {Number} len 推荐8的倍数
 *
 */
export function randomCode(len = 16) {
  if (len <= 0) return;
  let steps = Math.ceil(len / 8);
  let stepNums = [];
  for (let i = 0; i < steps; i++) {
    let ranNum = Math.random().toString(32).slice(-8);
    stepNums.push(ranNum);
  }

  return stepNums.join("");
}

/**
 *
 * @param {String} format 时间格式
 * @param {Date} date 需要格式化的时间对象
 */
export function formatDate(format = "YYYY/MM/DD HH:mm:ss", date = new Date()) {
  if (objTypeOf(date) !== "date") return;
  const options = {
    "Y+": date.getFullYear(),
    "M+": date.getMonth() + 1,
    "D+": date.getDate(),
    "H+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
  };
  Object.entries(options).map(([key, val]) => {
    if (new RegExp("(" + key + ")").test(format)) {
      const zeros = key === "Y+" ? "0000" : "00";
      const value = (zeros + val).substr(("" + val).length);
      format = format.replace(RegExp.$1, value);
    }
  });
  return format;
}

export function parseTimeRangeDateAndTime(startTime, endTime) {
  if (!startTime || !endTime)
    return {
      date: "",
      time: "",
    };

  const st = formatDate("YYYY-MM-DD HH:mm", new Date(startTime)).split(" ");
  const et = formatDate("YYYY-MM-DD HH:mm", new Date(endTime)).split(" ");

  return {
    date: st[0],
    time: `${st[1]}-${et[1]}`,
  };
}

/**
 * 获取本地时间，格式：年月日时分秒
 */
export function localNowDateTime() {
  return formatDate("YYYY年MM月DD日HH时mm分ss秒");
}

/**
 *
 * @param {Number} time 时间戳
 */
export function getTimeDatestamp(time) {
  const date = formatDate("YYYY-MM-DD HH:mm", new Date(time)).split(" ")[0];
  return new Date(`${date} 00:00:00`).getTime();
}

/**
 * 清除html标签
 * @param {String} str html字符串
 */
export function removeHtmlTag(str) {
  return str.replace(/<[^>]+>/g, "");
}

/**
 * 计算总数
 * @param {Array} dataList 需要统计的数组
 */
export function calcSum(dataList) {
  if (!dataList.length) return 0;
  return dataList.reduce(function (total, item) {
    return total + item;
  }, 0);
}

/** 获取数组最大数 */
export function maxNum(dataList) {
  return Math.max.apply(null, dataList);
}

export function isEmptyObject(obj) {
  return !Object.keys(obj).length;
}

export function humpToLowLine(a) {
  return a
    .replace(/([A-Z])/g, "-$1")
    .toLowerCase()
    .slice(1);
}

export function pickByNotNull(params) {
  let nData = {};
  Object.entries(params).forEach(([key, val]) => {
    if (val === null || val === "null" || val === "") return;
    nData[key] = val;
  });
  return nData;
}

export function autoSubmitForm(url, params) {
  const form = document.createElement("form");
  form.action = url;
  form.method = "post";

  Object.entries(params).forEach(([key, val]) => {
    const input = document.createElement("input");
    input.type = "hidden";
    input.name = key;
    input.value = val;
    form.appendChild(input);
  });
  document.body.appendChild(form);
  form.submit();
}

export function blobToText(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsText(blob, "utf-8");
    reader.onload = function () {
      resolve(reader.result);
    };
    reader.onerror = function () {
      reject();
    };
  });
}

export function parseHrefParam(href, paramName = null) {
  if (!href) return;
  const paramStr = href.split("?")[1];
  if (!paramStr) return;

  let params = {};
  paramStr.split("&").forEach((item) => {
    const con = item.split("=");
    params[con[0]] = con[1];
  });

  return paramName ? params[paramName] : params;
}

export function checkRichTextContentIsEmpty(cont) {
  if (!cont) return true;

  if (!cont.sections || !cont.sections.length) return true;

  let blocks = [];
  cont.sections.forEach((section) => {
    blocks = [...blocks, ...section.blocks];
  });

  if (!blocks.length) return true;

  if (blocks.some((item) => item.type !== "text")) {
    return false;
  } else {
    return !blocks
      .map((item) => item.value)
      .join("")
      .trim();
  }
}
