package com.awspaas.user.apps.donenow_ctt.service;

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 CityAbbreviationUtil {

    // 处理城市名称，去除常见后缀（如"市"、"省"等）
    private static String processCityName(String city) {
        if (city == null || city.trim().isEmpty()) {
            return "";
        }
        // 定义需要去除的后缀
        String[] suffixes = {"市", "省", "自治区", "自治州", "地区", "盟", "县", "区"};
        for (String suffix : suffixes) {
            if (city.endsWith(suffix)) {
                return city.substring(0, city.length() - suffix.length());
            }
        }
        return city;
    }

    // 获取单个汉字的拼音首字母（大写）
    private static char getFirstLetter(char chineseChar) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE); // 首字母大写
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 不带声调

        try {
            // 多音字可能返回多个拼音，取第一个
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(chineseChar, format);
            if (pinyinArray != null && pinyinArray.length > 0) {
                return pinyinArray[0].charAt(0); // 返回首字母
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }
        return chineseChar; // 非汉字直接返回原字符
    }

    // 生成城市拼音首字母缩写
    public static String getCityAbbreviation(String city) {
        String processedCity = processCityName(city);
        if (processedCity.isEmpty()) {
            return "";
        }

        StringBuilder abbreviation = new StringBuilder();
        for (int i = 0; i < processedCity.length(); i++) {
            char c = processedCity.charAt(i);
            abbreviation.append(getFirstLetter(c));
        }
        return abbreviation.toString();
    }

    // 测试
    public static void main(String[] args) {
        String cssx = "上海市";
        System.out.println(getCityAbbreviation(cssx)); // 输出：SH

        // 其他测试案例
        System.out.println(getCityAbbreviation("北京市")); // 输出：BJ
        System.out.println(getCityAbbreviation("广州市")); // 输出：GZ
        System.out.println(getCityAbbreviation("四川省")); // 输出：SC
    }
}