package com.storlead.user.util;

import com.storlead.user.model.UserInfo;
import com.storlead.user.pojo.vo.WxUserVO;
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.text.Collator;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class PingyinUtil {

    public static void main(String[] args) {
//        List<String> list = new ArrayList<>();
//        list.add("张三");
//        list.add("李四");
//        list.add("王五");
//        list.add("赵六");
//        list.add("曾七");
//        Map<String,Object> map = screenManufacturer(list);
//        for (String key:map.keySet()){
//            System.out.println("key= "+key+" and value= "+map.get(key));
//        }
//        System.out.println(getFullPinyin("曾")+getFullPinyin("张"));
        System.out.println(getLowFullSpell("目录"));
    }

    // 这里需要用到 pinyin4j-2.5.0.jar 这个汉字转拼音的jar包

    /**
     * 获取汉字串拼音，英文字符不变
     */
    public static String getLowFullSpell(String chinese) {
        chinese = filterSpecialChars(chinese);
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 128) {
                try {
                    pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(arr[i]);
            }
        }
        return pybf.toString();
    }

    /**
     * 获取汉字串拼音，英文字符不变
     */
    public static String getFullSpell(String chinese) {
        chinese = filterSpecialChars(chinese);
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 128) {
                try {
                    pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(arr[i]);
            }
        }
        return pybf.toString();
    }

    /**
     * 将集合数据按照汉字首字母分组排序
     */
    public static Map<String, Object> screenManufacturer(List<String> list) {
        try {
            Collator com = Collator.getInstance(Locale.CHINA);
            // 按字母排序
            Collections.sort(list, com);
            // 输出26个字母
            Map<String, Object> map = new TreeMap<>();
            for (int i = 1; i < 27; i++) {
                String word = String.valueOf((char)(96 + i)).toUpperCase();
                // 循环找出 首字母一样的数据
                List<String> letter = new ArrayList<>();
                for (String str : list) {
//                    String pybf = getFullSpell(str);
                    String pybf = getFullPinyin(str);
                    String zm = pybf.substring(0, 1);
                    if (word.equals(zm)) {
                        letter.add(str);
                    }
                }
                map.put(word, letter);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将集合数据按照汉字首字母分组排序
     */
    public static List<WxUserVO> wxUserList(List<UserInfo> userList) {
        try {
            List<String> userNameList = new ArrayList<>();
            Map<String,UserInfo> userInfoMap = new HashMap<>();
            for (UserInfo u:userList) {
                userNameList.add(u.getRealName()+u.getId());
                userInfoMap.put(u.getRealName()+u.getId(),u);
            }

            Collator com = Collator.getInstance(Locale.CHINA);
            // 按字母排序
            Collections.sort(userNameList, com);
            // 输出26个字母
            List<WxUserVO> wxUserVOList = new ArrayList<>();
            for (int i = 1; i < 27; i++) {
                String word = String.valueOf((char)(96 + i)).toUpperCase();
                // 循环找出 首字母一样的数据
                List<UserInfo> userInfoList = new ArrayList<>();
                for (String str : userNameList) {
//                    String pybf = getFullSpell(str);
                    String pybf = getFullPinyin(str);
                    String zm = pybf.substring(0, 1);
                    if (word.equals(zm)) {
                        userInfoList.add(userInfoMap.get(str));
                    }
                }
                WxUserVO wxUserVO = new WxUserVO();
                wxUserVO.setLetter(word);
                wxUserVO.setData(userInfoList);
                wxUserVOList.add(wxUserVO);
            }
            return wxUserVOList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


     /***
      * @Description: 姓氏多音字解决方案
      * @Param:
      * @return:
      * @Author: YPZ
      * @Date: 2023/3/23 11:26
      */
    /**
     * 多音字拼音
     */
    public static Map<String, String> FIRST_NAME_PINYIN = new HashMap<>();
    static {
        FIRST_NAME_PINYIN.put("繁", "PO");
        FIRST_NAME_PINYIN.put("区", "OU");
        FIRST_NAME_PINYIN.put("仇", "QIU");
        FIRST_NAME_PINYIN.put("种", "CHONG");
        FIRST_NAME_PINYIN.put("单", "SHAN");
        FIRST_NAME_PINYIN.put("解", "XIE");
        FIRST_NAME_PINYIN.put("查", "ZHA");
        FIRST_NAME_PINYIN.put("曾", "ZENG");
        FIRST_NAME_PINYIN.put("秘", "BI");
        FIRST_NAME_PINYIN.put("乐", "YUE");
        FIRST_NAME_PINYIN.put("重", "CHONG");
        FIRST_NAME_PINYIN.put("朴", "PIAO");
        FIRST_NAME_PINYIN.put("缪", " MIAO");
        FIRST_NAME_PINYIN.put("冼", " XIAN");
        FIRST_NAME_PINYIN.put("翟", "ZHAI");
        FIRST_NAME_PINYIN.put("折", "SHE");
        FIRST_NAME_PINYIN.put("黑", "HE");
        FIRST_NAME_PINYIN.put("盖", "GE");
        FIRST_NAME_PINYIN.put("沈", "SHEN");
        FIRST_NAME_PINYIN.put("尉迟", "YUCHI");
        FIRST_NAME_PINYIN.put("万俟", "MOQI");
    }

    /**
     * @Description: 过滤掉中文特殊字符
     * @throws PatternSyntaxException
     */
    public static String filterSpecialChars(String target) throws PatternSyntaxException
    {
        String regEx = "[\\uac00-\\ud7af\\u3130–\\u318F]*[\\u0800-\\u4e00`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？_]";
        Pattern pat = Pattern.compile(regEx);
        Matcher mat = pat.matcher(target);
        return mat.replaceAll("").trim();
    }
    /**
     * 获得完整拼音
     * 解决姓多音字问题
     *
     * @param keywords
     * @return
     */
    public static String getFullPinyin(String keywords) {
        if(keywords == null || "".equals(keywords)) {
            return keywords;
        }
        for (Map.Entry<String, String> map : FIRST_NAME_PINYIN.entrySet()) {
            if (keywords.startsWith(map.getKey())) {
                String suffix = keywords.substring(map.getKey().length());
                return map.getValue() + getFullSpell(suffix);
            }
        }
        return getFullSpell(keywords);
    }

    public static String getInitials(String chinese) {
        StringBuilder initials = new StringBuilder();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        for (char ch : chinese.toCharArray()) {
            if (Character.toString(ch).matches("[\u4E00-\u9FA5]")) { // 判断是否为汉字
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(ch, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        initials.append(pinyinArray[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {

                }
            } else {
                initials.append(ch); // 非汉字直接附加
            }
        }

        return initials.toString();
    }
}
