package com.tourism.common.core.util;

public class NumberToChineseConverter {

    // 中文数字字符数组
    private static final String[] CHINESE_DIGITS = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
    private static final String[] CHINESE_UNITS = {"", "十", "百", "千"};
    private static final String[] CHINESE_BIG_UNITS = {"", "万", "亿", "兆"};

    /**
     * 将阿拉伯数字转换为汉字
     * @param number 输入的阿拉伯数字
     * @return 转换后的汉字字符串
     */
    public static String convertToChinese(int number) {
        if (number == 0) {
            return "零";
        }
        if (number < 0) {
            return "负" + convertToChinese(-number);
        }

        StringBuilder result = new StringBuilder();
        String numStr = String.valueOf(number);
        int length = numStr.length();

        // 分组：每四位一组
        int groupIndex = 0;
        while (length > 0) {
            int start = Math.max(length - 4, 0);
            String group = numStr.substring(start, length);
            String groupChinese = convertGroupToChinese(Integer.parseInt(group));
            if (!groupChinese.isEmpty()) {
                result.insert(0, groupChinese + CHINESE_BIG_UNITS[groupIndex]);
            }
            length -= 4;
            groupIndex++;
        }

        return result.toString().replaceAll("零+$", ""); // 去除尾部多余的零
    }

    /**
     * 将四位以内的数字转换为汉字
     * @param number 四位以内的数字
     * @return 转换后的汉字字符串
     */
    private static String convertGroupToChinese(int number) {
        StringBuilder result = new StringBuilder();
        String numStr = String.valueOf(number);
        int length = numStr.length();
        boolean hasZero = false;

        for (int i = 0; i < length; i++) {
            int digit = numStr.charAt(i) - '0';
            if (digit == 0) {
                hasZero = true;
            } else {
                if (hasZero) {
                    result.append("零");
                    hasZero = false;
                }
                result.append(CHINESE_DIGITS[digit]).append(CHINESE_UNITS[length - 1 - i]);
            }
        }

        return result.toString().replaceAll("零+$", ""); // 去除尾部多余的零
    }
}

