package com.ruoyi.common.utils;

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.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.*;

public class PinyUtils {

    // 获取姓名拼音的大写首字母
    public static char getPinyinInitial(String name) {
        if (name == null || name.trim().isEmpty()) {
            return ' '; // 返回空格表示无效
        }

        String trimmedName = name.trim();
        char firstChar = trimmedName.charAt(0);

        // 如果是中文字符
        if (isChineseCharacter(firstChar)) {
            return getChinesePinyinInitial(firstChar);
        }
        // 非中文字符（英文、数字等）
        return Character.toUpperCase(firstChar);
    }

    // 判断是否是中文字符
    private static boolean isChineseCharacter(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION;
    }

    // 获取中文字符的拼音首字母（大写）
    private static char getChinesePinyinInitial(char c) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        try {
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
            if (pinyinArray != null && pinyinArray.length > 0) {
                // 取第一个拼音的首字母
                return pinyinArray[0].charAt(0);
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        // 转换失败时返回原字符的大写形式
        return Character.toUpperCase(c);
    }


}
