import NP from "number-precision";

/**
 * 将十六进制颜色转为rgba
 *使用时只需传入十六进制字符串，“n”表示透明度
 * */
export const colorRgba = (str, n) => {
  if (!str) {
    return;
  }
  // 十六进制颜色值的正则表达式
  let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  let sColor = str.toLowerCase();
  // 十六进制颜色转换为RGB格式
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      let sColorNew = "#";
      for (let i = 1; i < 4; i += 1) {
        // 例如：#eee,#fff等
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
      }
      sColor = sColorNew;
    }
    // 处理六位颜色值
    let sColorChange = [];
    for (let i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
    }
    return "rgba(" + sColorChange.join(",") + "," + n + ")";
  } else {
    return sColor;
  }
};
export function second(value) {
  let theTime = parseInt(value); // 秒
  let middle = 0; // 分
  let hour = 0; // 小时

  if (theTime > 60) {
    middle = parseInt(theTime / 60);
    theTime = parseInt(theTime % 60);
    if (middle > 60) {
      hour = parseInt(middle / 60);
      middle = parseInt(middle % 60);
    }
  }
  let result = "" + parseInt(theTime) + "秒";
  if (middle > 0) {
    result = "" + parseInt(middle) + "分" + result;
  }
  if (hour > 0) {
    result = "" + parseInt(hour) + "小时" + result;
  }
  return result;
}
/**
 * 将router转换一下，转换成一级菜单
 * params: routes 数组
 * params: newRoutes 对象属性
 */
export function formatRouter(routes, newRoutes = []) {
  routes.map((item) => {
    if (item.children && item.children.length > 0)
      formatRouter(item.children, newRoutes);
    newRoutes.push(item);
  });
  return newRoutes;
}
/**
 * 数组去重
 * 按数组对象的某一个属性或两个或三个属性去重
 * params: arr 数组
 * params: property 对象属性
 */
export const unique = (arr = [], property = []) => {
  for (let i = 0, len = arr.length; i < len; i++) {
    for (let j = i + 1; j < len; j++) {
      if (property.length === 1) {
        if (arr[i][property[0]] === arr[j][property[0]]) {
          arr.splice(j, 1);
          // splice 会改变数组长度，所以要将数组长度 len 和下标 j 减一
          len--;
          j--;
        }
      } else if (property.length === 2) {
        if (
          arr[i][property[0]] === arr[j][property[0]] &&
          arr[i][property[1]] === arr[j][property[1]]
        ) {
          arr.splice(j, 1);
          // splice 会改变数组长度，所以要将数组长度 len 和下标 j 减一
          len--;
          j--;
        }
      } else if (property.length === 3) {
        if (
          arr[i][property[0]] === arr[j][property[0]] &&
          arr[i][property[1]] === arr[j][property[1]] &&
          arr[i][property[2]] === arr[j][property[2]]
        ) {
          arr.splice(j, 1);
          // splice 会改变数组长度，所以要将数组长度 len 和下标 j 减一
          len--;
          j--;
        }
      } else {
        if (arr[i] === arr[j]) {
          arr.splice(j, 1);
          // splice 会改变数组长度，所以要将数组长度 len 和下标 j 减一
          len--;
          j--;
        }
      }
    }
  }
  return arr;
};
/**
 * 获取当前日期前后N天的日期
 * */
export function funDate(aa) {
  let date1 = new Date();
  let time1 =
    date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate(); // time1表示当前时间
  let date2 = new Date(date1);
  date2.setDate(date1.getDate() + aa);
  let time2 =
    date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate();
  return time2;
}
// 本月第一天
export function showMonthFirstDay() {
  var Nowdate = new Date();
  var MonthFirstDay = new Date(Nowdate.getFullYear(), Nowdate.getMonth(), 1);
  const M = Number(MonthFirstDay.getMonth()) + 1;
  return (
    MonthFirstDay.getFullYear() +
    "/" +
    M +
    "/" +
    MonthFirstDay.getDate() +
    " 00:00:00"
  );
}
/**
 * 表格行合并
 */
export const getSpanArr = (data, key) => {
  let spanArr = [];
  let pos = 0;
  for (let i = 0; i < data.length; i++) {
    if (i === 0) {
      spanArr.push(1);
      pos = 0;
    } else {
      // 判断这一条和上一条id是否相同
      if (data[i][key] === data[i - 1][key]) {
        spanArr[pos] += 1;
        spanArr.push(0);
      } else {
        spanArr.push(1);
        pos = i;
      }
    }
  }
  return {
    spanArr: spanArr,
    pos: pos,
  };
};
// 获取当前时间，格式YYYY-MM-DD
export function getNowFormatDate() {
  const date = new Date();
  const seperator1 = "-";
  const year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  const currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}
