package vip.xiaonuo.common.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import org.springframework.stereotype.Component;

/**
 * 文字转拼音工具类
 * */
@Component
public class PinyinUtils {

    private static final HanyuPinyinOutputFormat FORMAT;

    static {
        FORMAT = new HanyuPinyinOutputFormat();
        FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 不带音调
        FORMAT.setCaseType(HanyuPinyinCaseType.LOWERCASE);     // 小写输出
        FORMAT.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE); // ü
    }

    /**
     * 获取全拼（如：你好 -> ni hao）
     */
    public static String toPinyin(String chinese) {
        return toPinyin(chinese, true);
    }

    /**
     * 获取全拼，可选是否保留非中文字符
     */
    public static String toPinyin(String chinese, boolean retainNonChinese) {
        if (chinese == null || chinese.trim().isEmpty()) return "";

        StringBuilder sb = new StringBuilder();

        for (char ch : chinese.toCharArray()) {
            if (Character.toString(ch).matches("[\\u4E00-\\u9FA5]")) {
                try {
                    String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(ch, FORMAT);
                    if (pinyins != null && pinyins.length > 0) {
                        sb.append(pinyins[0]).append("");
                    }
                } catch (Exception e) {
                    sb.append(ch);
                }
            } else if (retainNonChinese) {
                sb.append(ch);
            }
        }

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

    /**
     * 获取拼音首字母（如：你好 -> nh）
     */
    public static String toFirstLetters(String chinese) {
        return toFirstLetters(chinese, true);
    }

    /**
     * 获取拼音首字母，可选是否保留非中文字符
     */
    public static String toFirstLetters(String chinese, boolean retainNonChinese) {
        if (chinese == null || chinese.trim().isEmpty()) return "";

        StringBuilder sb = new StringBuilder();

        for (char ch : chinese.toCharArray()) {
            if (Character.toString(ch).matches("[\\u4E00-\\u9FA5]")) {
                try {
                    String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(ch, FORMAT);
                    if (pinyins != null && pinyins.length > 0) {
                        sb.append(pinyins[0].charAt(0));
                    }
                } catch (Exception e) {
                    // 忽略异常
                }
            } else if (retainNonChinese) {
                sb.append(ch);
            }
        }

        return sb.toString();
    }
}

