package com.ruoyi.web.modules.trading.support;

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.HanyuPinyinVCharType;
import com.ruoyi.common.utils.StringUtils;

/**
 * 分配账号默认登录名：名称汉字拼音首字母（小写）+ 主键 id。
 */
public final class TradingPartnerLoginNameGenerator
{
    private static final HanyuPinyinOutputFormat FORMAT = new HanyuPinyinOutputFormat();

    static
    {
        FORMAT.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        FORMAT.setVCharType(HanyuPinyinVCharType.WITH_V);
    }

    private TradingPartnerLoginNameGenerator()
    {
    }

    public static String generate(String partnerName, Long id)
    {
        if (id == null)
        {
            throw new IllegalArgumentException("id is required");
        }
        String base = toInitials(StringUtils.nvl(partnerName, ""));
        if (base.isEmpty())
        {
            base = "user";
        }
        return base + id;
    }

    static String toInitials(String text)
    {
        if (StringUtils.isEmpty(text))
        {
            return "";
        }
        String trimmed = text.trim().replaceAll("\\s+", "");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < trimmed.length(); i++)
        {
            char c = trimmed.charAt(i);
            if (c <= 127 && Character.isLetterOrDigit(c))
            {
                sb.append(Character.toLowerCase(c));
            }
            else if (isChinese(c))
            {
                appendInitial(sb, c);
            }
        }
        return sb.toString();
    }

    private static void appendInitial(StringBuilder sb, char c)
    {
        try
        {
            String[] arr = PinyinHelper.toHanyuPinyinStringArray(c, FORMAT);
            if (arr != null && arr.length > 0 && StringUtils.isNotEmpty(arr[0]))
            {
                sb.append(arr[0].charAt(0));
            }
        }
        catch (Exception ex)
        {
            // skip unmapped char
        }
    }

    private static boolean isChinese(char c)
    {
        Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
        return block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || block == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || block == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A;
    }
}
