shinnosuke
2026-08-26 6a972c54fe99a186b5885db1b1319643ce9679dd
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package com.talentcard.server.business.portal;
 
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
 
import com.alibaba.fastjson.JSON;
import com.talentcard.server.business.DatabaseRows;
import com.talentcard.server.common.BusinessException;
import com.talentcard.server.common.ErrorCode;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
@Service
public class ChildrenEntrustmentPortalService {
 
    private final JdbcTemplate jdbc;
 
    public ChildrenEntrustmentPortalService(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> detail(Long serviceId, Long talentId) {
        Map<String, Object> merchant = approvalService(serviceId);
        Map<String, Object> benefit = benefit();
        boolean available = number(benefit.get("enabled")) == 1;
        Map<String, Object> matchedRight = matchedRight(merchant.get("merchantRightsConfig"), activeCardLevel(talentId));
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("benefitId", benefit.get("id"));
        result.put("serviceId", serviceId);
        result.put("title", benefit.get("title"));
        result.put("applicableCards", text(matchedRight.get("tag"), ""));
        result.put("heroImage", benefit.get("heroImage"));
        result.put("rightsText", text(matchedRight.get("detail"), text(benefit.get("rightsText"), "暂无使用说明")));
        result.put("available", available);
        result.put("unavailableReason", available ? "" : text(benefit.get("unavailableReason"), "该权益暂未开放"));
        return result;
    }
 
    @Transactional(readOnly = true)
    public List<Map<String, Object>> schools(Long serviceId) {
        Map<String, Object> merchant = approvalService(serviceId);
        List<Map<String, Object>> configuredSchools = configuredSchools(merchant.get("usageInstructions"));
        if (!configuredSchools.isEmpty()) return configuredSchools;
        Map<String, Object> benefit = benefit();
        return query("""
                select id, school_name, address, latitude, longitude, contact_mobile, detail_available
                from children_entrustment_school
                where benefit_id = ? and enabled = 1 and deleted = 0
                order by sort_no asc, id asc
                """, benefit.get("id")).stream().map(row -> {
            Map<String, Object> school = new LinkedHashMap<>();
            school.put("id", row.get("id"));
            school.put("name", row.get("schoolName"));
            school.put("address", text(row.get("address"), "暂未配置学校地址"));
            school.put("latitude", row.get("latitude"));
            school.put("longitude", row.get("longitude"));
            school.put("phone", text(row.get("contactMobile"), ""));
            school.put("detailAvailable", number(row.get("detailAvailable")) == 1);
            return school;
                }).toList();
    }
 
    private List<Map<String, Object>> configuredSchools(Object value) {
        return configuredSchoolRows(value).stream().map(row -> {
            Map<String, Object> school = new LinkedHashMap<>();
            school.put("id", row.get("id"));
            school.put("name", row.get("name"));
            school.put("address", row.get("address"));
            school.put("latitude", row.get("latitude"));
            school.put("longitude", row.get("longitude"));
            school.put("phone", row.get("phone"));
            school.put("detailAvailable", row.get("detailAvailable"));
            return school;
        }).toList();
    }
 
    private List<Map<String, Object>> configuredSchoolRows(Object value) {
        String json = text(value, "");
        if (json.isBlank()) return List.of();
        try {
            List<Map<String, Object>> rows = JSON.parseObject(json, new com.alibaba.fastjson.TypeReference<>() {});
            if (rows == null) return List.of();
            return rows.stream().map(row -> {
                Map<String, Object> school = new LinkedHashMap<>();
                String name = text(row.get("name"), "未命名学校");
                school.put("id", text(row.get("id"), name));
                school.put("name", name);
                school.put("address", text(row.get("address"), "暂未配置学校地址"));
                school.put("latitude", row.get("latitude"));
                school.put("longitude", row.get("longitude"));
                school.put("phone", text(row.get("phone"), text(row.get("contactMobile"), "")));
                String content = text(row.get("detail"), "");
                school.put("content", content);
                school.put("detailAvailable", !content.isBlank());
                return school;
            }).toList();
        } catch (RuntimeException ignored) {
            return List.of();
        }
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> school(Long serviceId, String schoolId) {
        if (schoolId == null || schoolId.isBlank()) throw new BusinessException(ErrorCode.BAD_REQUEST, "学校信息不能为空");
        Map<String, Object> merchant = approvalService(serviceId);
        List<Map<String, Object>> configuredSchools = configuredSchoolRows(merchant.get("usageInstructions"));
        if (!configuredSchools.isEmpty()) {
            Map<String, Object> matched = configuredSchools.stream()
                    .filter(row -> schoolId.equals(text(row.get("id"), "")) || schoolId.equals(text(row.get("name"), "")))
                    .findFirst()
                    .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND, "学校不存在或暂未开放"));
            if (!booleanValue(matched.get("detailAvailable"))) throw new BusinessException(ErrorCode.CONFLICT, "学校介绍暂未开放");
            Map<String, Object> result = new LinkedHashMap<>();
            result.put("id", matched.get("id"));
            result.put("name", matched.get("name"));
            result.put("address", matched.get("address"));
            result.put("content", matched.get("content"));
            return result;
        }
        try {
            return school(Long.parseLong(schoolId));
        } catch (NumberFormatException exception) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "学校不存在或暂未开放");
        }
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> school(Long schoolId) {
        if (schoolId == null || schoolId <= 0) throw new BusinessException(ErrorCode.BAD_REQUEST, "学校信息不能为空");
        List<Map<String, Object>> rows = query("""
                select id, school_name, address, detail_content, detail_available
                from children_entrustment_school
                where id = ? and enabled = 1 and deleted = 0
                limit 1
                """, schoolId);
        if (rows.isEmpty()) throw new BusinessException(ErrorCode.NOT_FOUND, "学校不存在或暂未开放");
        Map<String, Object> row = rows.get(0);
        if (number(row.get("detailAvailable")) != 1) throw new BusinessException(ErrorCode.CONFLICT, "学校介绍暂未开放");
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("id", row.get("id"));
        result.put("name", row.get("schoolName"));
        result.put("address", text(row.get("address"), "暂未配置学校地址"));
        result.put("content", text(row.get("detailContent"), ""));
        return result;
    }
 
    private Map<String, Object> approvalService(Long serviceId) {
        if (serviceId == null || serviceId <= 0) throw new BusinessException(ErrorCode.BAD_REQUEST, "学生托付服务信息不能为空");
        List<Map<String, Object>> rows = query("""
                select m.id, m.merchant_rights_config, m.usage_instructions
                from merchant m
                where m.id = ? and m.deleted = 0 and m.merchant_type_code = 'children'
                """, serviceId);
        if (rows.isEmpty()) throw new BusinessException(ErrorCode.NOT_FOUND, "学生托付服务不存在");
        return rows.get(0);
    }
 
    private Map<String, Object> matchedRight(Object value, String cardLevel) {
        if (cardLevel.isBlank() || value == null) return Map.of();
        try {
            List<Map<String, Object>> rights = JSON.parseObject(String.valueOf(value), new com.alibaba.fastjson.TypeReference<>() {});
            if (rights != null) {
                for (Map<String, Object> right : rights) {
                    if (booleanValue(right.get("enabled")) && cardLevel.equals(text(right.get("level"), ""))) return right;
                }
            }
        } catch (RuntimeException ignored) {
            // Fall back to the legacy children entrustment description when the configuration is invalid.
        }
        return Map.of();
    }
 
    private String activeCardLevel(Long talentId) {
        if (talentId == null || talentId <= 0) return "";
        List<Map<String, Object>> cards = query("""
                select card_level from talent_card
                where talent_id = ? and deleted = 0 and card_type = 'PERSONAL' and status = 1
                  and (valid_end is null or valid_end >= current_date)
                order by id desc limit 1
                """, talentId);
        return cards.isEmpty() ? "" : text(cards.get(0).get("cardLevel"), "");
    }
 
    private boolean booleanValue(Object value) {
        if (value instanceof Boolean bool) return bool;
        if (value instanceof Number number) return number.intValue() != 0;
        String result = text(value, "");
        return "true".equalsIgnoreCase(result) || "1".equals(result) || "yes".equalsIgnoreCase(result);
    }
 
    private Map<String, Object> benefit() {
        List<Map<String, Object>> rows = query("""
                select id, title, applicable_cards, hero_image, rights_text, enabled, unavailable_reason
                from children_entrustment_benefit where deleted = 0
                order by id asc limit 1
                """);
        if (rows.isEmpty()) throw new BusinessException(ErrorCode.NOT_FOUND, "学生托付权益暂未配置");
        return rows.get(0);
    }
 
    private List<Map<String, Object>> query(String sql, Object... args) {
        return DatabaseRows.normalize(jdbc.queryForList(sql, args));
    }
 
    private int number(Object value) {
        return value instanceof Number number ? number.intValue() : Integer.parseInt(String.valueOf(value));
    }
 
    private String text(Object value, String fallback) {
        String result = value == null ? "" : String.valueOf(value).trim();
        return result.isBlank() ? fallback : result;
    }
}