package com.bonus.common.biz.utils;

import java.math.BigDecimal;

public class NumberToChinese {

    private static final String[] NUMBERS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    private static final String[] UNITS = {"", "拾", "佰", "仟"};
    private static final String[] BIG_UNITS = {"", "万", "亿", "兆"};

    public static String number2CN(BigDecimal number) {
        // 分离整数和小数部分
        BigDecimal integerPart = number.setScale(0, BigDecimal.ROUND_DOWN);
        BigDecimal decimalPart = number.subtract(integerPart).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP);

        StringBuilder result = new StringBuilder();

        if (integerPart.compareTo(BigDecimal.ZERO) > 0) {
            result.append(integerToChinese(integerPart.longValue())).append("元");
        }

        if (decimalPart.compareTo(BigDecimal.ZERO) > 0) {
            int jiao = decimalPart.intValue() / 10;
            int fen = decimalPart.intValue() % 10;
            if(jiao > 0){
                result.append(NUMBERS[jiao]).append("角");
            }
            if(fen > 0){
                result.append(NUMBERS[fen]).append("分");
            } else if(jiao == 0 && fen == 0){
                result.append("整");
            }
        } else {
            result.append("整");
        }

        return result.toString();
    }

    private static String integerToChinese(long num) {
        if (num == 0) return NUMBERS[0]; // 如果是0直接返回"零"

        StringBuilder chineseNum = new StringBuilder();
        int unitPos = 0;
        boolean needZero = false;

        while (num > 0) {
            long index = num % 10; // 获取当前位的数字
            if (index != 0 || unitPos % 4 == 0 && num / 10 % 10 != 0) { // 只有在非零或特定位置（万、亿等）才添加单位
                chineseNum.insert(0, UNITS[unitPos % 4]); // 添加对应的单位
                chineseNum.insert(0, NUMBERS[(int)index]); // 添加对应的数字字符
                needZero = false;
            } else if (!needZero) { // 避免连续的零
                if (!(chineseNum.length() > 0 && chineseNum.charAt(0) == NUMBERS[0].charAt(0))) {
                    chineseNum.insert(0, NUMBERS[0]);
                }
                needZero = true;
            }
            num /= 10;
            unitPos++;

            if(unitPos % 4 == 0 && num > 0){
                chineseNum.insert(0, BIG_UNITS[unitPos / 4]);
            }
        }

        // 清理多余的“零”
        String result = chineseNum.toString().replaceAll("零[仟佰拾]", "零")
                .replaceAll("零{2,}", "零")
                .replaceFirst("^零", "");

        // 处理特殊情况如“壹拾”前加“壹”的情况
        result = result.replaceAll("壹拾", "拾");

        return result;
    }

//    public static void main(String[] args) {
//        BigDecimal totalCostAll = new BigDecimal("84341.59000");
//        System.out.println(number2CN(totalCostAll));
//    }
}