package com.maintain.common.pinyin;

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;

/**
 * 中文拼音工具类
 */
public class PinyinUtils {

    /**
     * 获取单个汉字的大写首字母
     * @param c 中文字符
     * @return 拼音首字母，如果不是中文则返回原字符
     */
    public static char getFirstLetter(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 c;
    }

    /**
     * 获取字符串的大写拼音首字母
     * @param str 中文字符串
     * @return 拼音首字母组成的字符串
     */
    public static String getFirstLetters(String str) {
        if (str == null || str.trim().isEmpty()) {
            return "";
        }

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            result.append(getFirstLetter(str.charAt(i)));
        }
        return result.toString();
    }

    /**
     * 获取字符串的大写拼音首字母缩写
     * @param str 中文字符串
     * @return 拼音首字母缩写(每个汉字取首字母)
     */
    public static String getAbbreviation(String str) {
        if (str == null || str.trim().isEmpty()) {
            return "";
        }

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (isChinese(c)) {
                result.append(getFirstLetter(c));
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }

    /**
     * 判断字符是否是中文
     * @param c 字符
     * @return 是否是中文
     */
    public static boolean isChinese(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;
    }

}
