package quant.rich.emoney.util;

public class StockCodeUtils {
    
    /**
     * 从 goodsId 转换为 tsCode
     * @param goodsId
     * @return
     */
    public static String goodsIdToTsCode(Integer goodsId) {
        if (goodsId == null || goodsId < 0) {
            throw new IllegalArgumentException("goodsId 不能为空或为负数");
        }

        final String s = goodsId.toString();
        final int len = s.length();

        switch (len) {
            case 6:
                // 6 位默认 SH
                return s + ".SH";

            case 7:
                // 7 位默认 SZ 或 BJ
                if (!s.startsWith("1")) {
                    throw new IllegalArgumentException("无法将 goodsId " + s + " 转换为 tsCode");
                }

                char second = s.charAt(1);
                String core = s.substring(1);

                if (second == '9') {
                    return core + ".BJ";
                }
                return core + ".SZ";

            default:
                throw new IllegalArgumentException("无法将 goodsId " + s + " 转换为 tsCode");
        }
    }
    
    /**
     * 从 tsCode 转换成 goodsId
     * @param tsCode
     * @return
     */
    public static Integer tsCodeToGoodsId(String tsCode) {
        if (tsCode == null || tsCode.isBlank()) {
            throw new IllegalArgumentException("tsCode 不能为空");
        }

        String s = tsCode.trim().toUpperCase();

        // 期望格式：XXX.SZ / XXX.SH / XXX.BJ
        int dot = s.indexOf('.');
        if (dot <= 0 || dot == s.length() - 1) {
            throw new IllegalArgumentException("tsCode 格式无效: " + tsCode);
        }

        String code = s.substring(0, dot);
        String market = s.substring(dot + 1);

        if (!code.matches("\\d+")) {
            throw new IllegalArgumentException("tsCode 数字部分无效: " + tsCode);
        }

        switch (market) {
            case "SH":
                if (code.length() == 6) {
                    return Integer.valueOf(code);
                }
                break;

            case "SZ":
                if (code.length() == 6) {
                    return Integer.valueOf("1" + code);
                }
                break;

            case "BJ":
                if (code.length() == 6) {
                    return Integer.valueOf("1" + code);
                }
                break;
        }

        throw new IllegalArgumentException("无法将 tsCode " + tsCode + " 转换为 goodsId");
    }

}
