shinnosuke
2026-09-11 b36f4c2800e88f8c5060ae926d3eb25d4bcb69c0
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
package com.talentcard.server.business.portal;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Locale;
 
import com.talentcard.server.business.DatabaseRows;
import com.talentcard.server.business.PageResult;
import com.talentcard.server.business.merchant.MerchantTypeCatalog;
import com.talentcard.server.business.merchant.MerchantTypeCatalog.MerchantType;
import com.talentcard.server.common.BusinessException;
import com.talentcard.server.common.ErrorCode;
import org.jsoup.Jsoup;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.ObjectMapper;
 
@Service
public class PortalService {
 
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private final JdbcTemplate jdbcTemplate;
 
    public PortalService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> home(Long talentId) {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("notices", query("""
                select id, title, content, notice_type, created_at
                from notice_message
                where receiver_type = 'TALENT'
                order by created_at desc
                limit 3
                """));
        result.put("news", query("""
                select id, title, summary, cover_url, source, view_count, is_top, publish_time
                from news_article
                where deleted = 0 and status = 1
                order by is_top desc, case when is_top = 1 then updated_at end desc, publish_time desc, id desc
                limit 4
                """));
        result.put("policies", query("""
                select id, policy_no, title, subtitle, cover_url, is_top, publish_time
                from policy_article
                where deleted = 0 and status = 1
                order by is_top desc, sort_no desc, publish_time desc, id desc
                limit 5
                """));
        result.put("benefits", query("""
                select id, benefit_name, benefit_type, cover_url, description
                from benefit
                where deleted = 0 and status = 1
                order by sort_no desc, id desc
                limit 8
                """));
        result.put("recommendedMerchants", query("""
                select id, merchant_name, merchant_type_code as merchant_type, logo_url, cover_url, address
                from merchant
                where deleted = 0 and status = 1 and is_recommend = 1
                order by sort_no desc, id desc
                limit 6
                """));
        Map<String, Object> homeSettings = new LinkedHashMap<>();
        for (Map<String, Object> row : query("""
                select setting_key, setting_value from admin_setting
                where setting_key in ('homeVideoUrl', 'miniProgramUrl')
                """)) {
            homeSettings.put(String.valueOf(row.get("settingKey")), row.get("settingValue"));
        }
        result.put("homeVideoUrl", String.valueOf(homeSettings.getOrDefault("homeVideoUrl", "")));
        result.put("miniProgramUrl", String.valueOf(homeSettings.getOrDefault("miniProgramUrl", "")));
        if (talentId != null) {
            result.put("cards", query("""
                    select id, talent_id, card_no, card_type, card_level, valid_start, valid_end, status
                    from talent_card
                    where deleted = 0 and talent_id = ?
                    order by id desc
                    """, talentId));
        }
        return result;
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> news(int page, int size) {
        PageResult<Map<String, Object>> result = page("""
                select id, title, summary, cover_url, source, content, view_count, is_top, publish_time
                from news_article
                where deleted = 0 and status = 1
                order by is_top desc, case when is_top = 1 then updated_at end desc, publish_time desc, id desc
                """, "select count(*) from news_article where deleted = 0 and status = 1", page, size);
        List<Map<String, Object>> records = result.records().stream().map(row -> {
            Map<String, Object> item = new LinkedHashMap<>(row);
            item.put("contentPreview", htmlToText((String) item.get("content")));
            item.remove("content");
            return item;
        }).toList();
        return new PageResult<>(records, result.page(), result.size(), result.total());
    }
 
    @Transactional
    public Map<String, Object> newsDetail(Long id) {
        int updated = jdbcTemplate.update("update news_article set view_count = view_count + 1 where id = ? and deleted = 0 and status = 1", id);
        if (updated == 0) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "资讯不存在");
        }
        return one("""
                select id, title, summary, cover_url, source, author, content, view_count, is_top, publish_time
                from news_article
                where deleted = 0 and status = 1 and id = ?
                """, id);
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> policies(int page, int size) {
        PageResult<Map<String, Object>> result = page("""
                select id, policy_no, title, subtitle, category_name, cover_url, tags, author, source, content, view_count, is_top, publish_time
                from policy_article
                where deleted = 0 and status = 1
                order by is_top desc, sort_no desc, publish_time desc, id desc
                """, "select count(*) from policy_article where deleted = 0 and status = 1", page, size);
        List<Map<String, Object>> records = result.records().stream().map(row -> {
            Map<String, Object> item = new LinkedHashMap<>(row);
            item.put("contentPreview", htmlToText((String) item.get("content")));
            item.remove("content");
            return item;
        }).toList();
        return new PageResult<>(records, result.page(), result.size(), result.total());
    }
 
