shinnosuke
2026-08-06 79ae06e6b4172d90df77b0e49ad3ab12ba63cd45
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
package com.talentcard.server.service;
 
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.talentcard.server.business.BusinessIdGenerator;
import com.talentcard.server.business.PageResult;
import com.talentcard.server.common.BusinessException;
import com.talentcard.server.common.ErrorCode;
import com.talentcard.server.entity.BenefitMerchant;
import com.talentcard.server.entity.TicketPackage;
import com.talentcard.server.entity.TicketPackageClaim;
import com.talentcard.server.entity.TicketPackageCode;
import com.talentcard.server.mapper.BenefitMerchantMapper;
import com.talentcard.server.mapper.TicketPackageClaimMapper;
import com.talentcard.server.mapper.TicketPackageCodeMapper;
import com.talentcard.server.mapper.TicketPackageMapper;
import com.talentcard.server.request.TicketPackageCodeImportRequest;
import com.talentcard.server.request.TicketPackageCodeLockRequest;
import com.talentcard.server.request.TicketPackageCodeStatusRequest;
import com.talentcard.server.request.TicketPackageSupplementRequest;
import com.talentcard.server.request.TicketPackageSaveRequest;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
@Service
public class TicketPackageAdminService {
    private static final List<String> CARD_LEVELS = List.of("卓越人才卡", "杰出人才卡", "菁英人才卡");
 
    private final TicketPackageMapper packageMapper;
    private final TicketPackageCodeMapper codeMapper;
    private final TicketPackageClaimMapper claimMapper;
    private final BenefitMerchantMapper merchantMapper;
 
