package com.brilliance.isc.utils;

import com.brilliance.mda.runtime.mda.util.MdaUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Optional;

public class BigDecimalUtils {


    public static String BigD2stringHalfUP(BigDecimal amt, int bit) {

        return amt.setScale(bit, RoundingMode.HALF_UP).toPlainString();

    }

    public static String BigD2stringDown(BigDecimal amt, int bit) {

        return amt.setScale(bit, RoundingMode.DOWN).toPlainString();

    }

    /**
     * String 转 Bigdecimal
     *
     * @param val
     * @return
     */
    public static BigDecimal string2BigDecimal(String val) {
        if (StringUtils.isEmpty(val)) {
            return BigDecimal.ZERO;
        }
        return Optional.of(val).map(BigDecimal::new).get();


    }

    public static String convertNumberToWords(String currency, BigDecimal number) {
        // 实现将数字转换为英文单词的逻辑，这里仅提供简单示例
        //（请注意，这个实现不适用于大额金额）
        String[] units = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
        String[] tens = {"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
        String[] teens = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
        String[] thousands = {"", "thousand", "million", "billion", "trillion"};

        //int dollars = number.intValue();
        String numStr = number.setScale(0, RoundingMode.DOWN).toString();
        int cents = number.remainder(BigDecimal.ONE).movePointRight(2).intValue();
        boolean biggerThanThousand = false;
        if (number.compareTo(new BigDecimal("1000")) > -1) {
            biggerThanThousand = true;
        }

        StringBuilder dollarsInWords = new StringBuilder();
        if (number.compareTo(new BigDecimal("0")) == 0) {
            dollarsInWords = new StringBuilder("zero");
        } else {
            int subIndex = numStr.length();
            int index = 0;
            while (subIndex > 0) {
                int num = Integer.parseInt(numStr.substring(Math.max(subIndex - 3, 0), subIndex));
                if (num != 0) {
                    dollarsInWords.insert(0, convertThreeDigitNumberToWords(num, units, tens, teens, index, biggerThanThousand) + " " + thousands[index] + " ");
                }
                subIndex -= 3;
                index++;
            }
        }

        String centsInWords = "";
        if (cents > 0) {
            centsInWords = cents + "/100";
        }
        // 部分面函文本是两个变量拼接的
        if (MdaUtils.isEmpty(currency)) {
            return dollarsInWords.toString().trim() + " " + centsInWords.trim();
        }

        // 格式化金额
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        String formattedAmount = numberFormat.format(number);
        return currency + formattedAmount + " (Say " + currency + " " + dollarsInWords.toString().trim() + " " + centsInWords.trim() + " only).";
    }

    private static String convertThreeDigitNumberToWords(int number, String[] units, String[] tens, String[] teens, int index, boolean biggerThanThousand) {
        StringBuilder sb = new StringBuilder();
        boolean bigthantwenty = false;

        if (number >= 100) {
            sb.append(units[number / 100]).append(" hundred ");
            number %= 100;
        }
        if (number >= 20) {
            bigthantwenty = true;
            sb.append(appendAnd(sb.toString(), index, biggerThanThousand)).append(tens[number / 10]).append(" ");
            number %= 10;
        } else if (number >= 10) {
            sb.append(appendAnd(sb.toString(), index, biggerThanThousand)).append(teens[number % 10]).append(" ");
            number = 0;
        }
        if (number > 0) {
            sb.append(bigthantwenty ? "" : appendAnd(sb.toString(), index, biggerThanThousand)).append(units[number]).append(" ");
        }

        return sb.toString().trim();
    }

    public static String appendAnd(String str, int index, boolean biggerThanThousand) {
        if (str.endsWith("hundred ") || (index == 0 && biggerThanThousand)) {
            return " and ";
        }
        return "";
    }

    /**
     * 金额相加 参数为字符串
     *
     * @param scal
     * @param amounts
     * @return
     */
    public static String stringAdd(int scal, String... amounts) {
        BigDecimal sum = BigDecimal.ZERO;
        for (String amt : amounts) {
            sum = sum.add(string2BigDecimal(amt));
        }
        return BigD2stringHalfUP(sum, scal);
    }

    public static BigDecimal add(int scal, BigDecimal... amounts) {
        BigDecimal sum = BigDecimal.ZERO;
        for (BigDecimal amt : amounts) {
            sum = sum.add(amt);
        }
        return sum.setScale(scal, RoundingMode.HALF_UP);
    }

    /**
     * 俩个金额相减
     * @param divisor
     * @param dividend
     * @return
     */
    public static BigDecimal subtract(BigDecimal divisor,BigDecimal dividend){
        return  divisor.subtract(dividend);
    }

    /**
     * 俩个金额相减求绝对值
     * @param divisor
     * @param dividend
     * @return
     */
    public static BigDecimal subtractAbs(BigDecimal divisor,BigDecimal dividend){
        return  divisor.subtract(dividend).abs();
    }

    public static BigDecimal divide(BigDecimal divisor,BigDecimal dividend){
        return  divisor.divide(dividend,4,RoundingMode.HALF_UP);
    }

    /**
     * 转bigdecimal
     * @param str
     * @returnisLimStart
     */
    public static BigDecimal parseBigDecimal(String str) {
        if (!StringUtils.isEmpty(str)) {
            return new BigDecimal(str);
        }
        return new BigDecimal(0);
    }
}