/**
 * 获取月份天数
 * @param {number} year
 * @param {number} month
 * @returns 天数
 */
export function getDayCount(year, month) {
  if (month == 2) {
    if (year % 400 === 0 || (year % 4 === 0 && year % 100)) { // 闰年
      return 29;
    }
    return 28;
  }
  return [1, 3, 5, 7, 8, 10, 12].indexOf(month) >= 0 ? 31 : 30;
}


/**
 * 计算指定日期 后几天的日期
 * @param {Date} date
 * @param {Number} count
 */
export function dateAfterDayCount(date = Date.now(), count = 1) {
  date = new Date(date)
  date.setDate(date.getDate() + count)
  return date
}


// 加法函数（精度丢失问题）
export function add(arg1, arg2) {
  let r1, r2, m;
  try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
  try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
  m = Math.pow(10, Math.max(r1, r2));
  return (arg1 * m + arg2 * m) / m
}


// 减法函数（精度丢失问题）
export function sub(arg1, arg2) {
  let r1, r2, m, n;
  try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
  try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
  m = Math.pow(10, Math.max(r1, r2));
  n = (r1 >= r2) ? r1 : r2;
  return Number(((arg1 * m - arg2 * m) / m).toFixed(n));
}



// 乘法函数（精度丢失问题）
export function mcl(num1, num2) {
  let m = 0, s1 = num1.toString(), s2 = num2.toString();
  try { m += s1.split(".")[1].length } catch (e) { }
  try { m += s2.split(".")[1].length } catch (e) { }
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}




// 除法函数（精度丢失问题）
export function division(num1, num2) {
  let t1, t2, r1, r2;
  try {
    t1 = num1.toString().split('.')[1].length;
  } catch (e) {
    t1 = 0;
  }
  try {
    t2 = num2.toString().split(".")[1].length;
  } catch (e) {
    t2 = 0;
  }
  r1 = Number(num1.toString().replace(".", ""));
  r2 = Number(num2.toString().replace(".", ""));
  return (r1 / r2) * Math.pow(10, t2 - t1);
}


//递归生成树形结构
export function getTreeData(data, pid, pidName = 'parentId', idName = 'id', childrenName = 'children', key = 'key', isNull = true) {
  let arr = [];

  for (let i = 0; i < data.length; i++) {
    if (data[i][pidName] == pid) {
      data[i][key] = data[i][idName];
      data[i][childrenName] = getTreeData(data, data[i][idName], pidName, idName, childrenName, key, isNull);
      if (isNull && data[i][childrenName].length == 0) delete data[i][childrenName]
      arr.push(data[i]);
    }
  }

  return arr;
}
