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 PinYinUtil {
  /**
   * 测试main方法
   * @param args
   */
  public static void main(String[] args) {
    System.out.println("‘张三’首字母大写：" + toChar("张三").toUpperCase()); //转为首字母大写
    System.out.println("‘张三’转成拼音：" + toPinyin("zc"));
    System.out.println("‘张三’第一个汉字首字母大写：" + toFirstChar("张三").toUpperCase());
  }
  /**
   * 获取字符串拼音的第一个字母
   * @param chinese
   * @return
   */
  public static String toChar(String chinese){
    String pinyinStr = "";
    char[] newChar = chinese.toCharArray();  //转为单个字符
    HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
    defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
    defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    for (int i = 0; i < newChar.length; i++) {
      if (newChar[i] > 128) {
        try {
          pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
        } catch (BadHanyuPinyinOutputFormatCombination e) {
          e.printStackTrace();
        }
      }else{
        pinyinStr += newChar[i];
      }
    }
    return pinyinStr;
  }

  /**
   * 汉字转为拼音
   * @param chinese
   * @return
   */
  public static String toPinyin(String chinese){
    String pinyinStr = "";
    char[] newChar = chinese.toCharArray();
    HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
    defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
    defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    for (int i = 0; i < newChar.length; i++) {
      if (newChar[i] > 128) {
        try {
          pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
        } catch (BadHanyuPinyinOutputFormatCombination e) {
          e.printStackTrace();
        }
      }else{
        pinyinStr += newChar[i];
      }
    }
    return pinyinStr;
  }


  /**
   * 有多个汉字，只取第一个汉字进行翻译
   * @param chinese
   * @return
   */
  public static String toFirstChar(String chinese){
    String pinyinStr = "";
    char[] newChar = chinese.toCharArray();  //转为单个字符
    HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
    defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
    defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    if (newChar[0] > 128) {
      try {
        pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[0], defaultFormat)[0].charAt(0);
      } catch (BadHanyuPinyinOutputFormatCombination e) {
        e.printStackTrace();
      }
    }else{
      pinyinStr += newChar[0];
    }
    return pinyinStr;
  }

}