/**
 * 深拷贝
 * */
export function deepClone(data) {
  return JSON.parse(JSON.stringify(data));
}
/**
 * table 合计必要字段
 */
export const getSummaries = (params, node = []) => {
  const { columns, data } = params;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return formatNub(NP.plus(Number(prev) || 0, Number(curr) || 0));
        } else {
          return formatNub(prev) || 0;
        }
      }, 0);
      if (!node.includes(column.label)) {
        sums[index] = "/";
      }
      sums[index] += "";
    } else {
      sums[index] = "/";
    }
  });
  return sums;
};
/**
 * table 合计必要字段
 * columns table列数据
 * data table 行数据
 * properties 不进行合并的参数
 */
export const sumNumVxe = (list, field) => {
  let count = 0;
  list.forEach((item) => {
    count = NP.plus(count, Number(item[field]));
  });
  return count;
};
export const getSummariesVxe = (columns, data, properties = []) => {
  const sums = columns.map((column, columnIndex) => {
    if (columnIndex === 0) {
      return "合计";
    }
    if (!column.property) {
      return "/";
    }
    if (!properties.includes(column.property)) {
      const num = sumNumVxe(data, column.property);
      return isNaN(num) ? "/" : formatNub(num);
    }
    return "/";
  });
  // 返回一个二维数组的表尾合计
  return [sums];
};
/**
 * 判断当前页面，是使用搜索引擎接口还是使用列表接口
 */
export const isSerch = (obj) => {
  let isKey = false;
  for (let i in obj) {
    let item = obj[i];
    if (Array.isArray(item)) {
      if (item.length > 0) {
        isKey = true;
        break;
      }
    } else if (
      typeof item === "string" ||
      typeof item === "number" ||
      typeof item === "boolean"
    ) {
      if (item) {
        isKey = true;
        break;
      }
    } else if (typeof item === "object") {
      if (item && JSON.stringify(item) !== "{}") {
        isKey = true;
        break;
      }
    }
  }
  return isKey;
};
/**
 * @description 时间格式化  时间戳转换为时间
 * @param date
 * @param fmt 例如 yyyy-MM-dd
 * @return {*}
 */

