package com.xiaopeng.order.utils;
|
|
import com.xiaopeng.common.core.utils.StringUtils;
|
|
import java.util.Objects;
|
import java.util.Optional;
|
|
public final class RegionCodeFilterUtil {
|
|
private RegionCodeFilterUtil() {
|
}
|
|
public enum MatchType {
|
EQ,
|
LIKE_RIGHT
|
}
|
|
public static final class CityCodeFilter {
|
private final MatchType matchType;
|
private final String value;
|
|
private CityCodeFilter(MatchType matchType, String value) {
|
this.matchType = matchType;
|
this.value = value;
|
}
|
|
public MatchType getMatchType() {
|
return matchType;
|
}
|
|
public String getValue() {
|
return value;
|
}
|
}
|
|
public static Optional<CityCodeFilter> resolveCityCodeFilter(String cityCode) {
|
if (StringUtils.isBlank(cityCode)) {
|
return Optional.empty();
|
}
|
|
String trimmed = cityCode.trim();
|
if (StringUtils.isBlank(trimmed)) {
|
return Optional.empty();
|
}
|
|
if (trimmed.length() == 6) {
|
if (trimmed.endsWith("0000")) {
|
return Optional.of(new CityCodeFilter(MatchType.LIKE_RIGHT, safeSubstring(trimmed, 0, 2)));
|
}
|
if (trimmed.endsWith("00")) {
|
return Optional.of(new CityCodeFilter(MatchType.LIKE_RIGHT, safeSubstring(trimmed, 0, 4)));
|
}
|
return Optional.of(new CityCodeFilter(MatchType.EQ, trimmed));
|
}
|
|
if (trimmed.length() == 2 || trimmed.length() == 4) {
|
return Optional.of(new CityCodeFilter(MatchType.LIKE_RIGHT, trimmed));
|
}
|
|
return Optional.of(new CityCodeFilter(MatchType.EQ, trimmed));
|
}
|
|
private static String safeSubstring(String str, int start, int end) {
|
if (StringUtils.isBlank(str)) {
|
return "";
|
}
|
int safeStart = Math.max(0, start);
|
int safeEnd = Math.min(str.length(), end);
|
if (safeStart >= safeEnd) {
|
return "";
|
}
|
return Objects.toString(str.substring(safeStart, safeEnd), "");
|
}
|
}
|