    @Transactional
    public Map<String, Object> policy(Long id) {
        int updated = jdbcTemplate.update("update policy_article set view_count = view_count + 1 where id = ? and deleted = 0 and status = 1", id);
        if (updated == 0) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "政策已下架或不存在");
        }
        Map<String, Object> policy = one("""
                select id, policy_no, title, subtitle, category_name, cover_url, content_images, tags, author, source, content, view_count, publish_time
                from policy_article
                where deleted = 0 and status = 1 and id = ?
                """, id);
        policy.put("categoryName", textOrDefault(policy.get("categoryName"), "东区政策"));
        policy.put("heroImage", policy.get("coverUrl"));
        policy.put("contentImages", imageUrls(policy.get("contentImages")));
        policy.put("contentText", htmlToText((String) policy.get("content")));
        return policy;
    }
 
    private String htmlToText(String content) {
        return content == null || content.isBlank() ? "" : Jsoup.parse(content).wholeText().trim();
    }
 
    private String textOrDefault(Object value, String fallback) {
        if (value == null) return fallback;
        String text = String.valueOf(value).trim();
        return text.isEmpty() ? fallback : text;
    }
 
    private List<String> imageUrls(Object value) {
        if (value == null || String.valueOf(value).isBlank()) return List.of();
        try {
            return OBJECT_MAPPER.readValue(String.valueOf(value), new TypeReference<List<String>>() {}).stream()
                    .filter(url -> url != null && !url.isBlank())
                    .toList();
        } catch (Exception ignored) {
            return List.of();
        }
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> benefits(String type, int page, int size) {
        if (type == null || type.isBlank()) {
            return page("""
                    select id, benefit_name, benefit_type, cover_url, description, valid_start, valid_end, total_quota, used_quota
                    from benefit
                    where deleted = 0 and status = 1
                    order by sort_no desc, id desc
                    """, "select count(*) from benefit where deleted = 0 and status = 1", page, size);
        }
        return page("""
                select id, benefit_name, benefit_type, cover_url, description, valid_start, valid_end, total_quota, used_quota
                from benefit
                where deleted = 0 and status = 1 and benefit_type = ?
                order by sort_no desc, id desc
                """, "select count(*) from benefit where deleted = 0 and status = 1 and benefit_type = ?", page, size, type);
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> merchants(
            String type,
            String keyword,
            String categoryId,
            String mode,
            String sortField,
            String sortOrder,
            Long talentId,
            int page,
            int size
    ) {
        String merchantWhere = " where deleted = 0 and status = 1";
        List<Object> args = new java.util.ArrayList<>();
        String requestedType = categoryId == null || categoryId.isBlank() ? type : categoryId;
        if (requestedType != null && !requestedType.isBlank() && !"all".equalsIgnoreCase(requestedType)) {
            merchantWhere = appendMerchantTypeFilter(merchantWhere, merchantTypesForRequestedValue(requestedType), args);
        }
        if (keyword != null && !keyword.isBlank()) {
            List<String> categoryTypes = merchantTypesForCategory(keyword.trim());
            if (!categoryTypes.isEmpty()) {
                merchantWhere = appendMerchantTypeFilter(merchantWhere, categoryTypes, args);
            } else {
                merchantWhere += " and (merchant_name like ? or address like ? or merchant_type like ?)";
            String like = "%" + keyword.trim() + "%";
                args.add(like);
                args.add(like);
                args.add(like);
            }
        }
        PageResult<Map<String, Object>> result = page("""
                select id, merchant_name, merchant_type_code as merchant_type, contact_name, contact_mobile, logo_url, cover_url, address,
                       is_recommend, sort_no, longitude, latitude, business_status, service_label, merchant_rights_config,
                       (exists(select 1 from merchant_coupon c
                               where c.merchant_id = merchant.id and c.deleted = 0 and c.status = 1
                                 and (c.valid_start is null or c.valid_start <= current_date)
                                 and (c.valid_end is null or c.valid_end >= current_date))
                        or (merchant.merchant_type_code = 'cinema' and exists(select 1 from ticket_package tp
                               where tp.deleted = 0 and tp.status = 1
                                 and (tp.valid_start is null or tp.valid_start <= current_date)
                                 and (tp.valid_end is null or tp.valid_end >= current_date)
                                 and (tp.merchant_id = merchant.id or exists (
                                     select 1 from ticket_package_merchant tpm
                                     where tpm.package_id = tp.id and tpm.merchant_id = merchant.id and tpm.deleted = 0
                                 ))))) as coupon_available,
                       (select min(p.sale_price) from merchant_product p where p.merchant_id = merchant.id and p.deleted = 0 and p.status = 1 and p.audit_status = 2) as sale_price,
                       (select min(p.original_price) from merchant_product p where p.merchant_id = merchant.id and p.deleted = 0 and p.status = 1 and p.audit_status = 2) as original_price
                from merchant
                """ + merchantWhere + " order by sort_no asc, id asc",
                "select count(*) from merchant" + merchantWhere, page, size, args.toArray());
        List<Map<String, Object>> records = result.records().stream().map(row -> {
            Map<String, Object> item = enrichMerchantSearchRow(row);
            Long merchantId = item.get("id") instanceof Number id ? id.longValue() : null;
            item.put("couponAvailable", booleanValue(row.get("couponAvailable")));
            item.put("discountText", merchantId == null ? "" : merchantLowestTalentDiscount(merchantId, talentId));
            item.put("benefitTags", merchantListBenefitTags(item, row, talentId));
            item.remove("merchantRightsConfig");
            return item;
        }).toList();
        return new PageResult<>(records, result.page(), result.size(), result.total());
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> foodTopic() {
        Map<String, Object> topic = one("""
                select category_key, category_label, intro
                from equity_image_category
                where category_key = 'food'
                """);
        topic.put("description", topic.get("intro"));
        topic.put("images", query("""
                select id, item_name as name, image_url, sort_no
                from equity_image_item
                where category_key = 'food' and deleted = 0 and enabled = 1
                order by sort_no asc, id asc
                """));
        return topic;
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> foodMerchants(int page, int size, Long talentId) {
        String merchantWhere = " where deleted = 0 and merchant_type_code = 'food'";
        PageResult<Map<String, Object>> result = page("""
                select id, merchant_name, merchant_type_code as merchant_type, contact_name, contact_mobile, logo_url, cover_url, address,
                       status, sort_no, longitude, latitude, business_status,
                       (select min(p.sale_price) from merchant_product p where p.merchant_id = merchant.id and p.deleted = 0 and p.status = 1 and p.audit_status = 2) as sale_price,
                       (select min(p.original_price) from merchant_product p where p.merchant_id = merchant.id and p.deleted = 0 and p.status = 1 and p.audit_status = 2) as original_price
                from merchant
                """ + merchantWhere + " order by sort_no asc, id asc",
                "select count(*) from merchant" + merchantWhere, page, size);
        List<Map<String, Object>> records = result.records().stream().map(row -> {
            Map<String, Object> item = enrichMerchantSearchRow(row);
            Long merchantId = item.get("id") instanceof Number id ? id.longValue() : null;
            boolean couponAvailable = merchantId != null && hasActiveMerchantCoupon(merchantId);
            String discountText = merchantId == null ? "" : merchantLowestTalentDiscount(merchantId, talentId);
            item.put("couponAvailable", couponAvailable);
            item.put("discountText", discountText);
            item.put("benefitTags", merchantBenefitTags("food", couponAvailable, discountText, null));
            return item;
        }).toList();
        return new PageResult<>(records, result.page(), result.size(), result.total());
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> travelTopic() {
        Map<String, Object> topic = one("""
                select category_key, category_label, intro
                from equity_image_category
                where category_key = 'city'
                """);
        topic.put("description", topic.get("intro"));
        topic.put("images", query("""
                select id, item_name as name, image_url, sort_no
                from equity_image_item
                where category_key = 'city' and deleted = 0 and enabled = 1
                order by sort_no asc, id asc
                """));
        return topic;
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> travelMerchants(int page, int size) {
        return travelMerchants(page, size, null);
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> travelMerchants(int page, int size, Long talentId) {
        String merchantWhere = " where deleted = 0 and merchant_type_code = 'scenic'";
        PageResult<Map<String, Object>> result = page("""
                select id, merchant_name, merchant_type_code as merchant_type, contact_name, contact_mobile, logo_url, cover_url, address,
                       status, sort_no, longitude, latitude, business_status,
                       (select min(p.sale_price) from merchant_product p where p.merchant_id = merchant.id and p.deleted = 0 and p.status = 1 and p.audit_status = 2) as sale_price,
                       (select min(p.original_price) from merchant_product p where p.merchant_id = merchant.id and p.deleted = 0 and p.status = 1 and p.audit_status = 2) as original_price
                from merchant
                """ + merchantWhere + " order by sort_no asc, id asc",
                "select count(*) from merchant" + merchantWhere, page, size);
        List<Map<String, Object>> records = result.records().stream().map(row -> {
            Map<String, Object> item = enrichMerchantSearchRow(row);
            item.put("merchantType", "scenic");
            Long merchantId = item.get("id") instanceof Number id ? id.longValue() : null;
            boolean couponAvailable = merchantId != null && hasActiveMerchantCoupon(merchantId);
            String discountText = merchantId == null ? "" : merchantLowestTalentDiscount(merchantId, talentId);
            item.put("couponAvailable", couponAvailable);
            item.put("discountText", discountText);
            item.put("benefitTags", merchantBenefitTags("scenic", couponAvailable, discountText, null));
            return item;
        }).toList();
        return new PageResult<>(records, result.page(), result.size(), result.total());
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> stayTopic() {
        Map<String, Object> topic = one("""
                select category_key, category_label, intro
                from equity_image_category
                where category_key = 'home'
                """);
        topic.put("description", topic.get("intro"));
        topic.put("images", query("""
                select id, item_name as name, image_url, sort_no
                from equity_image_item
                where category_key = 'home' and deleted = 0 and enabled = 1
                order by sort_no asc, id asc
                """));
        return topic;
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> stayMerchants(String type, int page, int size) {
        return stayMerchants(type, page, size, null);
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> stayMerchants(String type, int page, int size, Long talentId) {
        String requestedType = MerchantTypeCatalog.canonicalCode(type);
        boolean apartment = switch (requestedType) {
            case "hotel" -> false;
            case "apartment" -> true;
            default -> throw new BusinessException(ErrorCode.BAD_REQUEST, "不支持的住宿服务类型");
        };
        String responseMerchantType = apartment ? "apartment" : "hotel";
        String merchantWhere = " where deleted = 0 and merchant_type_code = '" + responseMerchantType + "'";
        PageResult<Map<String, Object>> result = page("""
                select id, merchant_name, merchant_type_code as merchant_type, contact_name, contact_mobile, logo_url, cover_url, address,
                       status, sort_no, longitude, latitude, business_status, group_buying_enabled, merchant_rights_config,
                       (select min(p.sale_price) from merchant_product p where p.merchant_id = merchant.id and p.deleted = 0 and p.status = 1 and p.audit_status = 2) as sale_price,
                       (select min(p.original_price) from merchant_product p where p.merchant_id = merchant.id and p.deleted = 0 and p.status = 1 and p.audit_status = 2) as original_price
                from merchant
                """ + merchantWhere + " order by sort_no asc, id asc",
                "select count(*) from merchant" + merchantWhere, page, size);
        List<Map<String, Object>> records = result.records().stream().map(row -> {
            Map<String, Object> item = enrichMerchantSearchRow(row);
            item.put("merchantType", responseMerchantType);
            Long merchantId = item.get("id") instanceof Number id ? id.longValue() : null;
            boolean couponAvailable = merchantId != null && hasActiveMerchantCoupon(merchantId);
            String discountText = merchantId == null ? "" : merchantLowestTalentDiscount(merchantId, talentId);
            Map<String, Object> right = matchingMerchantRight(
                    merchantRightsConfigs(row.get("merchantRightsConfig")),
                    activeProductCardLevel(talentId),
                    activeTalentSourceAreaType(talentId),
                    true);
            item.put("couponAvailable", couponAvailable);
            item.put("discountText", discountText);
            item.put("benefitTags", merchantBenefitTags(responseMerchantType, couponAvailable, discountText, right));
            item.remove("merchantRightsConfig");
            return item;
        }).toList();
        return new PageResult<>(records, result.page(), result.size(), result.total());
    }
 
    private List<String> merchantListBenefitTags(Map<String, Object> item, Map<String, Object> row, Long talentId) {
        String merchantType = MerchantTypeCatalog.canonicalCode(textOrDefault(item.get("merchantType"), ""));
        boolean couponAvailable = booleanValue(item.get("couponAvailable"));
        String discountText = textOrDefault(item.get("discountText"), "").trim();
        String cardLevel = activeProductCardLevel(talentId);
        String sourceAreaType = activeTalentSourceAreaType(talentId);
        Map<String, Object> right = matchingMerchantRight(
                merchantRightsConfigs(row.get("merchantRightsConfig")), cardLevel, sourceAreaType, true);
        if (usesMerchantDetailHeaderTags(merchantType) || "cinema".equals(merchantType)) {
            return merchantBenefitTags(merchantType, couponAvailable, discountText, right);
        }
 
        boolean shoppingType = MerchantTypeCatalog.find(merchantType)
                .map(type -> type.shoppingCategoryKey() != null)
                .orElse(false);
        if (shoppingType) {
            List<String> tags = new ArrayList<>();
            if (couponAvailable) tags.add("券");
            if (right != null) {
                String configuredDiscount = merchantRightDiscountText(right);
                if (!configuredDiscount.isBlank()) tags.add(configuredDiscount);
            }
            return tags;
        }
 
        String serviceLabel = textOrDefault(row.get("serviceLabel"), "").trim();
        String categoryTag = !serviceLabel.isBlank() ? serviceLabel : discountText;
        if (categoryTag.isBlank()) categoryTag = "人才专享";
        return List.of(categoryTag);
    }
 
    private boolean usesMerchantDetailHeaderTags(String merchantType) {
        return List.of("food", "scenic", "hotel", "apartment", "dental", "culture").contains(merchantType);
    }
 
    private List<String> merchantBenefitTags(
            String merchantType,
            boolean couponAvailable,
            String productDiscountText,
            Map<String, Object> right
    ) {
        String type = MerchantTypeCatalog.canonicalCode(merchantType);
        if ("cinema".equals(type)) {
            return couponAvailable ? List.of("券") : List.of();
        }
        List<String> tags = new ArrayList<>();
        if (couponAvailable) tags.add("券");
        String discount = textOrDefault(productDiscountText, "").trim();
        if ("人才专享".equals(discount)) discount = "";
        boolean hotelLike = "hotel".equals(type) || "apartment".equals(type);
        if (hotelLike && right != null && booleanValue(right.get("freeVoucherEnabled"))) {
            String times = textOrDefault(right.get("freeVoucherTimes"), "").trim();
            discount = times.isBlank() ? "免费" : "免费" + times + "次";
        }
        if (!discount.isBlank() && !tags.contains(discount)) tags.add(discount);
        if (hotelLike && right != null && booleanValue(right.get("storeConsume")) && booleanValue(right.get("consumeEnabled"))) {
            String consumeType = textOrDefault(right.get("consumeType"), "");
            String consumeDiscount = textOrDefault(right.get("consumeDiscount"), "").trim();
            String consumeCoupon = textOrDefault(right.get("consumeCoupon"), "").trim();
            String consumeTag = "";
            if ("折扣".equals(consumeType) && !consumeDiscount.isBlank()) consumeTag = consumeDiscount + "折";
            else if ("优惠".equals(consumeType) && !consumeCoupon.isBlank()) consumeTag = "减" + consumeCoupon;
            if (!consumeTag.isBlank() && !tags.contains(consumeTag)) tags.add(consumeTag);
        }
        return tags;
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> entertainmentTopic() {
        Map<String, Object> topic = one("""
                select category_key, category_label, intro
                from equity_image_category
                where category_key = 'entertainment'
                """);
        topic.put("description", topic.get("intro"));
        topic.put("images", query("""
                select id, item_name as name, image_url, sort_no
                from equity_image_item
                where category_key = 'entertainment' and deleted = 0 and enabled = 1
                order by sort_no asc, id asc
                """));
        return topic;
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> entertainmentMerchants(int page, int size) {
        String merchantWhere = " where deleted = 0 and merchant_type_code = 'cinema'";
        PageResult<Map<String, Object>> result = page("""
                select id, merchant_name, merchant_type_code as merchant_type, contact_name, contact_mobile, logo_url, cover_url, address,
                       service_label, status, sort_no, longitude, latitude, business_status,
                       (exists(select 1 from merchant_coupon c
                               where c.merchant_id = merchant.id and c.deleted = 0 and c.status = 1
                                 and (c.valid_start is null or c.valid_start <= current_date)
                                 and (c.valid_end is null or c.valid_end >= current_date))
                        or exists(select 1 from ticket_package p
                                  where p.deleted = 0 and p.status = 1
                                    and (p.valid_start is null or p.valid_start <= current_date)
                                    and (p.valid_end is null or p.valid_end >= current_date)
                                    and (p.merchant_id = merchant.id or exists (
                                        select 1 from ticket_package_merchant pm
                                        where pm.package_id = p.id and pm.merchant_id = merchant.id and pm.deleted = 0
                                    )))) as coupon_available,
                       (select min(p.sale_price) from merchant_product p where p.merchant_id = merchant.id and p.deleted = 0 and p.status = 1 and p.audit_status = 2) as sale_price,
                       (select min(p.original_price) from merchant_product p where p.merchant_id = merchant.id and p.deleted = 0 and p.status = 1 and p.audit_status = 2) as original_price
                from merchant
                """ + merchantWhere + " order by sort_no asc, id asc",
                "select count(*) from merchant" + merchantWhere, page, size);
        List<Map<String, Object>> records = result.records().stream().map(row -> {
            Map<String, Object> item = enrichMerchantSearchRow(row);
            boolean couponAvailable = booleanValue(item.get("couponAvailable"));
            item.put("couponAvailable", couponAvailable);
            item.put("discountText", couponAvailable ? "券" : "");
            item.put("benefitTags", merchantBenefitTags("cinema", couponAvailable, "", null));
            return item;
        }).toList();
        return new PageResult<>(records, result.page(), result.size(), result.total());
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> transportTopic() {
        Map<String, Object> topic = one("""
                select category_key, category_label, intro
                from equity_image_category
                where category_key = 'transport'
                """);
        topic.put("title", topic.get("categoryLabel"));
        topic.put("themeColor", "#F26A38");
        topic.put("description", topic.get("intro"));
        topic.put("images", query("""
                select id, item_name as name, image_url, sort_no
                from equity_image_item
                where category_key = 'transport' and deleted = 0 and enabled = 1
                order by sort_no asc, id asc
                """));
        return topic;
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> transportMerchants(String type, int page, int size, Long talentId) {
        String requestedType = MerchantTypeCatalog.canonicalCode(type);
        if (!List.of("fuel", "parking", "carWash").contains(requestedType)) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "不支持的行服务类型");
        }
        String merchantWhere = " where deleted = 0 and merchant_type_code = '" + requestedType + "'";
        PageResult<Map<String, Object>> result = page("""
                select id, merchant_name, merchant_type_code as merchant_type, contact_name, contact_mobile, logo_url, cover_url, address,
                       service_label, status, sort_no, longitude, latitude, business_status, merchant_rights_config,
                       (select min(p.sale_price) from merchant_product p where p.merchant_id = merchant.id and p.deleted = 0 and p.status = 1 and p.audit_status = 2) as sale_price,
                       (select min(p.original_price) from merchant_product p where p.merchant_id = merchant.id and p.deleted = 0 and p.status = 1 and p.audit_status = 2) as original_price
                from merchant
                """ + merchantWhere + " order by sort_no asc, id asc",
                "select count(*) from merchant" + merchantWhere, page, size);
        String cardLevel = "carWash".equals(requestedType) ? activeProductCardLevel(talentId) : null;
        String sourceAreaType = "carWash".equals(requestedType) ? activeTalentSourceAreaType(talentId) : "";
        List<Map<String, Object>> records = result.records().stream().map(row -> {
            Map<String, Object> item = enrichMerchantSearchRow(row);
            item.put("merchantType", requestedType);
            if ("carWash".equals(requestedType)) {
                List<Map<String, Object>> rights = merchantRightsConfigs(item.get("merchantRightsConfig"));
                String externalLinkType = carWashExternalLinkType(rights);
                Map<String, Object> right = matchingMerchantRight(rights, cardLevel, sourceAreaType, true);
                String discountText = carWashListDiscountText(externalLinkType, right);
                item.put("externalLinkType", externalLinkType);
                item.put("discountText", discountText);
                item.put("benefitTagVisible", !discountText.isBlank());
            } else {
                item.put("discountText", textOrDefault(item.get("serviceLabel"), textOrDefault(item.get("discountText"), "人才专享")));
            }
            item.remove("merchantRightsConfig");
            return item;
        }).toList();
        return new PageResult<>(records, result.page(), result.size(), result.total());
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> shoppingTopic() {
        Map<String, Object> topic = one("""
                select category_key, category_label, intro
                from equity_image_category
                where category_key = 'shopping'
                """);
        topic.put("title", topic.get("categoryLabel"));
        topic.put("description", topic.get("intro"));
        topic.put("images", query("""
                select id, item_name as name, image_url, sort_no
                from equity_image_item
                where category_key = 'shopping' and deleted = 0 and enabled = 1
                order by sort_no asc, id asc
                """));
        topic.put("categories", query("""
                select category_key as id, category_name as name, sort_no
                from shopping_topic_category
                where deleted = 0 and enabled = 1
                order by sort_no asc, id asc
                """));
        return topic;
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> shoppingMerchants(String categoryId, int page, int size) {
        return shoppingMerchants(categoryId, page, size, null);
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> shoppingMerchants(String categoryId, int page, int size, Long talentId) {
        if (categoryId == null || categoryId.isBlank()) throw new BusinessException(ErrorCode.BAD_REQUEST, "请选择购物服务分类");
        int categoryCount = jdbcTemplate.queryForObject("""
                select count(*) from shopping_topic_category
                where category_key = ? and enabled = 1 and deleted = 0
                """, Integer.class, categoryId);
        if (categoryCount == 0) throw new BusinessException(ErrorCode.BAD_REQUEST, "不支持的购物服务分类");
        List<String> merchantTypeCodes = MerchantTypeCatalog.codesForShoppingCategory(categoryId);
        if (merchantTypeCodes.isEmpty()) throw new BusinessException(ErrorCode.BAD_REQUEST, "该购物分类未配置商家类型");
        String placeholders = String.join(",", java.util.Collections.nCopies(merchantTypeCodes.size(), "?"));
        String merchantWhere = """
                where m.deleted = 0
                  and m.merchant_type_code in (%s)
                """.formatted(placeholders);
        List<Object> args = new ArrayList<>();
        args.add(categoryId);
        args.addAll(merchantTypeCodes);
        PageResult<Map<String, Object>> result = page("""
                select m.id, m.merchant_name, m.merchant_type_code as merchant_type, m.contact_name, m.contact_mobile, m.logo_url, m.cover_url, m.address,
                       m.service_label, m.status, m.sort_no, m.longitude, m.latitude, m.business_status, m.merchant_rights_config
                from merchant m
                left join shopping_topic_merchant mapping on mapping.merchant_id = m.id and mapping.deleted = 0 and mapping.category_key = ?
                """ + merchantWhere + " order by mapping.sort_no asc, m.sort_no asc, m.id asc",
                "select count(*) from merchant m left join shopping_topic_merchant mapping on mapping.merchant_id = m.id and mapping.deleted = 0 and mapping.category_key = ? " + merchantWhere,
                page, size, args.toArray());
        String cardLevel = activeProductCardLevel(talentId);
        String sourceAreaType = activeTalentSourceAreaType(talentId);
        List<Map<String, Object>> records = result.records().stream().map(row -> {
            Map<String, Object> item = enrichMerchantSearchRow(row);
            List<Map<String, Object>> rights = merchantRightsConfigs(row.get("merchantRightsConfig"));
            Map<String, Object> configuredRight = matchingMerchantRight(rights, cardLevel, sourceAreaType, true);
            Map<String, Object> levelRight = matchingMerchantRight(rights, cardLevel, sourceAreaType, false);
            Long merchantId = row.get("id") instanceof Number number ? number.longValue() : null;
            item.put("couponAvailable", merchantId != null && hasActiveMerchantCoupon(merchantId));
            item.put("storeConsumeAvailable", configuredRight != null
                    && booleanValue(configuredRight.get("storeConsume"))
                    && booleanValue(configuredRight.get("consumeEnabled")));
            String merchantType = MerchantTypeCatalog.canonicalCode(textOrDefault(item.get("merchantType"), ""));
            boolean couponAvailable = booleanValue(item.get("couponAvailable"));
            if (configuredRight != null) {
                item.put("discountText", merchantRightDiscountText(configuredRight));
                item.put("rightsAvailable", true);
            } else if (levelRight != null || !rights.isEmpty()) {
                item.put("discountText", levelRight == null ? "" : merchantRightDiscountText(levelRight));
                item.put("rightsAvailable", false);
                item.put("available", false);
                item.put("unavailableReason", levelRight == null ? "当前人才卡暂未配置该权益" : "当前人才卡暂未开通该权益");
            } else {
                item.put("discountText", textOrDefault(item.get("serviceLabel"), ""));
                item.put("rightsAvailable", true);
            }
            if (usesMerchantDetailHeaderTags(merchantType)) {
                String productDiscount = merchantId == null ? "" : merchantLowestTalentDiscount(merchantId, talentId);
                item.put("discountText", productDiscount);
                item.put("benefitTags", merchantBenefitTags(merchantType, couponAvailable, productDiscount, configuredRight));
            } else {
                List<String> tags = new ArrayList<>();
                if (couponAvailable) tags.add("券");
                String storeDiscount = textOrDefault(item.get("discountText"), "").trim();
                if (!storeDiscount.isBlank() && !"人才专享".equals(storeDiscount)) tags.add(storeDiscount);
                item.put("benefitTags", tags);
            }
            item.remove("merchantRightsConfig");
            return item;
        }).toList();
        return new PageResult<>(records, result.page(), result.size(), result.total());
    }
 
    private String merchantRightDiscountText(Map<String, Object> right) {
        if (!booleanValue(right.get("storeConsume")) || !booleanValue(right.get("consumeEnabled"))) return "";
        String discount = textOrDefault(right.get("discount"), "").trim();
        if (discount.isBlank()) return "";
        try {
            BigDecimal value = new BigDecimal(discount).stripTrailingZeros();
            if (value.compareTo(BigDecimal.ZERO) <= 0 || value.compareTo(BigDecimal.TEN) > 0) return "";
            return value.toPlainString() + "折";
        } catch (NumberFormatException ignored) {
            return "";
        }
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> premiumTopic() {
        Map<String, Object> topic = one("""
                select category_key, category_label, intro
                from equity_image_category
                where category_key = 'premium'
                """);
        topic.put("title", topic.get("categoryLabel"));
        topic.put("description", topic.get("intro"));
        topic.put("images", query("""
                select id, item_name as name, image_url, sort_no
                from equity_image_item
                where category_key = 'premium' and deleted = 0 and enabled = 1
                order by sort_no asc, id asc
                """));
        topic.put("categories", query("""
                select category_key as id, category_name as name, business_type, sort_no
                from premium_topic_category
                where deleted = 0 and enabled = 1
                order by sort_no asc, id asc
                """));
        return topic;
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> premiumServices(String type, int page, int size) {
        String categoryId = jdbcTemplate.query("select category_key from premium_topic_category where category_name = ? and enabled = 1 and deleted = 0 limit 1", rs -> rs.next() ? rs.getString("category_key") : null, type == null ? "" : type.trim());
        if (categoryId == null || categoryId.isBlank()) throw new BusinessException(ErrorCode.BAD_REQUEST, "请选择臻享服务分类");
        Integer categoryCount = jdbcTemplate.queryForObject("""
                select count(*) from premium_topic_category
                where category_key = ? and enabled = 1 and deleted = 0
                """, Integer.class, categoryId);
        if (categoryCount == null || categoryCount == 0) throw new BusinessException(ErrorCode.BAD_REQUEST, "不支持的臻享服务分类");
        MerchantType merchantType = MerchantTypeCatalog.forPremiumCategory(categoryId)
                .orElseThrow(() -> new BusinessException(ErrorCode.BAD_REQUEST, "该臻享分类未配置商家类型"));
        String serviceWhere = " where m.deleted = 0 and m.merchant_type_code = ?";
        PageResult<Map<String, Object>> result = page("""
                select m.id, m.merchant_name, m.merchant_type_code as merchant_type, m.contact_mobile, m.cover_url, m.address,
                       m.service_label, m.status, m.sort_no, m.longitude, m.latitude,
                       mapping.sort_no as topic_sort_no
                from merchant m
                left join premium_topic_merchant mapping on mapping.merchant_id = m.id and mapping.deleted = 0 and mapping.category_key = ?
                """ + serviceWhere + " order by mapping.sort_no asc, m.sort_no asc, m.id asc",
                "select count(*) from merchant m left join premium_topic_merchant mapping on mapping.merchant_id = m.id and mapping.deleted = 0 and mapping.category_key = ? " + serviceWhere,
                page, size, categoryId, merchantType.code());
        List<Map<String, Object>> records = result.records().stream().map(row -> {
            Map<String, Object> item = enrichMerchantSearchRow(row);
            item.put("businessType", merchantType.premiumBusinessType());
            item.put("targetAction", merchantType.premiumBusinessType());
            item.put("benefitText", textOrDefault(row.get("serviceLabel"), "人才专享"));
            item.put("discountText", textOrDefault(row.get("serviceLabel"), "人才专享"));
            return item;
        }).toList();
        return new PageResult<>(records, result.page(), result.size(), result.total());
    }
 
    private Map<String, Object> enrichMerchantSearchRow(Map<String, Object> row) {
        Map<String, Object> result = new LinkedHashMap<>(row);
        String merchantType = String.valueOf(result.getOrDefault("merchantType", ""));
        result.put("categoryName", categoryName(merchantType));
        result.put("detailType", detailType(merchantType));
        result.put("detailBusinessId", result.get("id"));
        result.put("targetAction", targetAction(merchantType));
        Object status = result.get("status");
        result.put("available", !(status instanceof Number number) || number.intValue() == 1);
        result.put("sort", result.get("sortNo"));
        result.put("discountText", discountText(result.get("salePrice"), result.get("originalPrice")));
        return result;
    }
 
    private String categoryName(String merchantType) {
        return MerchantTypeCatalog.find(merchantType).map(MerchantType::topicName).orElse("其他权益");
    }
 
    private String appendMerchantTypeFilter(String merchantWhere, List<String> merchantTypes, List<Object> args) {
        if (merchantTypes.size() == 1) {
            args.add(merchantTypes.get(0));
            return merchantWhere + " and merchant_type_code = ?";
        }
        args.addAll(merchantTypes);
        String placeholders = String.join(",", Collections.nCopies(merchantTypes.size(), "?"));
        return merchantWhere + " and merchant_type_code in (" + placeholders + ")";
    }
 
    private List<String> merchantTypesForRequestedValue(String value) {
        List<String> types = MerchantTypeCatalog.codesForRequestedValue(value);
        return types.isEmpty() ? List.of("other") : types;
    }
 
    private List<String> merchantTypesForCategory(String value) {
        return MerchantTypeCatalog.codesForRequestedValue(value);
    }
 
    private String detailType(String merchantType) {
        return MerchantTypeCatalog.find(merchantType).map(MerchantType::detailType).orElse("MERCHANT");
    }
 
    private String targetAction(String merchantType) {
        return detailType(merchantType);
    }
 
    private String discountText(Object salePrice, Object originalPrice) {
        if (salePrice instanceof Number sale && originalPrice instanceof Number original
                && original.doubleValue() > 0 && sale.doubleValue() == 0) {
            return "免费";
        }
        if (salePrice instanceof Number sale && originalPrice instanceof Number original
                && sale.doubleValue() > 0 && original.doubleValue() > sale.doubleValue()) {
            double discount = Math.round(sale.doubleValue() / original.doubleValue() * 100) / 10.0;
            return discount + "折";
        }
        return "人才专享";
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> merchantDetail(Long id) {
        return merchantDetail(id, null);
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> merchantDetail(Long id, Long talentId) {
        Map<String, Object> merchant = one("""
                select id, merchant_name, merchant_type_code as merchant_type, contact_name, contact_mobile, logo_url, cover_url, address,
                       business_status, longitude, latitude, group_buying_enabled, usage_instructions, rights_text, merchant_rights_config,
                       service_label, status, is_recommend, sort_no
                from merchant
                where deleted = 0 and id = ?
                """, id);
        merchant.put("available", ((Number) merchant.getOrDefault("status", 0)).intValue() == 1);
        merchant.put("groupBuyingEnabled", ((Number) merchant.getOrDefault("groupBuyingEnabled", 1)).intValue() == 1);
        merchant.put("couponAvailable", hasActiveMerchantCoupon(id));
        merchant.put("discountText", merchantLowestTalentDiscount(id, talentId));
        String cardLevel = activeProductCardLevel(talentId);
        merchant.put("cardLevel", cardLevel);
        String sourceAreaType = activeTalentSourceAreaType(talentId);
        merchant.put("sourceAreaType", sourceAreaType);
        List<Map<String, Object>> rightsConfigs = merchantRightsConfigs(merchant.get("merchantRightsConfig"));
        Map<String, Object> configuredRight = matchingMerchantRight(rightsConfigs, cardLevel, sourceAreaType, true);
        Map<String, Object> levelRight = matchingMerchantRight(rightsConfigs, cardLevel, sourceAreaType, false);
        boolean freeVoucherEnabled = false;
        String freeVoucherTimes = "";
        String freeVoucherCycle = "";
        String consumeType = "";
        String consumeDiscount = "";
        String consumeCoupon = "";
        boolean storeConsume = false;
        boolean consumeEnabled = false;
        merchant.put("rightsAvailable", configuredRight != null);
        if (configuredRight != null) {
            merchant.put("rightsTag", textOrDefault(configuredRight.get("tag"), ""));
            merchant.put("rightsText", textOrDefault(configuredRight.get("detail"), textOrDefault(merchant.get("rightsText"), "")));
            merchant.put("applicableCards", textOrDefault(configuredRight.get("tag"), ""));
            merchant.put("rightsStatus", "AVAILABLE");
            freeVoucherEnabled = booleanValue(configuredRight.get("freeVoucherEnabled"));
            freeVoucherTimes = textOrDefault(configuredRight.get("freeVoucherTimes"), "");
            freeVoucherCycle = textOrDefault(configuredRight.get("freeVoucherCycle"), "");
            consumeType = textOrDefault(configuredRight.get("consumeType"), "");
            consumeDiscount = textOrDefault(configuredRight.get("consumeDiscount"), "");
            consumeCoupon = textOrDefault(configuredRight.get("consumeCoupon"), "");
            storeConsume = booleanValue(configuredRight.get("storeConsume"));
            consumeEnabled = booleanValue(configuredRight.get("consumeEnabled"));
        } else if (levelRight != null) {
            merchant.put("rightsTag", textOrDefault(levelRight.get("tag"), ""));
            merchant.put("rightsText", "当前人才卡暂未开通该权益");
            merchant.put("applicableCards", textOrDefault(levelRight.get("tag"), ""));
            merchant.put("rightsStatus", "DISABLED");
        } else if (!rightsConfigs.isEmpty()) {
            merchant.put("rightsTag", "");
            merchant.put("rightsText", "当前人才卡暂未配置该权益");
            merchant.put("applicableCards", "");
            merchant.put("rightsStatus", "MISSING");
        } else {
            merchant.put("rightsStatus", "UNCONFIGURED");
        }
        merchant.put("freeVoucherEnabled", freeVoucherEnabled);
        merchant.put("freeVoucherTimes", freeVoucherTimes);
        merchant.put("freeVoucherCycle", freeVoucherCycle);
        merchant.put("consumeType", consumeType);
        merchant.put("consumeDiscount", consumeDiscount);
        merchant.put("consumeCoupon", consumeCoupon);
        merchant.put("storeConsume", storeConsume);
        merchant.put("consumeEnabled", consumeEnabled);
        merchant.put("benefitTags", merchantBenefitTags(
                textOrDefault(merchant.get("merchantType"), ""),
                booleanValue(merchant.get("couponAvailable")),
                textOrDefault(merchant.get("discountText"), ""),
                configuredRight));
        merchant.put("usageInstructions", merchantUsageInstructions(
                id, merchant.get("merchantRightsConfig"), cardLevel, merchant.get("usageInstructions")));
        List<String> heroImages = new ArrayList<>();
        String coverUrl = textOrDefault(merchant.get("coverUrl"), "");
        if (!coverUrl.isBlank()) heroImages.add(coverUrl);
        for (Map<String, Object> product : query("""
                select cover_url
                from merchant_product
                where merchant_id = ? and deleted = 0 and status = 1 and audit_status = 2
                  and cover_url is not null and cover_url <> ''
                order by sort_no desc, id desc
                limit 8
                """, id)) {
            String imageUrl = textOrDefault(product.get("coverUrl"), "");
            if (!imageUrl.isBlank() && !heroImages.contains(imageUrl)) heroImages.add(imageUrl);
        }
        merchant.put("heroImages", heroImages);
        return merchant;
    }
 
    private Map<String, Object> matchingMerchantRight(List<Map<String, Object>> rights, String cardLevel, String sourceAreaType, boolean requireEnabled) {
        if (cardLevel == null) return null;
        List<String> candidates = merchantRightCandidates(cardLevel, sourceAreaType);
        for (String candidate : candidates) {
            for (Map<String, Object> right : rights) {
                if (requireEnabled && !booleanValue(right.get("enabled"))) continue;
                if (candidate.equals(textOrDefault(right.get("level"), ""))) return right;
                if (sameCardLevel(right.get("level"), candidate)) return right;
            }
        }
        return null;
    }
 
    private List<String> merchantRightCandidates(String cardLevel, String sourceAreaType) {
        String level = normalizedCardLevel(cardLevel);
        String area = normalizedSourceAreaType(sourceAreaType);
        if ("EXCELLENT".equals(level)) {
            if ("LOCAL".equals(area)) return List.of("卓越人才卡(本地)", "卓越人才卡");
            if ("OUTSIDE".equals(area)) return List.of("卓越人才卡(外地)", "卓越人才卡");
            return List.of("卓越人才卡");
        }
        if ("OUTSTANDING".equals(level)) return List.of("杰出人才卡");
        if ("ELITE".equals(level)) return List.of("菁英人才卡");
        return cardLevel == null || cardLevel.isBlank() ? List.of() : List.of(cardLevel);
    }
 
    private String cardLevelText(String cardLevel) {
        return switch (normalizedCardLevel(cardLevel)) {
            case "EXCELLENT" -> "卓越卡";
            case "OUTSTANDING" -> "杰出卡";
            case "ELITE" -> "菁英卡";
            default -> "人才卡";
        };
    }
 
    private String merchantUsageInstructions(Long merchantId, Object rightsConfig, String cardLevel, Object fallback) {
        if (cardLevel != null) {
            for (Map<String, Object> right : merchantRightsConfigs(rightsConfig)) {
                if (!booleanValue(right.get("enabled")) || !booleanValue(right.get("consumeEnabled"))
                        || !booleanValue(right.get("storeConsume")) || !sameCardLevel(right.get("level"), cardLevel)) continue;
                String description = textOrDefault(right.get("consumeDesc"), "");
                if (!description.isBlank()) return description;
            }
            List<Map<String, Object>> benefits = query("""
                    select card_level, benefit_text
                    from merchant_card_benefit
                    where merchant_id = ? and status = 1
                    order by sort_no desc, id desc
                    """, merchantId);
            for (Map<String, Object> benefit : benefits) {
                if (sameCardLevel(benefit.get("cardLevel"), cardLevel)) {
                    String description = textOrDefault(benefit.get("benefitText"), "");
                    if (!description.isBlank()) return description;
                }
            }
        }
        return textOrDefault(fallback, "以当前商户到店消费规则为准");
    }
 
    private List<Map<String, Object>> merchantRightsConfigs(Object value) {
        if (value == null || String.valueOf(value).isBlank()) return List.of();
        try {
            return OBJECT_MAPPER.readValue(String.valueOf(value), new TypeReference<List<Map<String, Object>>>() {});
        } catch (Exception ignored) {
            return List.of();
        }
    }
 
    private String carWashExternalLinkType(List<Map<String, Object>> rights) {
        for (Map<String, Object> right : rights) {
            if (right.containsKey("externalLinkType")
                    || right.containsKey("externalMiniProgramShortLink")
                    || right.containsKey("externalMiniProgramPath")
                    || right.containsKey("externalWebUrl")) {
                return textOrDefault(right.get("externalLinkType"), "");
            }
        }
        return "";
    }
 
    private String carWashListDiscountText(String externalLinkType, Map<String, Object> right) {
        if ("miniProgram".equals(externalLinkType) || right == null) return "";
        return merchantRightDiscountText(right);
    }
 
    private boolean booleanValue(Object value) {
        if (value instanceof Boolean bool) return bool;
        if (value instanceof Number number) return number.intValue() != 0;
        String text = value == null ? "" : String.valueOf(value).trim();
        return "true".equalsIgnoreCase(text) || "1".equals(text) || "yes".equalsIgnoreCase(text);
    }
 
    private boolean sameCardLevel(Object configured, String actual) {
        return normalizedCardLevel(configured).equals(normalizedCardLevel(actual));
    }
 
    private String normalizedSourceAreaType(Object value) {
        String raw = textOrDefault(value, "").toUpperCase(Locale.ROOT);
        if (raw.contains("OUTSIDE") || raw.contains("外地")) return "OUTSIDE";
        if (raw.contains("LOCAL") || raw.contains("本地")) return "LOCAL";
        return "";
    }
 
    private String normalizedCardLevel(Object value) {
        String level = value == null ? "" : String.valueOf(value).trim().toUpperCase(Locale.ROOT);
        if (level.contains("卓越") || "EXCELLENT".equals(level)) return "EXCELLENT";
        if (level.contains("杰出") || "OUTSTANDING".equals(level)) return "OUTSTANDING";
        if (level.contains("菁英") || "ELITE".equals(level)) return "ELITE";
        return level;
    }
 
    private boolean hasActiveMerchantCoupon(Long merchantId) {
        Long count = jdbcTemplate.queryForObject("""
                select count(*)
                from merchant_coupon
                where merchant_id = ? and deleted = 0 and status = 1
                  and (valid_start is null or valid_start <= current_date)
                  and (valid_end is null or valid_end >= current_date)
                """, Long.class, merchantId);
        return count != null && count > 0;
    }
 
    private String merchantLowestTalentDiscount(Long merchantId, Long talentId) {
        String cardLevel = activeProductCardLevel(talentId);
        if (cardLevel == null) return "";
        BigDecimal lowestRate = null;
        for (Map<String, Object> product : query("""
                select id, original_price, sale_price, rights_config
                from merchant_product
                where merchant_id = ? and deleted = 0 and status = 1 and audit_status = 2
                """, merchantId)) {
            ProductPriceCalculator.ProductRight right = ProductPriceCalculator.productRight(
                    product.get("rightsConfig"), cardLevel);
            if (right == null || right.discount().signum() <= 0) continue;
            BigDecimal rate = right.discount().divide(BigDecimal.TEN, 6, RoundingMode.HALF_UP);
            if (lowestRate == null || rate.compareTo(lowestRate) < 0) {
                lowestRate = rate;
            }
        }
        if (lowestRate == null || lowestRate.compareTo(BigDecimal.ONE) >= 0) return "";
        double discount = Math.round(lowestRate.doubleValue() * 100) / 10.0;
        return discount + "折";
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> productDetail(Long id) {
        return productDetail(id, null);
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> productDetail(Long id, Long talentId) {
        Map<String, Object> product = one("""
                select id, merchant_id, product_no, product_type, product_name, subtitle, cover_url,
                       original_price, sale_price, subsidy_amount, stock, sales_count, detail_text, benefit_desc,
                       purchase_notice, product_images, rights_config, valid_start_time, valid_end_time,
                       audit_status, status
                from merchant_product
                where deleted = 0 and id = ?
                """, id);
        int stock = ((Number) product.getOrDefault("stock", 0)).intValue();
        boolean available = ((Number) product.getOrDefault("status", 0)).intValue() == 1
                && ((Number) product.getOrDefault("auditStatus", 0)).intValue() == 2;
        product.put("available", available);
        product.put("soldOut", stock == 0);
        BigDecimal configuredOriginalPrice = decimal(product.get("originalPrice"));
        if (configuredOriginalPrice.signum() <= 0) {
            configuredOriginalPrice = decimal(product.get("salePrice"));
            product.put("originalPrice", configuredOriginalPrice);
        }
        BigDecimal configuredSalePrice = decimal(product.get("salePrice"));
        BigDecimal personalizedPrice = personalizedProductPrice(product, talentId);
        product.put("salePrice", personalizedPrice);
        product.put("personalized", talentId != null && personalizedPrice.compareTo(configuredSalePrice) != 0);
        Long merchantId = ((Number) product.get("merchantId")).longValue();
        product.put("couponAvailable", hasActiveMerchantCoupon(merchantId));
        product.put("discountText", merchantLowestTalentDiscount(merchantId, talentId));
        return product;
    }
 
    @Transactional(readOnly = true)
    public List<Map<String, Object>> availableOrderCoupons(Long merchantId, Long productId, String orderId) {
        return availableOrderCoupons(merchantId, productId, orderId, null);
    }
 
    @Transactional(readOnly = true)
    public List<Map<String, Object>> availableOrderCoupons(Long merchantId, Long productId, String orderId, Long talentId) {
        Map<String, Object> product = orderCouponProduct(merchantId, productId, orderId);
        BigDecimal productAmount = personalizedProductPrice(product, talentId);
        String cardLevel = talentId == null ? null : activeCouponCardLevel(talentId);
        return query("""
                select c.id, c.coupon_name, c.condition_type, c.condition_amount, c.coupon_amount,
                       c.valid_start, c.valid_end
                from merchant_coupon c
                where c.deleted = 0 and c.status = 1 and c.merchant_id = ?
                  and (c.valid_start is null or c.valid_start <= current_date)
                  and (c.valid_end is null or c.valid_end >= current_date)
              and (c.condition_type = 'NONE' or c.condition_amount is null or c.condition_amount <= ?)
              and (? is null or coalesce(c.talent_levels, '') = '' or find_in_set(?, replace(c.talent_levels, '、', ',')) > 0)
              and (c.product_scope = 'ALL' or exists (
                select 1 from merchant_coupon_product cp
                where cp.coupon_id = c.id and cp.product_id = ?
              ))
              and (? is null or not exists (
                select 1 from benefit_order o
                where o.coupon_id = c.id and o.talent_id = ? and o.deleted = 0 and o.order_status = 0
                  and (o.expires_at is null or o.expires_at > current_timestamp)
              ))
            order by c.coupon_amount desc, c.id desc
            """, merchantId, productAmount, cardLevel, cardLevel, productId, talentId, talentId).stream()
                .map(this::couponListItem)
                .toList();
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> orderCouponQuote(Long merchantId, Long productId, String orderId, Long couponId) {
        return orderCouponQuote(merchantId, productId, orderId, couponId, null);
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> orderCouponQuote(Long merchantId, Long productId, String orderId, Long couponId, Long talentId) {
        Map<String, Object> product = orderCouponProduct(merchantId, productId, orderId);
        BigDecimal originalAmount = decimal(product.get("originalPrice"));
        if (originalAmount.signum() <= 0) originalAmount = decimal(product.get("salePrice"));
        BigDecimal productAmount = personalizedProductPrice(product, talentId);
        String cardLevel = talentId == null ? null : activeCouponCardLevel(talentId);
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("orderId", orderId);
        result.put("merchantId", merchantId);
        result.put("productId", productId);
        result.put("productName", product.get("productName"));
        result.put("coverUrl", product.get("coverUrl"));
        result.put("originalAmount", originalAmount);
        result.put("productAmount", productAmount);
        result.put("productDiscountAmount", originalAmount.subtract(productAmount).max(BigDecimal.ZERO));
        result.put("discountText", discountText(productAmount, originalAmount));
 
        if (couponId == null) {
            result.put("couponId", null);
            result.put("couponLabel", "无");
            result.put("couponAmount", BigDecimal.ZERO);
            result.put("discountAmount", originalAmount.subtract(productAmount).max(BigDecimal.ZERO));
            result.put("payAmount", productAmount);
            result.put("subsidyAmount", originalAmount.subtract(productAmount).max(BigDecimal.ZERO));
            return result;
        }
 
        List<Map<String, Object>> coupons = query("""
                select c.id, c.coupon_name, c.condition_type, c.condition_amount, c.coupon_amount,
                       c.valid_start, c.valid_end
                from merchant_coupon c
                where c.id = ? and c.deleted = 0 and c.status = 1 and c.merchant_id = ?
                  and (c.valid_start is null or c.valid_start <= current_date)
                  and (c.valid_end is null or c.valid_end >= current_date)
              and (c.condition_type = 'NONE' or c.condition_amount is null or c.condition_amount <= ?)
              and (? is null or coalesce(c.talent_levels, '') = '' or find_in_set(?, replace(c.talent_levels, '、', ',')) > 0)
              and (c.product_scope = 'ALL' or exists (
                select 1 from merchant_coupon_product cp
                where cp.coupon_id = c.id and cp.product_id = ?
              ))
              and (? is null or not exists (
                select 1 from benefit_order o
                where o.coupon_id = c.id and o.talent_id = ? and o.deleted = 0 and o.order_status = 0
                  and (o.expires_at is null or o.expires_at > current_timestamp)
              ))
            """, couponId, merchantId, productAmount, cardLevel, cardLevel, productId, talentId, talentId);
        if (coupons.isEmpty()) {
            throw new BusinessException(ErrorCode.CONFLICT, "该优惠券当前不可用,请重新选择");
        }
        Map<String, Object> coupon = coupons.get(0);
        BigDecimal couponAmount = decimal(coupon.get("couponAmount")).min(productAmount);
        result.put("couponId", couponId);
        result.put("couponName", coupon.get("couponName"));
        result.put("couponLabel", "减" + moneyText(couponAmount) + "元");
        result.put("couponAmount", couponAmount);
        result.put("discountAmount", originalAmount.subtract(productAmount).max(BigDecimal.ZERO).add(couponAmount));
        result.put("payAmount", productAmount.subtract(couponAmount).max(BigDecimal.ZERO));
        result.put("subsidyAmount", originalAmount.subtract(productAmount).max(BigDecimal.ZERO).add(couponAmount));
        return result;
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> products(Long merchantId, String type, Long talentId, int page, int size) {
        StringBuilder sql = new StringBuilder("""
                select id, merchant_id, product_no, product_type, product_name, subtitle, cover_url,
                       original_price, sale_price, subsidy_amount, stock, sales_count, benefit_desc, rights_config
                from merchant_product
                where deleted = 0 and status = 1 and audit_status = 2
                """);
        StringBuilder countSql = new StringBuilder("""
                select count(*) from merchant_product
                where deleted = 0 and status = 1 and audit_status = 2
                """);
        new Object();
        List<Object> args = new java.util.ArrayList<>();
        if (merchantId != null) {
            sql.append(" and merchant_id = ?");
            countSql.append(" and merchant_id = ?");
            args.add(merchantId);
        }
        if (type != null && !type.isBlank()) {
            sql.append(" and product_type = ?");
            countSql.append(" and product_type = ?");
            args.add(type);
        }
        sql.append(" order by sort_no desc, id desc");
        PageResult<Map<String, Object>> result = page(sql.toString(), countSql.toString(), page, size, args.toArray());
        List<Map<String, Object>> records = result.records().stream().map(product -> {
            Map<String, Object> item = new LinkedHashMap<>(product);
            BigDecimal configuredSalePrice = decimal(product.get("salePrice"));
            BigDecimal configuredOriginalPrice = decimal(product.get("originalPrice"));
            BigDecimal originalPrice = decimal(item.get("originalPrice"));
            if (originalPrice.signum() <= 0) originalPrice = decimal(item.get("salePrice"));
            BigDecimal personalizedPrice = personalizedProductPrice(item, talentId);
            item.put("configuredSalePrice", configuredSalePrice);
            item.put("configuredOriginalPrice", configuredOriginalPrice.signum() > 0 ? configuredOriginalPrice : originalPrice);
            item.put("originalPrice", originalPrice);
            item.put("salePrice", personalizedPrice);
            item.put("personalized", talentId != null && personalizedPrice.compareTo(decimal(product.get("salePrice"))) != 0);
            item.put("discountText", discountText(personalizedPrice, originalPrice));
            return item;
        }).toList();
        return new PageResult<>(records, result.page(), result.size(), result.total());
    }
 
    private Map<String, Object> orderCouponProduct(Long merchantId, Long productId, String orderId) {
        if (merchantId == null || productId == null || orderId == null || orderId.isBlank()) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "订单、商户和商品信息不能为空");
        }
        Map<String, Object> product = one("""
                select id, merchant_id, product_name, cover_url, original_price, sale_price, rights_config, stock, status, audit_status
                from merchant_product
                where deleted = 0 and id = ? and merchant_id = ?
                """, productId, merchantId);
        boolean available = ((Number) product.getOrDefault("status", 0)).intValue() == 1
                && ((Number) product.getOrDefault("auditStatus", 0)).intValue() == 2
                && ((Number) product.getOrDefault("stock", 0)).intValue() != 0;
        if (!available) {
            throw new BusinessException(ErrorCode.CONFLICT, "商品当前不可购买");
        }
        return product;
    }
 
    private BigDecimal personalizedProductPrice(Map<String, Object> product, Long talentId) {
        if (talentId == null) return decimal(product.get("salePrice"));
        String cardLevel = activeProductCardLevel(talentId);
        if (cardLevel == null) return decimal(product.get("salePrice"));
        return ProductPriceCalculator.calculate(product.get("originalPrice"), product.get("salePrice"), product.get("rightsConfig"), cardLevel,
                usedFreeCount(talentId, product.get("id"), product.get("rightsConfig"), cardLevel)).salePrice();
    }
 
    private String activeProductCardLevel(Long talentId) {
        if (talentId == null) return null;
        List<Map<String, Object>> cards = query("select card_level from talent_card where deleted = 0 and status = 1 and talent_id = ? and (card_type = 'PERSONAL' or card_type is null) order by id desc limit 1", talentId);
        Object cardLevel = cards.isEmpty() ? null : cards.get(0).get("cardLevel");
        if (cardLevel == null) {
            List<Map<String, Object>> talents = query("select talent_level from talent_user where deleted = 0 and status = 1 and id = ? limit 1", talentId);
            if (!talents.isEmpty()) cardLevel = talents.get(0).get("talentLevel");
        }
        return cardLevel == null ? null : String.valueOf(cardLevel);
    }
 
    private String activeTalentSourceAreaType(Long talentId) {
        if (talentId == null) return "";
        List<Map<String, Object>> rows = query("""
                select source_area_type
                from talent_user
                where deleted = 0 and status = 1 and id = ?
                limit 1
                """, talentId);
        if (rows.isEmpty()) return "";
        return normalizedSourceAreaType(rows.get(0).get("sourceAreaType"));
    }
 
    private int usedFreeCount(Long talentId, Object productId, Object rightsConfig, Object cardLevel) {
        ProductPriceCalculator.ProductRight right = ProductPriceCalculator.productRight(rightsConfig, cardLevel);
        if (right == null || !right.free() || !(productId instanceof Number number)) return 0;
        Long count = jdbcTemplate.queryForObject("""
                select count(*)
                from benefit_order
                where deleted = 0 and talent_id = ? and product_id = ? and pay_amount = 0 and order_status = 1
                  and created_at >= ?
                """, Long.class, talentId, number.longValue(), freeWindowStart(right.resetCycle()));
        return count == null ? 0 : count.intValue();
    }
 
    private LocalDateTime freeWindowStart(String resetCycle) {
        String cycle = resetCycle == null ? "" : resetCycle.trim().toUpperCase(Locale.ROOT);
        LocalDate today = LocalDate.now();
        if (cycle.isBlank() || "NONE".equals(cycle)) return LocalDate.of(1970, 1, 1).atStartOfDay();
        if (cycle.contains("DAY") || cycle.contains("天") || cycle.contains("日")) return today.atStartOfDay();
        if (cycle.contains("WEEK") || cycle.contains("周") || cycle.contains("星期")) return today.minusDays(today.getDayOfWeek().getValue() - 1L).atStartOfDay();
        if (cycle.contains("MONTH") || cycle.contains("月")) return today.withDayOfMonth(1).atStartOfDay();
        return today.with(TemporalAdjusters.firstDayOfYear()).atStartOfDay();
    }
 
    private Map<String, Object> couponListItem(Map<String, Object> coupon) {
        BigDecimal amount = decimal(coupon.get("couponAmount"));
        BigDecimal conditionAmount = decimal(coupon.get("conditionAmount"));
        boolean noThreshold = "NONE".equalsIgnoreCase(String.valueOf(coupon.get("conditionType")))
                || coupon.get("conditionAmount") == null;
        Map<String, Object> item = new LinkedHashMap<>();
        item.put("id", coupon.get("id"));
        item.put("name", coupon.get("couponName"));
        item.put("amount", moneyText(amount));
        item.put("selectedLabel", "减" + moneyText(amount) + "元");
        item.put("scope", noThreshold ? "无门槛可用" : "满" + moneyText(conditionAmount) + "元可用");
        item.put("expireTime", coupon.get("validEnd") == null ? "长期有效" : String.valueOf(coupon.get("validEnd")));
        item.put("available", true);
        item.put("unavailableReason", "");
        return item;
    }
 
    private BigDecimal decimal(Object value) {
        if (value == null) return BigDecimal.ZERO;
        return new BigDecimal(String.valueOf(value)).setScale(2, RoundingMode.HALF_UP);
    }
 
    private String moneyText(BigDecimal value) {
        return value.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
    }
 
    private String activeCouponCardLevel(Long talentId) {
        List<Map<String, Object>> cards = query("select card_level from talent_card where talent_id=? and deleted=0 and status=1 and card_type='PERSONAL' and (valid_end is null or valid_end >= current_date) order by id desc limit 1", talentId);
        if (cards.isEmpty()) throw new BusinessException(ErrorCode.CONFLICT, "当前暂无有效人才卡");
        return String.valueOf(cards.get(0).get("cardLevel"));
    }
 
    private List<Map<String, Object>> query(String sql, Object... args) {
        return DatabaseRows.normalize(jdbcTemplate.queryForList(sql, args));
    }
 
    private Map<String, Object> one(String sql, Object... args) {
        List<Map<String, Object>> rows = query(sql, args);
        if (rows.isEmpty()) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "数据不存在");
        }
        return rows.get(0);
    }
 
    private PageResult<Map<String, Object>> page(String sql, String countSql, int page, int size, Object... args) {
        int safePage = Math.max(page, 1);
        int safeSize = Math.min(Math.max(size, 1), 100);
        Object[] pageArgs = java.util.Arrays.copyOf(args, args.length + 2);
        pageArgs[args.length] = safeSize;
        pageArgs[args.length + 1] = (safePage - 1) * safeSize;
        List<Map<String, Object>> records = query(sql + " limit ? offset ?", pageArgs);
        Long total = jdbcTemplate.queryForObject(countSql, Long.class, args);
        return new PageResult<>(records, safePage, safeSize, total == null ? 0 : total);
    }
}