export function formatDate(date, fmt) {
  if (!date) return;
  date *= (date + "").length === 10 ? 1000 : 1;
  let _date = new Date(date);
  let _fmt = fmt || "yyyy-MM-dd hh:mm";
  let o = {
    "M+": _date.getMonth() + 1,
    "d+": _date.getDate(),
    "h+": _date.getHours(),
    "m+": _date.getMinutes(),
    "s+": _date.getSeconds(),
  };
  if (/(y+)/.test(_fmt)) {
    _fmt = _fmt.replace(
      RegExp.$1,
      (_date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (let k in o) {
    if (new RegExp("(" + k + ")").test(_fmt)) {
      _fmt = _fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return _fmt;
}
/**
 * 格式化数字，数字每隔三位加个逗号
 * params: num 需要处理的数字
 * params: len 需要保留的小数点位数
 */
export const formattedNumber = (num, len = 2) => {
  let result = "",
    counter = 0;
  let formatNum;
  if (num < 0) {
    formatNum = formatNub(Math.abs(num) || 0, len);
  } else {
    formatNum = formatNub(num || 0, len);
  }
  let stringNum = formatNum.toString().split(".");
  for (let i = stringNum[0].length - 1; i >= 0; i--) {
    counter++;
    result = stringNum[0].charAt(i) + result;
    if (!(counter % 3) && i !== 0) {
      result = "," + result;
    }
  }
  result = num < 0 ? "-" + result : result;
  if (stringNum[1]) {
    return "¥" + result + "." + stringNum[1];
  } else {
    return "¥" + result;
  }
};
/**
 * 不四舍五入保留n位小数
 * params: val 需要处理的数字
 * params: len 需要保留的小数点位数
 */
export const formatNub = (num, n = 2) => {
  if (n > 0) {
    if (typeof num != "number" && !Number(num)) {
      return "0.00";
    }

    num = Number(num).toString();
    let result = "";
    let zeroResult = function (n) {
      let zero = "";
      for (let i = 0; i < n; i++) {
        zero += "0";
      }
      return zero;
    };
    if (num % 1 == 0) {
      //整数
      result = num + "." + zeroResult(n);
    } else {
      //小数
      let num1 = num.split(".");
      if (num1[1].length < n) {
        result = num1[0] + "." + num1[1] + zeroResult(n - num1[1].length);
      } else {
        result = num1[0] + "." + num1[1].substring(0, n);
      }
    }
    return result;
  } else {
    return Number(num) || 0;
  }
};
/**

 * @description 格式化时间
 * @param time
 * @param cFormat
 * @returns {string|null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  return format.replace(/{([ymdhisa])+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
}

/**

 * @description 格式化时间
 * @param time
 * @param option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**

 * @description 将url请求参数转为json格式
 * @param url
 * @returns {{}|any}
 */
export function paramObj(url) {
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, " ") +
      '"}'
  );
}

/**

 * @description 父子关系的数组转换成树形结构数据
 * @param data
 * @returns {*}
 */
export function translateDataToTree(data) {
  const parent = data.filter(
    (value) => value.parentId === "undefined" || value.parentId == null
  );
  const children = data.filter(
    (value) => value.parentId !== "undefined" && value.parentId != null
  );
  const translator = (parent, children) => {
    parent.forEach((parent) => {
      children.forEach((current, index) => {
        if (current.parentId === parent.id) {
          const temp = JSON.parse(JSON.stringify(children));
          temp.splice(index, 1);
          translator([current], temp);
          typeof parent.children !== "undefined"
            ? parent.children.push(current)
            : (parent.children = [current]);
        }
      });
    });
  };
  translator(parent, children);
  return parent;
}

/**

 * @description 树形结构数据转换成父子关系的数组
 * @param data
 * @returns {[]}
 */
export function translateTreeToData(data) {
  const result = [];
  data.forEach((item) => {
    const loop = (data) => {
      result.push({
        id: data.id,
        name: data.name,
        parentId: data.parentId,
      });
      const child = data.children;
      if (child) {
        for (let i = 0; i < child.length; i++) {
          loop(child[i]);
        }
      }
    };
    loop(item);
  });
  return result;
}

/**

 * @description 10位时间戳转换
 * @param time
 * @returns {string}
 */
export function tenBitTimestamp(time) {
  const date = new Date(time * 1000);
  const y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? "" + m : m;
  let d = date.getDate();
  d = d < 10 ? "" + d : d;
  let h = date.getHours();
  h = h < 10 ? "0" + h : h;
  let minute = date.getMinutes();
  let second = date.getSeconds();
  minute = minute < 10 ? "0" + minute : minute;
  second = second < 10 ? "0" + second : second;
  return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second; //组合
}

/**

 * @description 13位时间戳转换
 * @param time
 * @returns {string}
 */
export function thirteenBitTimestamp(time) {
  const date = new Date(time / 1);
  const y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? "" + m : m;
  let d = date.getDate();
  d = d < 10 ? "" + d : d;
  let h = date.getHours();
  h = h < 10 ? "0" + h : h;
  let minute = date.getMinutes();
  let second = date.getSeconds();
  minute = minute < 10 ? "0" + minute : minute;
  second = second < 10 ? "0" + second : second;
  return y + "年" + m + "月" + d + "日 " + h + ":" + minute + ":" + second; //组合
}

/**

 * @description 获取随机id
 * @param length
 * @returns {string}
 */
export function uuid(length = 32) {
  const num = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  let str = "";
  for (let i = 0; i < length; i++) {
    str += num.charAt(Math.floor(Math.random() * num.length));
  }
  return str;
}

/**

 * @description m到n的随机数
 * @param m
 * @param n
 * @returns {number}
 */
export function random(m, n) {
  return Math.floor(Math.random() * (m - n) + n);
}

/**

 * @description addEventListener
 * @type {function(...[*]=)}
 */
export const on = (function () {
  return function (element, event, handler, useCapture = false) {
    if (element && event && handler) {
      element.addEventListener(event, handler, useCapture);
    }
  };
})();

/**

 * @description removeEventListener
 * @type {function(...[*]=)}
 */
export const off = (function () {
  return function (element, event, handler, useCapture = false) {
    if (element && event) {
      element.removeEventListener(event, handler, useCapture);
    }
  };
})();
