import crypto from "crypto";
//个位数字补零
export function numberB0(n) {
  return n < 10 ? "0" + n : n;
}

/**
 * 传入[开始日期, 结束日期]
 * 返回格式[2020-10-01 00:00:00, 2020-10-01 23:59:59]
 * tag: 1，补时分秒
 *      2，补分秒
 *      3，补秒
 * */
export function dateQjChange(list, tag) {
  if (list[0] === "" || list[0] === null) return list;
  let d1 = new Date(list[0]);
  let d2 = new Date(list[1]);
  if (tag === undefined) {
    tag = 1;
  }
  switch (tag) {
    case 1:
      return [
        d1.getFullYear() +
          "-" +
          numberB0(d1.getMonth() + 1) +
          "-" +
          numberB0(d1.getDate()) +
          " 00:00:00",
        d2.getFullYear() +
          "-" +
          numberB0(d2.getMonth() + 1) +
          "-" +
          numberB0(d2.getDate()) +
          " 23:59:59",
      ];
    case 2:
      return [
        d1.getFullYear() +
          "-" +
          numberB0(d1.getMonth() + 1) +
          "-" +
          numberB0(d1.getDate()) +
          " " +
          numberB0(d1.getHours()) +
          ":00:00",
        d2.getFullYear() +
          "-" +
          numberB0(d2.getMonth() + 1) +
          "-" +
          numberB0(d2.getDate()) +
          " " +
          numberB0(d2.getHours()) +
          ":59:59",
      ];
      break;
    case 3:
      return [
        d1.getFullYear() +
          "-" +
          numberB0(d1.getMonth() + 1) +
          "-" +
          numberB0(d1.getDate()) +
          " " +
          numberB0(d1.getHours()) +
          ":" +
          numberB0(d1.getMinutes()) +
          ":00",
        d2.getFullYear() +
          "-" +
          numberB0(d2.getMonth() + 1) +
          "-" +
          numberB0(d2.getDate()) +
          " " +
          numberB0(d2.getHours()) +
          ":" +
          numberB0(d2.getMinutes()) +
          ":59",
      ];
      break;
  }
}

//金额分割符,4位分割（仅数字）
export function getNewNum(nStr) {
  nStr += "";
  var x = nStr.split(".");
  var x1 = x[0];
  var x2 = x.length > 1 ? "." + x[1] : "";
  var rgx = /(\d+)(\d{4})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, "$1" + "," + "$2");
  }
  return x1 + x2;
}

/*
 *  Ant和element-ui 级联相同bug - 底层存在children的时候会显示空模块的问题，此方法可以完成任意级别的递归找children。
 *  data:原型数据
 * */
export function cascaderBugRepair(data) {
  if (data == null) return false;
  let nums = data.length;
  for (var i = 0; i < nums; i++) {
    if (data[i].children.length <= 0) {
      delete data[i].children;
    } else {
      if (data[i].children.length > 0) {
        data[i].children = cascaderBugRepair(data[i].children);
      }
    }
  }
  return data;
}

/*
 *  MD5加密方法
 * */
export function getMd5(data) {
  const md5 = crypto.createHash("md5");
  md5.update(data);
  let md5password = md5.digest("hex");
  return md5password.toString().toUpperCase();
}

export default {
  getMd5,
  cascaderBugRepair,
  getNewNum,
  dateQjChange,
  numberB0,
};
