import Decimal from "decimal.js";


/**
 * 全局方法 处理为特定的decimal 格式
 * @param {*} num 
 */
export const decimalFormat = (num) => {
  // 处理特殊字符为字母的情况
  const reg = /[a-zA-Z]/gmi;
  if (reg.test(num) && num != undefined && num != null && isFinite(num)) {
    return num;
  } else if (!parseFloat(num)) {
    return "-";
  } else {
    return add(num, 0, 4, 15, true);
  }
};

/**
 * 加法
 * @param {*} num1 
 * @param {*} num2 
 * @returns 
 */
export const add = (num1, num2, digit = 9, intLen = 20, omit = false) => {
  const flag = (!parseFloat(num1) && parseFloat(num1) != "0") || (!parseFloat(num2) && parseFloat(num2) != "0");
  if (flag) throw new Error("传入参数错误，参数不为number");
  const decimal1 = new Decimal(num1);
  const decimal2 = new Decimal(num2);
  const result = decimal1.plus(decimal2);
  return omit ? result.toFixed(digit, Decimal.ROUND_HALF_UP) : result.toDecimalPlaces(digit, Decimal.ROUND_HALF_UP).toSignificantDigits(intLen).toString();
};

/**
 * 减法
 * @param {*} num1 
 * @param {*} num2 
 * @returns 
 */
export const subtract = (num1, num2, digit = 9, intLen = 20, omit = false) => {
  const flag = (!parseFloat(num1) && parseFloat(num1) != "0") || (!parseFloat(num2) && parseFloat(num2) != "0");
  if (flag) throw new Error("传入参数错误，参数不为number");
  const decimal1 = new Decimal(num1);
  const decimal2 = new Decimal(num2);
  const result = decimal1.minus(decimal2);
  return omit ? result.toFixed(digit, Decimal.ROUND_HALF_UP) : result.toDecimalPlaces(digit, Decimal.ROUND_HALF_UP).toSignificantDigits(intLen).toString();
};

/**
 * 乘法
 * @param {*} num1 
 * @param {*} num2 
 * @returns 
 */
export const multiply = (num1, num2, digit = 9, intLen = 20, omit = false) => {
  const flag = (!parseFloat(num1) && parseFloat(num1) != "0") || (!parseFloat(num2) && parseFloat(num2) != "0");
  if (flag) throw new Error("传入参数错误，参数不为number");
  const decimal1 = new Decimal(num1);
  const decimal2 = new Decimal(num2);
  const result = decimal1.times(decimal2);
  return omit ? result.toFixed(digit, Decimal.ROUND_HALF_UP) : result.toDecimalPlaces(digit, Decimal.ROUND_HALF_UP).toSignificantDigits(intLen).toString();
};

/**
 * 除法
 * @param {*} num1 
 * @param {*} num2 
 * @returns 
 */
export const divide = (num1, num2, digit = 9, intLen = 20, omit = false) => {
  const flag = (!parseFloat(num1) && parseFloat(num1) != "0") || (!parseFloat(num2) && parseFloat(num2) != "0");
  if (flag) throw new Error("传入参数错误，参数不为number");
  const decimal1 = new Decimal(num1);
  const decimal2 = new Decimal(num2);
  const result = decimal1.dividedBy(decimal2);
  return omit ? result.toFixed(digit, Decimal.ROUND_HALF_UP) : result.toDecimalPlaces(digit, Decimal.ROUND_HALF_UP).toSignificantDigits(intLen).toString();
};

// 检测结果是否是负数
export const targetIsNegative = (num) => {
  const flag = (!parseFloat(num) && parseFloat(num) != "0");
  if (flag) throw new Error("传入参数错误，参数不为number");
  return new Decimal(num).isNegative();
};
