“mitao”
2026-03-09 70beeda88720131e21baf4c51fd20d5bf486959a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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), "");
    }
}