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

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.openstats.constant.OpenStatsConstants;

/**
 * 从 consignee_address 提取地级市名称
 */
public final class AddressCityParser
{
    private static final Pattern AFTER_PROVINCE_CITY = Pattern.compile(
            "(?:省|自治区|特别行政区)([^市]+市|.+?自治州|.+?地区|.+?盟)");

    private static final Pattern LEADING_CITY = Pattern.compile(
            "^([^市]+市|.+?自治州|.+?地区|.+?盟)");

    private AddressCityParser()
    {
    }

    public static String parseCity(String consigneeAddress)
    {
        if (StringUtils.isEmpty(consigneeAddress))
        {
            return OpenStatsConstants.UNKNOWN_CITY;
        }
        String regionPart = consigneeAddress.trim();
        int spaceIdx = regionPart.indexOf(' ');
        if (spaceIdx > 0)
        {
            regionPart = regionPart.substring(0, spaceIdx).trim();
        }
        regionPart = regionPart.replace("/", "");
        if (StringUtils.isEmpty(regionPart))
        {
            return OpenStatsConstants.UNKNOWN_CITY;
        }
        Matcher afterProvince = AFTER_PROVINCE_CITY.matcher(regionPart);
        if (afterProvince.find())
        {
            return afterProvince.group(1);
        }
        Matcher leading = LEADING_CITY.matcher(regionPart);
        if (leading.find())
        {
            return leading.group(1);
        }
        return OpenStatsConstants.UNKNOWN_CITY;
    }
}
