package com.mosty.base.utils;


import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.apache.commons.lang3.StringUtils;


public class getPinYin {
    /**
     * 获取中文拼音
     *
     * @param str
     * @param shortPinyin 为true获取中文拼音首字母
     * @param retain      为true保留其他字符
     * @return String
     */
    private static String getPinyin(String str, boolean shortPinyin, boolean retain) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        StringBuffer pinyinBuffer = new StringBuffer();
        char[] arr = str.toCharArray();
        for (char c : arr) {
            String[] temp = PinyinHelper.toHanyuPinyinStringArray(c);
            if (ArrayUtils.isNotEmpty(temp)) {
                if (StringUtils.isNotBlank(temp[0])) {
                    if (shortPinyin) {
                        pinyinBuffer.append(temp[0].charAt(0));
                    } else {
                        pinyinBuffer.append(temp[0].replaceAll("\\d", ""));
                    }
                }
            } else {
                if (retain) {
                    pinyinBuffer.append(c);
                }
            }
        }
        return pinyinBuffer.toString();
    }

    public static String getShortPinyin(String str) {
        return getPinyin(str, true, false);
    }


}
