package com.sunxung.factoring.component.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.exception.BadHanyuPinyinOutputFormatCombination;

public class ChinesePinYinUtil {

    /**
     * 将汉字转换为全拼
     */
    public static String getPinYin(String str) {
        if (str == null || str.isEmpty()) {
            return "";
        }
        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        StringBuilder sb = new StringBuilder();
        try {
            for (char c : str.toCharArray()) {
                // 如果包含有中文标点除号，需要使用正则表达式
                if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                    sb.append(PinyinHelper.toHanyuPinyinStringArray(c, outputFormat)[0]);
                } else {
                    sb.append(Character.toString(c));
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        String fullPinYin = sb.toString();
        if (StringUtil.isNotEmpty(fullPinYin) && fullPinYin.length() > 45) {
            fullPinYin = fullPinYin.substring(0, 45);
        }
        return fullPinYin;
    }

    /**
     * 提取每个汉字的首字母
     */
    public static String getPinYinFirstChar(String str) {
        if (str == null || str.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (char c : str.toCharArray()) {
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
            if (pinyinArray != null) {
                sb.append(pinyinArray[0].charAt(0));
            } else {
                sb.append(c);
            }
        }
        String simplePinYin = sb.toString();
        if (StringUtil.isNotEmpty(simplePinYin) && simplePinYin.length() > 25) {
            simplePinYin = simplePinYin.substring(0, 25);
        }
        return simplePinYin;
    }
}