    public TicketPackageAdminService(
            TicketPackageMapper packageMapper,
            TicketPackageCodeMapper codeMapper,
            TicketPackageClaimMapper claimMapper,
            BenefitMerchantMapper merchantMapper
    ) {
        this.packageMapper = packageMapper;
        this.codeMapper = codeMapper;
        this.claimMapper = claimMapper;
        this.merchantMapper = merchantMapper;
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> packages(Long merchantId, Integer status, String keyword, int page, int size) {
        int safePage = Math.max(page, 1);
        int safeSize = Math.min(Math.max(size, 1), 100);
        Integer normalizedStatus = normalizeStatusFilter(status);
        Long total = packageMapper.countAdminPage(merchantId, normalizedStatus, clean(keyword));
        List<Map<String, Object>> records = packageMapper.selectAdminPage(merchantId, normalizedStatus, clean(keyword), safeSize, (safePage - 1) * safeSize)
                .stream()
                .map(this::packageView)
                .toList();
        return new PageResult<>(records, safePage, safeSize, total == null ? 0 : total);
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> packageDetail(Long id) {
        return packageView(requirePackageDetail(id));
    }
 
    @Transactional
    public Map<String, Object> createPackage(TicketPackageSaveRequest request) {
        validateMerchant(request.merchantId());
        TicketPackage entity = new TicketPackage();
        entity.setPackageNo(BusinessIdGenerator.next("TP"));
        apply(entity, request);
        entity.setDeleted(0);
        packageMapper.insert(entity);
        return packageDetail(entity.getId());
    }
 
    @Transactional
    public Map<String, Object> updatePackage(Long id, TicketPackageSaveRequest request) {
        Long packageId = requireId(id, "票包ID不能为空");
        validateMerchant(request.merchantId());
        TicketPackage current = packageMapper.selectByIdForUpdate(packageId);
        if (current == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "票包不存在");
        }
        apply(current, request);
        int updated = packageMapper.updateById(current);
        if (updated != 1) {
            throw new BusinessException(ErrorCode.CONFLICT, "票包配置已变化,请刷新后重试");
        }
        return packageDetail(packageId);
    }
 
    @Transactional
    public Map<String, Object> updatePackageStatus(Long id, Integer status) {
        Long packageId = requireId(id, "票包ID不能为空");
        int normalized = normalizeStatus(status);
        int updated = packageMapper.update(null, new UpdateWrapper<TicketPackage>()
                .set("status", normalized)
                .eq("id", packageId)
                .eq("deleted", 0));
        if (updated != 1) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "票包不存在");
        }
        return packageDetail(packageId);
    }
 
    @Transactional
    public Map<String, Object> importCodes(Long packageId, TicketPackageCodeImportRequest request) {
        TicketPackage ticketPackage = requirePackage(packageId);
        String batchNo = clean(request.batchNo()).isBlank() ? BusinessIdGenerator.next("TPC") : clean(request.batchNo());
        String remark = clean(request.remark());
        Set<String> distinctCodes = new LinkedHashSet<>();
        for (String code : request.codes()) {
            String cleaned = clean(code);
            if (!cleaned.isBlank()) {
                distinctCodes.add(cleaned);
            }
        }
        if (distinctCodes.isEmpty()) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "兑换码列表不能为空");
        }
        int imported = 0;
        int duplicate = 0;
        for (String exchangeCode : distinctCodes) {
            TicketPackageCode entity = new TicketPackageCode();
            entity.setPackageId(ticketPackage.getId());
            entity.setExchangeCode(exchangeCode);
            entity.setBatchNo(batchNo);
            entity.setStatus("AVAILABLE");
            entity.setRemark(remark);
            entity.setDeleted(0);
            try {
                codeMapper.insert(entity);
                imported++;
            } catch (DuplicateKeyException exception) {
                duplicate++;
            }
        }
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("packageId", ticketPackage.getId());
        result.put("batchNo", batchNo);
        result.put("submittedCount", request.codes().size());
        result.put("distinctCount", distinctCodes.size());
        result.put("importedCount", imported);
        result.put("duplicateCount", duplicate);
        result.put("stock", stock(ticketPackage.getId()));
        return result;
    }
 
    @Transactional
    public Map<String, Object> importCodeFile(Long packageId, MultipartFile file, String batchNo, String remark) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "兑换码文件不能为空");
        }
        List<String> codes = readExcelCodes(file);
        return importCodes(packageId, new TicketPackageCodeImportRequest(batchNo, codes, remark));
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> stock(Long packageId) {
        return packageView(requirePackageDetail(packageId));
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> codes(Long packageId, String status, String batchNo, String keyword, int page, int size) {
        int safePage = Math.max(page, 1);
        int safeSize = Math.min(Math.max(size, 1), 100);
        String normalizedStatus = normalizeCodeStatusFilter(status);
        Long total = codeMapper.countAdminPage(packageId, normalizedStatus, clean(batchNo), clean(keyword));
        List<Map<String, Object>> records = codeMapper.selectAdminPage(packageId, normalizedStatus, clean(batchNo), clean(keyword), safeSize, (safePage - 1) * safeSize)
                .stream()
                .map(this::codeView)
                .toList();
        return new PageResult<>(records, safePage, safeSize, total == null ? 0 : total);
    }
 
    @Transactional
    public Map<String, Object> updateCodeStatus(Long codeId, TicketPackageCodeStatusRequest request) {
        Long id = requireId(codeId, "兑换码ID不能为空");
        String nextStatus = normalizeCodeStatus(request.status(), false);
        TicketPackageCode current = codeMapper.selectById(id);
        if (current == null || intValue(current.getDeleted()) == 1) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "兑换码不存在");
        }
        if ("ISSUED".equals(current.getStatus()) && !"USED".equals(nextStatus)) {
            throw new BusinessException(ErrorCode.CONFLICT, "已发放兑换码只能标记为已使用");
        }
        if ("USED".equals(current.getStatus())) {
            throw new BusinessException(ErrorCode.CONFLICT, "已使用兑换码不能变更状态");
        }
        UpdateWrapper<TicketPackageCode> update = new UpdateWrapper<TicketPackageCode>()
                .set("status", nextStatus)
                .set("remark", clean(request.remark()))
                .eq("id", id)
                .eq("deleted", 0);
        if ("USED".equals(nextStatus)) {
            update.set("used_at", LocalDateTime.now());
        }
        int updated = codeMapper.update(null, update);
        if (updated != 1) {
            throw new BusinessException(ErrorCode.CONFLICT, "兑换码状态已变化,请刷新后重试");
        }
        if ("USED".equals(nextStatus) && current.getIssuedClaimId() != null) {
            claimMapper.update(null, new UpdateWrapper<com.talentcard.server.entity.TicketPackageClaim>()
                    .set("status", "USED")
                    .set("used_at", LocalDateTime.now())
                    .eq("id", current.getIssuedClaimId())
                    .eq("deleted", 0));
        }
        return codeView(codeMapper.selectAdminPage(current.getPackageId(), "", "", current.getExchangeCode(), 1, 0).stream().findFirst().orElse(Map.of()));
    }
 
    @Transactional(readOnly = true)
    public PageResult<Map<String, Object>> claims(Long packageId, Long talentId, String status, String keyword, int page, int size) {
        int safePage = Math.max(page, 1);
        int safeSize = Math.min(Math.max(size, 1), 100);
        String normalizedStatus = normalizeClaimStatusFilter(status);
        Long total = claimMapper.countAdminPage(packageId, talentId, normalizedStatus, clean(keyword));
        List<Map<String, Object>> records = claimMapper.selectAdminPage(packageId, talentId, normalizedStatus, clean(keyword), safeSize, (safePage - 1) * safeSize)
                .stream()
                .map(this::claimView)
                .toList();
        return new PageResult<>(records, safePage, safeSize, total == null ? 0 : total);
    }
 
 
    @Transactional(readOnly = true)
    public Map<String, Object> codeDetail(Long codeId) {
        Long id = requireId(codeId, "兑换码ID不能为空");
        Map<String, Object> row = codeMapper.selectAdminDetailById(id);
        if (row == null || row.isEmpty()) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "兑换码不存在");
        }
        return codeDetailView(row);
    }
 
    @Transactional(readOnly = true)
    public Map<String, Object> validateCode(String exchangeCode, Long packageId, Long merchantId) {
        String codeValue = clean(exchangeCode);
        if (codeValue.isBlank()) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "兑换码码值不能为空");
        }
        Map<String, Object> row = codeMapper.selectAdminDetailByExchangeCode(codeValue, packageId);
        if (row == null || row.isEmpty()) {
            return validationResult(false, "兑换码不存在", row);
        }
        String reason = validationReason(row, merchantId);
        if (reason.isBlank() && "AVAILABLE".equals(text(row, "status"))) {
            return validationResult(true, "", row);
        }
        if (reason.isBlank()) {
            reason = codeStatusReason(text(row, "status"));
        }
        return validationResult(false, reason, row);
    }
 
    @Transactional
    public Map<String, Object> lockForIssue(Long codeId, TicketPackageCodeLockRequest request) {
        Long id = requireId(codeId, "兑换码ID不能为空");
        TicketPackageCode code = codeMapper.selectByIdForUpdate(id);
        if (code == null || intValue(code.getDeleted()) == 1) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "兑换码不存在");
        }
        if (!"AVAILABLE".equals(code.getStatus())) {
            throw new BusinessException(ErrorCode.CONFLICT, "仅可用状态兑换码可锁定");
        }
        validateLockablePackage(packageMapper.selectById(code.getPackageId()));
        ClaimerInfo claimer = resolveClaimer(request.talentId(), request.cardId(), false);
        int locked = codeMapper.lockForIssue(code.getId(), claimer.talentId(), claimer.cardId());
        if (locked != 1) {
            throw new BusinessException(ErrorCode.CONFLICT, "兑换码已被领取或状态已变化,请刷新后重试");
        }
        if (!clean(request.remark()).isBlank()) {
            codeMapper.update(null, new UpdateWrapper<TicketPackageCode>()
                    .set("remark", clean(request.remark()))
                    .eq("id", code.getId())
                    .eq("deleted", 0));
        }
        return codeDetailView(codeMapper.selectAdminDetailById(code.getId()));
    }
 
    @Transactional
    public Map<String, Object> releaseLock(Long codeId) {
        Long id = requireId(codeId, "兑换码ID不能为空");
        TicketPackageCode code = codeMapper.selectByIdForUpdate(id);
        if (code == null || intValue(code.getDeleted()) == 1) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "兑换码不存在");
        }
        if (!"LOCKED".equals(code.getStatus())) {
            throw new BusinessException(ErrorCode.CONFLICT, "仅锁定状态兑换码可解锁");
        }
        int released = codeMapper.releaseLock(id);
        if (released != 1) {
            throw new BusinessException(ErrorCode.CONFLICT, "兑换码状态已变化,请刷新后重试");
        }
        return codeDetailView(codeMapper.selectAdminDetailById(id));
    }
 
    @Transactional
    public Map<String, Object> voidCode(Long codeId, String remark) {
        Long id = requireId(codeId, "兑换码ID不能为空");
        TicketPackageCode code = codeMapper.selectByIdForUpdate(id);
        if (code == null || intValue(code.getDeleted()) == 1) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "兑换码不存在");
        }
        String current = code.getStatus();
        if ("USED".equals(current) || "VOID".equals(current)) {
            throw new BusinessException(ErrorCode.CONFLICT, "已使用或已作废兑换码不能作废");
        }
        UpdateWrapper<TicketPackageCode> update = new UpdateWrapper<TicketPackageCode>()
                .set("status", "VOID")
                .set("remark", clean(remark))
                .eq("id", id)
                .eq("deleted", 0);
        if ("LOCKED".equals(current)) {
            update.set("locked_by_talent_id", null)
                    .set("locked_by_card_id", null)
                    .set("locked_at", null);
        }
        int updated = codeMapper.update(null, update);
        if (updated != 1) {
            throw new BusinessException(ErrorCode.CONFLICT, "兑换码状态已变化,请刷新后重试");
        }
        if (code.getIssuedClaimId() != null) {
            claimMapper.update(null, new UpdateWrapper<TicketPackageClaim>()
                    .set("status", "CANCELLED")
                    .eq("id", code.getIssuedClaimId())
                    .eq("deleted", 0));
        }
        return codeDetailView(codeMapper.selectAdminDetailById(id));
    }
 
    @Transactional
    public Map<String, Object> supplementClaim(TicketPackageSupplementRequest request) {
        Long packageId = requireId(request.packageId(), "票包ID不能为空");
        TicketPackage ticketPackage = packageMapper.selectByIdForUpdate(packageId);
        validateLockablePackage(ticketPackage);
        TicketPackageCode code = resolveSupplementCode(request, packageId);
        TicketPackageClaim existing = claimMapper.selectByCodeId(code.getId());
        if (existing != null) {
            return claimAdminView(existing);
        }
        String current = code.getStatus();
        if (!"AVAILABLE".equals(current) && !"LOCKED".equals(current)) {
            throw new BusinessException(ErrorCode.CONFLICT, "仅可用或锁定状态兑换码可补录发放");
        }
        ClaimerInfo claimer = resolveClaimer(request.talentId(), request.cardId(), true);
        LocalDateTime now = LocalDateTime.now();
        if ("AVAILABLE".equals(current)) {
            int locked = codeMapper.lockForIssue(code.getId(), claimer.talentId(), claimer.cardId());
            if (locked != 1) {
                throw new BusinessException(ErrorCode.CONFLICT, "兑换码已被领取,请刷新后重试");
            }
        }
        TicketPackageClaim claim = new TicketPackageClaim();
        claim.setClaimNo(BusinessIdGenerator.next("TPC"));
        claim.setPackageId(ticketPackage.getId());
        claim.setCodeId(code.getId());
        claim.setMerchantId(ticketPackage.getMerchantId());
        claim.setTalentId(claimer.talentId());
        claim.setCardId(claimer.cardId());
        claim.setPrimaryCardId(claimer.primaryCardId());
        claim.setCardNo(claimer.cardNo());
        claim.setCardLevel(claimer.cardLevel());
        claim.setTalentName(claimer.talentName());
        claim.setTalentMobile(claimer.talentMobile());
        claim.setExchangeCode(code.getExchangeCode());
        claim.setStatus("ISSUED");
        claim.setValidEnd(ticketPackage.getValidEnd());
        claim.setIdempotencyKey("MANUAL-" + claim.getClaimNo());
        claim.setDeleted(0);
        try {
            claimMapper.insert(claim);
        } catch (DuplicateKeyException exception) {
            codeMapper.releaseLock(code.getId());
            TicketPackageClaim concurrent = claimMapper.selectByCodeId(code.getId());
            if (concurrent != null) {
                return claimAdminView(concurrent);
            }
            throw new BusinessException(ErrorCode.CONFLICT, "补录请求已提交,请稍后查询发放结果");
        } catch (RuntimeException exception) {
            codeMapper.releaseLock(code.getId());
            throw exception;
        }
        int issued = codeMapper.update(null, new UpdateWrapper<TicketPackageCode>()
                .set("status", "ISSUED")
                .set("issued_claim_id", claim.getId())
                .set("issued_at", now)
                .set("locked_by_talent_id", claimer.talentId())
                .set("locked_by_card_id", claimer.cardId())
                .set("locked_at", now)
                .set("remark", clean(request.remark()))
                .eq("id", code.getId())
                .eq("status", "LOCKED")
                .eq("deleted", 0));
        if (issued != 1) {
            throw new BusinessException(ErrorCode.CONFLICT, "兑换码发放失败,请重试");
        }
        return claimAdminView(claim);
    }
 
    private TicketPackageCode resolveSupplementCode(TicketPackageSupplementRequest request, Long packageId) {
        if (request.codeId() != null) {
            TicketPackageCode code = codeMapper.selectByIdForUpdate(request.codeId());
            if (code == null || intValue(code.getDeleted()) == 1) {
                throw new BusinessException(ErrorCode.NOT_FOUND, "兑换码不存在");
            }
            if (!packageId.equals(code.getPackageId())) {
                throw new BusinessException(ErrorCode.CONFLICT, "兑换码不属于该票包");
            }
            return code;
        }
        String codeValue = clean(request.exchangeCode());
        if (codeValue.isBlank()) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "兑换码ID与兑换码码值至少填一个");
        }
        TicketPackageCode code = codeMapper.selectByExchangeCodeForUpdate(codeValue, packageId);
        if (code == null || intValue(code.getDeleted()) == 1) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "兑换码不存在");
        }
        return code;
    }
    private List<String> readExcelCodes(MultipartFile file) {
        List<String> codes = new ArrayList<>();
        DataFormatter formatter = new DataFormatter();
        try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
            if (workbook.getNumberOfSheets() < 1) {
                throw new BusinessException(ErrorCode.BAD_REQUEST, "兑换码文件没有工作表");
            }
            Sheet sheet = workbook.getSheetAt(0);
            boolean firstValue = true;
            for (Row row : sheet) {
                if (row == null) {
                    continue;
                }
                String code = clean(formatter.formatCellValue(row.getCell(0)));
                if (code.isBlank()) {
                    continue;
                }
                if (firstValue && isCodeHeader(code)) {
                    firstValue = false;
                    continue;
                }
                firstValue = false;
                codes.add(code);
                if (codes.size() > 5000) {
                    throw new BusinessException(ErrorCode.BAD_REQUEST, "单次最多导入5000个兑换码");
                }
            }
        } catch (IOException | EncryptedDocumentException | IllegalArgumentException exception) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "兑换码文件读取失败,请上传未加密的Excel文件");
        }
        if (codes.isEmpty()) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "兑换码文件中未读取到兑换码");
        }
        return codes;
    }
 
    private boolean isCodeHeader(String value) {
        String text = clean(value).toUpperCase(Locale.ROOT);
        return List.of("兑换码", "券码", "码", "EXCHANGE_CODE", "CODE").contains(text);
    }
    private void apply(TicketPackage entity, TicketPackageSaveRequest request) {
        entity.setPackageName(cleanRequired(request.packageName(), "票包名称不能为空"));
        entity.setMerchantId(request.merchantId());
        entity.setCoverUrl(clean(request.coverUrl()));
        entity.setTalentLevels(joinTalentLevels(request.talentLevels()));
        entity.setClaimPrice(request.claimPrice() == null ? BigDecimal.ZERO : request.claimPrice());
        entity.setPerUserLimit(request.perUserLimit() == null ? 1 : request.perUserLimit());
        entity.setValidStart(request.validStart());
        entity.setValidEnd(request.validEnd());
        if (entity.getValidStart() != null && entity.getValidEnd() != null && entity.getValidEnd().isBefore(entity.getValidStart())) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "有效结束日期不能早于有效开始日期");
        }
        entity.setAppName(clean(request.appName()));
        entity.setAppJumpUrl(clean(request.appJumpUrl()));
        entity.setUsageText(clean(request.usageText()));
        entity.setStatus(normalizeStatus(request.status()));
        entity.setSortNo(request.sortNo() == null ? 0 : request.sortNo());
    }
 
    private Map<String, Object> packageView(Map<String, Object> row) {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("id", value(row, "id"));
        result.put("packageNo", text(row, "packageNo", "package_no"));
        result.put("packageName", text(row, "packageName", "package_name"));
        result.put("merchantId", value(row, "merchantId", "merchant_id"));
        result.put("merchantName", text(row, "merchantName", "merchant_name"));
        result.put("coverUrl", text(row, "coverUrl", "cover_url"));
        result.put("talentLevels", splitLevels(text(row, "talentLevels", "talent_levels")));
        result.put("claimPrice", value(row, "claimPrice", "claim_price"));
        result.put("perUserLimit", intValue(value(row, "perUserLimit", "per_user_limit")));
        result.put("validStart", value(row, "validStart", "valid_start"));
        result.put("validEnd", value(row, "validEnd", "valid_end"));
        result.put("appName", text(row, "appName", "app_name"));
        result.put("appJumpUrl", text(row, "appJumpUrl", "app_jump_url"));
        result.put("usageText", text(row, "usageText", "usage_text"));
        result.put("status", intValue(value(row, "status")));
        result.put("sortNo", intValue(value(row, "sortNo", "sort_no")));
        result.put("totalCodes", intValue(value(row, "totalCodes", "total_codes")));
        result.put("availableCodes", intValue(value(row, "availableCodes", "available_codes")));
        result.put("lockedCodes", intValue(value(row, "lockedCodes", "locked_codes")));
        result.put("issuedCodes", intValue(value(row, "issuedCodes", "issued_codes")));
        result.put("usedCodes", intValue(value(row, "usedCodes", "used_codes")));
        result.put("voidCodes", intValue(value(row, "voidCodes", "void_codes")));
        result.put("createdAt", value(row, "createdAt", "created_at"));
        result.put("updatedAt", value(row, "updatedAt", "updated_at"));
        return result;
    }
 
    private Map<String, Object> codeView(Map<String, Object> row) {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("id", value(row, "id"));
        result.put("packageId", value(row, "packageId", "package_id"));
        result.put("packageName", text(row, "packageName", "package_name"));
        result.put("exchangeCode", text(row, "exchangeCode", "exchange_code"));
        result.put("batchNo", text(row, "batchNo", "batch_no"));
        result.put("status", text(row, "status"));
        result.put("statusName", codeStatusName(text(row, "status")));
        result.put("lockedByTalentId", value(row, "lockedByTalentId", "locked_by_talent_id"));
        result.put("lockedByCardId", value(row, "lockedByCardId", "locked_by_card_id"));
        result.put("lockedAt", value(row, "lockedAt", "locked_at"));
        result.put("issuedClaimId", value(row, "issuedClaimId", "issued_claim_id"));
        result.put("issuedAt", value(row, "issuedAt", "issued_at"));
        result.put("usedAt", value(row, "usedAt", "used_at"));
        result.put("remark", text(row, "remark"));
        result.put("createdAt", value(row, "createdAt", "created_at"));
        result.put("updatedAt", value(row, "updatedAt", "updated_at"));
        return result;
    }
 
    private Map<String, Object> claimView(Map<String, Object> row) {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("id", value(row, "id"));
        result.put("claimNo", text(row, "claimNo", "claim_no"));
        result.put("packageId", value(row, "packageId", "package_id"));
        result.put("packageName", text(row, "packageName", "package_name"));
        result.put("merchantId", value(row, "merchantId", "merchant_id"));
        result.put("merchantName", text(row, "merchantName", "merchant_name"));
        result.put("talentId", value(row, "talentId", "talent_id"));
        result.put("cardId", value(row, "cardId", "card_id"));
        result.put("cardNo", text(row, "cardNo", "card_no"));
        result.put("cardLevel", text(row, "cardLevel", "card_level"));
        result.put("talentName", text(row, "talentName", "talent_name"));
        result.put("talentMobile", text(row, "talentMobile", "talent_mobile"));
        result.put("exchangeCode", text(row, "exchangeCode", "exchange_code"));
        result.put("status", text(row, "status"));
        result.put("statusName", claimStatusName(text(row, "status")));
        result.put("validEnd", value(row, "validEnd", "valid_end"));
        result.put("source", claimSource(text(row, "idempotencyKey")));
        result.put("sourceName", "MANUAL".equals(claimSource(text(row, "idempotencyKey"))) ? "后台补录" : "线上领取");
        result.put("usedAt", value(row, "usedAt", "used_at"));
        result.put("createdAt", value(row, "createdAt", "created_at"));
        result.put("updatedAt", value(row, "updatedAt", "updated_at"));
        return result;
    }
 
    private Map<String, Object> requirePackageDetail(Long id) {
        Long packageId = requireId(id, "票包ID不能为空");
        Map<String, Object> row = packageMapper.selectAdminDetail(packageId);
        if (row == null || row.isEmpty()) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "票包不存在");
        }
        return row;
    }
 
    private TicketPackage requirePackage(Long id) {
        Long packageId = requireId(id, "票包ID不能为空");
        TicketPackage ticketPackage = packageMapper.selectOne(new QueryWrapper<TicketPackage>()
                .eq("id", packageId)
                .eq("deleted", 0)
                .last("limit 1"));
        if (ticketPackage == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "票包不存在");
        }
        return ticketPackage;
    }
 
    private void validateMerchant(Long merchantId) {
        if (merchantId == null) {
            return;
        }
        BenefitMerchant merchant = merchantMapper.selectOne(new QueryWrapper<BenefitMerchant>()
                .eq("id", merchantId)
                .eq("deleted", 0)
                .last("limit 1"));
        if (merchant == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "指定商家不存在");
        }
    }
 
    private String joinTalentLevels(List<String> levels) {
        if (levels == null || levels.isEmpty()) {
            return "";
        }
        List<String> cleaned = new ArrayList<>();
        for (String level : levels) {
            String value = clean(level);
            if (value.isBlank()) {
                continue;
            }
            if (!CARD_LEVELS.contains(value)) {
                throw new BusinessException(ErrorCode.BAD_REQUEST, "适用人才卡等级仅支持卓越人才卡、杰出人才卡、菁英人才卡");
            }
            if (!cleaned.contains(value)) {
                cleaned.add(value);
            }
        }
        return String.join("、", cleaned);
    }
 
    private List<String> splitLevels(String value) {
        String text = clean(value);
        if (text.isBlank()) {
            return List.of();
        }
        return List.of(text.split("[、,,]"));
    }
 
    private int normalizeStatus(Integer status) {
        if (status == null) {
            return 1;
        }
        if (status != 0 && status != 1) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "状态只能为0停用或1启用");
        }
        return status;
    }
 
    private Integer normalizeStatusFilter(Integer status) {
        if (status == null) {
            return null;
        }
        return normalizeStatus(status);
    }
 
    private String normalizeCodeStatusFilter(String status) {
        String value = clean(status);
        return value.isBlank() ? "" : normalizeCodeStatus(value, true);
    }
 
    private String normalizeCodeStatus(String status, boolean allowIssuedLocked) {
        String value = clean(status).toUpperCase(Locale.ROOT);
        return switch (value) {
            case "AVAILABLE", "可发放" -> "AVAILABLE";
            case "VOID", "作废" -> "VOID";
            case "USED", "已使用" -> "USED";
            case "LOCKED", "锁定" -> allowIssuedLocked ? "LOCKED" : throwStatus();
            case "ISSUED", "已发放" -> allowIssuedLocked ? "ISSUED" : throwStatus();
            default -> throwStatus();
        };
    }
 
    private String throwStatus() {
        throw new BusinessException(ErrorCode.BAD_REQUEST, "兑换码状态不正确");
    }
 
    private String normalizeClaimStatusFilter(String status) {
        String value = clean(status);
        if (value.isBlank()) {
            return "";
        }
        return switch (value.toUpperCase(Locale.ROOT)) {
            case "ISSUED", "已发放" -> "ISSUED";
            case "USED", "已使用" -> "USED";
            case "EXPIRED", "已过期" -> "EXPIRED";
            case "CANCELLED", "CANCELED", "已取消" -> "CANCELLED";
            default -> throw new BusinessException(ErrorCode.BAD_REQUEST, "发放状态不正确");
        };
    }
 
    private String codeStatusName(String status) {
        return switch (clean(status).toUpperCase(Locale.ROOT)) {
            case "LOCKED" -> "锁定";
            case "ISSUED" -> "已发放";
            case "USED" -> "已使用";
            case "VOID" -> "作废";
            default -> "可发放";
        };
    }
 
    private String claimStatusName(String status) {
        return switch (clean(status).toUpperCase(Locale.ROOT)) {
            case "USED" -> "已使用";
            case "EXPIRED" -> "已过期";
            case "CANCELLED", "CANCELED" -> "已取消";
            default -> "已发放";
        };
    }
 
 
    private void validateLockablePackage(TicketPackage ticketPackage) {
        if (ticketPackage == null || intValue(ticketPackage.getDeleted()) == 1) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "票包不存在");
        }
        if (intValue(ticketPackage.getStatus()) != 1) {
            throw new BusinessException(ErrorCode.CONFLICT, "票包当前不可发放");
        }
        LocalDate today = LocalDate.now();
        if (ticketPackage.getValidStart() != null && ticketPackage.getValidStart().isAfter(today)) {
            throw new BusinessException(ErrorCode.CONFLICT, "票包尚未开始发放");
        }
        if (ticketPackage.getValidEnd() != null && ticketPackage.getValidEnd().isBefore(today)) {
            throw new BusinessException(ErrorCode.CONFLICT, "票包已过期");
        }
    }
 
    private ClaimerInfo resolveClaimer(Long talentId, Long cardId, boolean lock) {
        if ((talentId == null || talentId <= 0) && (cardId == null || cardId <= 0)) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "持卡人ID或人才卡ID不能为空");
        }
        Map<String, Object> source = lock
                ? claimMapper.selectActiveCardSnapshotForUpdate(talentId, cardId)
                : claimMapper.selectActiveCardSnapshot(talentId, cardId);
        if (source == null || source.isEmpty()) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "有效人才卡不存在");
        }
        String cardType = text(source, "cardType", "card_type").toUpperCase(Locale.ROOT);
        if ("PERSONAL".equals(cardType) || cardType.isBlank()) {
            return new ClaimerInfo(
                    longValue(source, "talentId", "talent_id"),
                    longValue(source, "cardId", "card_id"),
                    text(source, "cardNo", "card_no"),
                    text(source, "cardLevel", "card_level"),
                    text(source, "talentName", "talent_name"),
                    text(source, "talentMobile", "talent_mobile"),
                    longValue(source, "cardId", "card_id"),
                    text(source, "cardLevel", "card_level")
            );
        }
        Map<String, Object> primary = lock
                ? claimMapper.selectPrimaryCardByFamilyCardForUpdate(longValue(source, "cardId", "card_id"))
                : claimMapper.selectPrimaryCardByFamilyCard(longValue(source, "cardId", "card_id"));
        if (primary == null || primary.isEmpty()) {
            throw new BusinessException(ErrorCode.CONFLICT, "亲属附属卡未找到有效主卡");
        }
        return new ClaimerInfo(
                longValue(source, "talentId", "talent_id"),
                longValue(source, "cardId", "card_id"),
                text(source, "cardNo", "card_no"),
                text(primary, "cardLevel", "card_level"),
                text(source, "talentName", "talent_name"),
                text(source, "talentMobile", "talent_mobile"),
                longValue(primary, "cardId", "card_id"),
                text(primary, "cardLevel", "card_level")
        );
    }
 
    private Map<String, Object> codeDetailView(Map<String, Object> row) {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("id", value(row, "id"));
        result.put("packageId", value(row, "packageId"));
        result.put("packageNo", text(row, "packageNo"));
        result.put("packageName", text(row, "packageName"));
        result.put("merchantId", value(row, "merchantId"));
        result.put("merchantName", text(row, "merchantName"));
        result.put("exchangeCode", text(row, "exchangeCode"));
        result.put("batchNo", text(row, "batchNo"));
        result.put("validStart", value(row, "validStart"));
        result.put("validEnd", value(row, "validEnd"));
        result.put("status", text(row, "status"));
        result.put("statusName", codeStatusName(text(row, "status")));
        result.put("lockedByTalentId", value(row, "lockedByTalentId"));
        result.put("lockedByCardId", value(row, "lockedByCardId"));
        result.put("lockedAt", value(row, "lockedAt"));
        result.put("issuedClaimId", value(row, "issuedClaimId"));
        result.put("issuedAt", value(row, "issuedAt"));
        result.put("usedAt", value(row, "usedAt"));
        result.put("claimNo", text(row, "claimNo"));
        result.put("claimStatus", text(row, "claimStatus"));
        result.put("claimTalentId", value(row, "claimTalentId"));
        result.put("claimTalentName", text(row, "claimTalentName"));
        result.put("claimTalentMobile", text(row, "claimTalentMobile"));
        result.put("claimCardNo", text(row, "claimCardNo"));
        result.put("claimCardLevel", text(row, "claimCardLevel"));
        result.put("remark", text(row, "remark"));
        result.put("createdAt", value(row, "createdAt"));
        result.put("updatedAt", value(row, "updatedAt"));
        return result;
    }
 
    private Map<String, Object> validationResult(boolean claimable, String reason, Map<String, Object> row) {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("found", row != null && !row.isEmpty());
        result.put("claimable", claimable);
        result.put("reason", reason);
        if (row != null && !row.isEmpty()) {
            result.put("codeId", value(row, "id"));
            result.put("exchangeCode", text(row, "exchangeCode"));
            result.put("packageId", value(row, "packageId"));
            result.put("packageNo", text(row, "packageNo"));
            result.put("packageName", text(row, "packageName"));
            result.put("merchantId", value(row, "merchantId"));
            result.put("merchantName", text(row, "merchantName"));
            result.put("validStart", value(row, "validStart"));
            result.put("validEnd", value(row, "validEnd"));
            result.put("status", text(row, "status"));
            result.put("statusName", codeStatusName(text(row, "status")));
            result.put("batchNo", text(row, "batchNo"));
            result.put("claimNo", text(row, "claimNo"));
            result.put("claimStatus", text(row, "claimStatus"));
            result.put("claimTalentName", text(row, "claimTalentName"));
            result.put("claimTalentMobile", text(row, "claimTalentMobile"));
            result.put("claimCardNo", text(row, "claimCardNo"));
            result.put("usedAt", value(row, "claimUsedAt"));
        }
        return result;
    }
 
    private String validationReason(Map<String, Object> row, Long merchantId) {
        if (intValue(value(row, "packageStatus")) != 1) {
            return "票包已停用";
        }
        LocalDate today = LocalDate.now();
        LocalDate validStart = toLocalDate(value(row, "validStart"));
        LocalDate validEnd = toLocalDate(value(row, "validEnd"));
        if (validStart != null && validStart.isAfter(today)) {
            return "票包尚未开始领取";
        }
        if (validEnd != null && validEnd.isBefore(today)) {
            return "票包已过期";
        }
        Long rowMerchantId = longValue(row, "merchantId");
        if (merchantId != null && rowMerchantId != null && !merchantId.equals(rowMerchantId)) {
            return "兑换码不适用于该商户";
        }
        return "";
    }
 
    private String codeStatusReason(String status) {
        return switch (clean(status).toUpperCase(Locale.ROOT)) {
            case "LOCKED" -> "兑换码已锁定";
            case "ISSUED" -> "兑换码已发放";
            case "USED" -> "兑换码已使用";
            case "VOID" -> "兑换码已作废";
            default -> "兑换码当前不可领取";
        };
    }
 
    private Map<String, Object> claimAdminView(TicketPackageClaim claim) {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("id", claim.getId());
        result.put("claimNo", claim.getClaimNo());
        result.put("packageId", claim.getPackageId());
        result.put("codeId", claim.getCodeId());
        result.put("merchantId", claim.getMerchantId());
        result.put("talentId", claim.getTalentId());
        result.put("cardId", claim.getCardId());
        result.put("primaryCardId", claim.getPrimaryCardId());
        result.put("cardNo", claim.getCardNo());
        result.put("cardLevel", claim.getCardLevel());
        result.put("talentName", claim.getTalentName());
        result.put("talentMobile", claim.getTalentMobile());
        result.put("exchangeCode", claim.getExchangeCode());
        result.put("status", claim.getStatus());
        result.put("statusName", claimStatusName(claim.getStatus()));
        result.put("validEnd", claim.getValidEnd());
        result.put("source", claimSource(claim.getIdempotencyKey()));
        result.put("sourceName", "MANUAL".equals(claimSource(claim.getIdempotencyKey())) ? "后台补录" : "线上领取");
        result.put("usedAt", claim.getUsedAt());
        result.put("createdAt", claim.getCreatedAt());
        result.put("updatedAt", claim.getUpdatedAt());
        return result;
    }
 
    private String claimSource(String idempotencyKey) {
        return clean(idempotencyKey).startsWith("MANUAL-") ? "MANUAL" : "CLAIM";
    }
 
    private LocalDate toLocalDate(Object value) {
        if (value instanceof LocalDate date) {
            return date;
        }
        if (value instanceof java.sql.Date date) {
            return date.toLocalDate();
        }
        if (value instanceof java.sql.Timestamp timestamp) {
            return timestamp.toLocalDateTime().toLocalDate();
        }
        return null;
    }
 
    private Long longValue(Map<String, Object> row, String... keys) {
        Object value = value(row, keys);
        return value instanceof Number number ? number.longValue() : null;
    }
 
    private record ClaimerInfo(
            Long talentId,
            Long cardId,
            String cardNo,
            String cardLevel,
            String talentName,
            String talentMobile,
            Long primaryCardId,
            String primaryCardLevel
    ) {
    }
    private Long requireId(Long id, String message) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, message);
        }
        return id;
    }
 
    private String cleanRequired(String value, String message) {
        String text = clean(value);
        if (text.isBlank()) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, message);
        }
        return text;
    }
 
    private Object value(Map<String, Object> row, String... keys) {
        for (String key : keys) {
            if (row.containsKey(key)) {
                return row.get(key);
            }
        }
        return null;
    }
 
    private String text(Map<String, Object> row, String... keys) {
        Object value = value(row, keys);
        return value == null ? "" : String.valueOf(value).trim();
    }
 
    private int intValue(Object value) {
        return value instanceof Number number ? number.intValue() : 0;
    }
 
    private String clean(String value) {
        return value == null ? "" : value.trim();
    }
}