package com.lanyuanxiaoyao.leopard.core.helper;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import java.util.function.Function;

/**
 * @author lanyuanxiaoyao
 * @version 20250912
 */
public class NumberHelper {
  public static final String FINANCE_NULL_DOUBLE = "/";

  public static String formatFinanceDouble(Double value) {
    if (ObjectUtil.isNull(value)) {
      return FINANCE_NULL_DOUBLE;
    }
    var result = FINANCE_NULL_DOUBLE;
    var absValue = Double.valueOf(Math.abs(value));
    if (absValue > 100000000) {
      result = NumberUtil.decimalFormat("#.##亿", absValue / 100000000);
    } else if (value > 10000) {
      result = NumberUtil.decimalFormat("#.##万", absValue / 10000);
    } else {
      result = NumberUtil.decimalFormat("#.##", absValue);
    }
    return value < 0 ? "-" + result : result;
  }

  public static String formatDaysDouble(Double value) {
    if (ObjectUtil.isNull(value)) {
      return FINANCE_NULL_DOUBLE;
    }
    return NumberUtil.decimalFormat("#", value);
  }

  public static String formatPercentageDouble(Double value) {
    if (ObjectUtil.isNull(value)) {
      return null;
    }
    return NumberUtil.decimalFormat("0.00%", value);
  }

  public static String formatPriceDouble(Double value) {
    if (ObjectUtil.isNull(value)) {
      return null;
    }
    return NumberUtil.decimalFormat("0.00", value);
  }

  public static String formatPriceDouble(Integer value) {
    if (ObjectUtil.isNull(value)) {
      return null;
    }
    return NumberUtil.decimalFormat("0.00", value);
  }

  public static Double parseDouble(String value) {
    if (StrUtil.isBlank(value)) {
      return null;
    }
    return Double.parseDouble(value);
  }

  public static Double parseDouble(String value, Function<Double, Double> ifSuccess) {
    var result = parseDouble(value);
    return ObjectUtil.isNull(result) ? null : ifSuccess.apply(result);
  }

  public static Double safePlus(Double a, Double b) {
    if (ObjectUtil.isNull(a) || ObjectUtil.isNull(b)) {
      return null;
    }
    return a + b;
  }

  public static Double safeMinus(Double a, Double b) {
    if (ObjectUtil.isNull(a) || ObjectUtil.isNull(b)) {
      return null;
    }
    return a - b;
  }

  public static Double safeDiv(Double a, Double b) {
    if (ObjectUtil.isNull(a) || ObjectUtil.isNull(b) || b == 0) {
      return null;
    }
    return NumberUtil.div(a, b, 4);
  }
}
