yanderong
2026-07-27 39e943b054a6c62b22a6fe28199f17361807b143
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
package com.ruoyi.other.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.page.PageInfo;
import com.ruoyi.other.api.domain.TExchangeCodeDetail;
import com.ruoyi.other.api.domain.TExchangeCodePackage;
import com.ruoyi.other.api.domain.TExchangeCodePackageSpec;
import com.ruoyi.other.api.domain.TExchangeCodeUseRecord;
import com.ruoyi.other.api.dto.ExchangeCodeBindDTO;
import com.ruoyi.other.api.dto.ExchangeCodeConsumeDTO;
import com.ruoyi.other.api.dto.ExchangeCodePackageSaveDTO;
import com.ruoyi.other.api.dto.ExchangeCodePackageSpecDTO;
import com.ruoyi.other.api.dto.ExchangeCodeUseRecordQuery;
import com.ruoyi.other.api.vo.ExchangeCodeBindResultVO;
import com.ruoyi.other.api.vo.ExchangeCodeConsumeResultVO;
import com.ruoyi.other.api.vo.ExchangeCodePackageDetailVO;
import com.ruoyi.other.api.vo.ExchangeCodePackageSpecVO;
import com.ruoyi.other.mapper.TExchangeCodeDetailMapper;
import com.ruoyi.other.mapper.TExchangeCodePackageMapper;
import com.ruoyi.other.mapper.TExchangeCodePackageSpecMapper;
import com.ruoyi.other.mapper.TExchangeCodeUseRecordMapper;
import com.ruoyi.other.query.ExchangeCodeBatchInvalidDTO;
import com.ruoyi.other.query.ExchangeCodeDetailQuery;
import com.ruoyi.other.query.ExchangeCodePackageQuery;
import com.ruoyi.other.service.TExchangeCodePackageService;
import com.ruoyi.other.vo.ExchangeCodeBatchInvalidResultVO;
import com.ruoyi.other.vo.ExchangeCodeDetailVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
 
@Service
public class TExchangeCodePackageServiceImpl extends ServiceImpl<TExchangeCodePackageMapper, TExchangeCodePackage>
        implements TExchangeCodePackageService {
 
    private static final Integer STATUS_ENABLE = 1;
    private static final Integer STATUS_DISABLE = 2;
    private static final Integer CODE_STATUS_UNBOUND = 1;
    private static final Integer CODE_STATUS_BOUND = 2;
    private static final Integer CODE_STATUS_INVALID = 3;
    private static final Integer USE_RECORD_TYPE_EXCHANGE = 1;
    private static final Integer USE_RECORD_TYPE_CONSUME = 2;
    private static final Integer USE_RECORD_TYPE_REFUND = 3;
    private static final String EXPIRE_INVALID_REASON = "领取截止日期已过期";
    private static final DateTimeFormatter BATCH_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
 
    @Resource
    private TExchangeCodePackageSpecMapper packageSpecMapper;
 
    @Resource
    private TExchangeCodeDetailMapper codeDetailMapper;
 
    @Resource
    private TExchangeCodeUseRecordMapper useRecordMapper;
 
    /**
     * 分页查询兑换码卡包列表。
     *
     * @param query 查询条件
     * @return 卡包分页结果
     */
    @Override
    public PageInfo<TExchangeCodePackage> pageList(ExchangeCodePackageQuery query) {
        PageInfo<TExchangeCodePackage> pageInfo = new PageInfo<>(query.getPageCurr(), query.getPageSize());
        List<TExchangeCodePackage> records = this.baseMapper.pageList(pageInfo, query);
        pageInfo.setRecords(records);
        return pageInfo;
    }
 
    /**
     * 新增兑换码卡包。
     *
     * @param dto 卡包保存参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePackage(ExchangeCodePackageSaveDTO dto) {
        validateSaveDTO(dto, false);
        TExchangeCodePackage entity = buildPackageEntity(dto, new TExchangeCodePackage());
        this.save(entity);
        saveSpecsAndCodes(entity.getId(), dto.getSpecList(), dto.getInventory(), null);
        refreshPackageStats(entity.getId());
    }
 
    /**
     * 编辑兑换码卡包。
     *
     * @param dto 卡包保存参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePackage(ExchangeCodePackageSaveDTO dto) {
        if (dto.getId() == null) {
            throw new ServiceException("卡包ID不能为空");
        }
        validateSaveDTO(dto, true);
        TExchangeCodePackage old = this.getById(dto.getId());
        if (old == null) {
            throw new ServiceException("卡包不存在");
        }
        if (dto.getInventory() < old.getInventory()) {
            throw new ServiceException("编辑时库存只能增加");
        }
        TExchangeCodePackage entity = buildPackageEntity(dto, old);
        this.updateById(entity);
        packageSpecMapper.delete(new QueryWrapper<TExchangeCodePackageSpec>().eq("package_id", dto.getId()));
        saveSpecsAndCodes(dto.getId(), dto.getSpecList(), dto.getInventory(), old.getInventory());
        refreshPackageStats(dto.getId());
    }
 
    /**
     * 更新兑换码卡包启用状态。
     *
     * @param id 卡包ID
     * @param status 启用状态
     */
    @Override
    public void updatePackageStatus(Long id, Integer status) {
        if (id == null) {
            throw new ServiceException("卡包ID不能为空");
        }
        if (!STATUS_ENABLE.equals(status) && !STATUS_DISABLE.equals(status)) {
            throw new ServiceException("启用状态不正确");
        }
        TExchangeCodePackage old = this.getById(id);
        if (old == null) {
            throw new ServiceException("卡包不存在");
        }
        TExchangeCodePackage entity = new TExchangeCodePackage();
        entity.setId(id);
        entity.setStatus(status);
        this.updateById(entity);
    }
 
    /**
     * 刷新所有已过领取截止日期的兑换码卡包未绑定兑换码状态。
     */
    @Override
    public void refreshExpiredPackageCodes() {
        List<TExchangeCodePackage> expiredPackages = this.list(new QueryWrapper<TExchangeCodePackage>()
                .isNotNull("expire_time")
                .lt("expire_time", LocalDateTime.now())
                .eq("del_flag", 0));
        for (TExchangeCodePackage exchangePackage : expiredPackages) {
            refreshExpiredPackageCodes(exchangePackage.getId());
        }
    }
 
    /**
     * 删除兑换码卡包。
     *
     * @param ids 卡包ID,多个ID用英文逗号分隔
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePackage(String ids) {
        if (!StringUtils.hasText(ids)) {
            throw new ServiceException("卡包ID不能为空");
        }
        List<Long> idList = Arrays.stream(ids.split(","))
                .filter(StringUtils::hasText)
                .map(Long::valueOf)
                .collect(Collectors.toList());
        if (idList.isEmpty()) {
            throw new ServiceException("卡包ID不能为空");
        }
        Long boundCount = codeDetailMapper.selectCount(new QueryWrapper<TExchangeCodeDetail>()
                .in("package_id", idList)
                .eq("status", CODE_STATUS_BOUND)
                .eq("del_flag", 0));
        if (boundCount != null && boundCount > 0) {
            throw new ServiceException("存在已绑定兑换码,不允许删除");
        }
        this.removeByIds(idList);
        packageSpecMapper.delete(new QueryWrapper<TExchangeCodePackageSpec>().in("package_id", idList));
        codeDetailMapper.delete(new QueryWrapper<TExchangeCodeDetail>().in("package_id", idList));
    }
 
    /**
     * 查询兑换码卡包详情。
     *
     * @param id 卡包ID
     * @return 卡包详情
     */
    @Override
    public ExchangeCodePackageDetailVO getDetail(Long id) {
        TExchangeCodePackage entity = this.getById(id);
        if (entity == null) {
            throw new ServiceException("卡包不存在");
        }
        refreshExpiredPackageCodes(id);
        refreshPackageStats(id);
        entity = this.getById(id);
        ExchangeCodePackageDetailVO detailVO = new ExchangeCodePackageDetailVO();
        BeanUtils.copyProperties(entity, detailVO);
        List<TExchangeCodePackageSpec> specs = packageSpecMapper.selectList(new QueryWrapper<TExchangeCodePackageSpec>()
                .eq("package_id", id)
                .orderByAsc("sort", "id"));
        List<ExchangeCodePackageSpecVO> specVOList = new ArrayList<>();
        for (TExchangeCodePackageSpec spec : specs) {
            ExchangeCodePackageSpecVO vo = new ExchangeCodePackageSpecVO();
            BeanUtils.copyProperties(spec, vo);
            Long boundCount = codeDetailMapper.selectCount(new QueryWrapper<TExchangeCodeDetail>()
                    .eq("package_spec_id", spec.getId())
                    .eq("status", CODE_STATUS_BOUND)
                    .eq("del_flag", 0));
            Long unboundCount = codeDetailMapper.selectCount(new QueryWrapper<TExchangeCodeDetail>()
                    .eq("package_spec_id", spec.getId())
                    .eq("status", CODE_STATUS_UNBOUND)
                    .eq("del_flag", 0));
            vo.setBoundCount(boundCount == null ? 0 : boundCount.intValue());
            vo.setUnboundCount(unboundCount == null ? 0 : unboundCount.intValue());
            specVOList.add(vo);
        }
        detailVO.setSpecList(specVOList);
        return detailVO;
    }
 
    /**
     * 分页查询兑换码明细。
     *
     * @param query 查询条件
     * @return 兑换码明细分页结果
     */
    @Override
    public PageInfo<ExchangeCodeDetailVO> codePage(ExchangeCodeDetailQuery query) {
        refreshExpiredPackageCodes(query.getPackageId());
        PageInfo<ExchangeCodeDetailVO> pageInfo = new PageInfo<>(query.getPageCurr(), query.getPageSize());
        List<ExchangeCodeDetailVO> records = codeDetailMapper.pageList(pageInfo, query);
        pageInfo.setRecords(records);
        return pageInfo;
    }
 
    /**
     * 导出兑换码明细。
     *
     * @param query 查询条件
     * @return 兑换码明细导出数据
     */
    @Override
    public List<ExchangeCodeDetailVO> exportCodes(ExchangeCodeDetailQuery query) {
        refreshExpiredPackageCodes(query.getPackageId());
        return codeDetailMapper.exportList(query);
    }
 
    /**
     * 批量失效兑换码。
     *
     * @param dto 失效参数
     * @return 失效结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExchangeCodeBatchInvalidResultVO batchInvalidate(ExchangeCodeBatchInvalidDTO dto) {
        if (dto.getPackageId() == null || dto.getDetailIds() == null || dto.getDetailIds().isEmpty()) {
            throw new ServiceException("请选择需要失效的兑换码");
        }
        int success = 0;
        int skip = 0;
        List<TExchangeCodeDetail> details = codeDetailMapper.selectBatchIds(dto.getDetailIds());
        for (TExchangeCodeDetail detail : details) {
            if (!Objects.equals(detail.getPackageId(), dto.getPackageId())) {
                continue;
            }
            if (Objects.equals(detail.getStatus(), CODE_STATUS_UNBOUND)) {
                detail.setStatus(CODE_STATUS_INVALID);
                detail.setInvalidTime(LocalDateTime.now());
                detail.setInvalidReason("后台批量失效");
                codeDetailMapper.updateById(detail);
                success++;
            } else {
                skip++;
            }
        }
        refreshPackageStats(dto.getPackageId());
        return new ExchangeCodeBatchInvalidResultVO(success, skip);
    }
 
    /**
     * 查询可下载二维码的兑换码列表。
     *
     * @param packageId 卡包ID
     * @param onlyUnbound 是否只查询未绑定兑换码
     * @return 可下载二维码的兑换码列表
     */
    @Override
    public List<ExchangeCodeDetailVO> listDownloadableCodes(Long packageId, boolean onlyUnbound) {
        ExchangeCodeDetailQuery query = new ExchangeCodeDetailQuery();
        query.setPackageId(packageId);
        if (onlyUnbound) {
            query.setStatus(CODE_STATUS_UNBOUND);
        }
        return exportCodes(query);
    }
 
    /**
     * 查询兑换码明细。
     *
     * @param id 兑换码明细ID
     * @return 兑换码明细
     */
    @Override
    public ExchangeCodeDetailVO getCodeDetail(Long id) {
        TExchangeCodeDetail detail = codeDetailMapper.selectById(id);
        if (detail == null || Boolean.TRUE.equals(detail.getDelFlag())) {
            throw new ServiceException("兑换码不存在");
        }
        ExchangeCodeDetailVO vo = new ExchangeCodeDetailVO();
        BeanUtils.copyProperties(detail, vo);
        if (detail.getPackageSpecId() != null) {
            TExchangeCodePackageSpec spec = packageSpecMapper.selectById(detail.getPackageSpecId());
            if (spec != null) {
                vo.setAmount(spec.getAmount());
                vo.setQuantity(spec.getQuantity());
            }
        }
        return vo;
    }
 
    /**
     * 绑定兑换码。
     *
     * @param dto 绑定参数
     * @param userId 用户ID
     * @param phone 手机号
     * @return 绑定结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExchangeCodeBindResultVO bindExchangeCode(ExchangeCodeBindDTO dto, Long userId, String phone) {
        if (!StringUtils.hasText(dto.getCode()) || !StringUtils.hasText(dto.getPassword())) {
            throw new ServiceException("兑换码或密码不能为空");
        }
        TExchangeCodeDetail detail = codeDetailMapper.selectOne(new QueryWrapper<TExchangeCodeDetail>()
                .eq("code", dto.getCode())
                .eq("password", dto.getPassword())
                .last("limit 1"));
        if (detail == null) {
            throw new ServiceException("兑换码或密码错误");
        }
        TExchangeCodePackage exchangePackage = this.getById(detail.getPackageId());
        if (exchangePackage == null || !Objects.equals(exchangePackage.getStatus(), STATUS_ENABLE)) {
            throw new ServiceException("卡包已下架");
        }
        if (exchangePackage.getExpireTime() != null && exchangePackage.getExpireTime().isBefore(LocalDateTime.now())) {
            refreshExpiredPackageCodes(exchangePackage.getId());
            throw new ServiceException("已失效");
        }
        if (Objects.equals(detail.getStatus(), CODE_STATUS_INVALID)) {
            throw new ServiceException("卡号失效");
        }
        if (Objects.equals(detail.getStatus(), CODE_STATUS_BOUND)) {
            throw new ServiceException("兑换码已绑定");
        }
        String bindPhone = StringUtils.hasText(phone) ? phone : dto.getPhone();
        if (!StringUtils.hasText(bindPhone)) {
            throw new ServiceException("绑定手机号不能为空");
        }
        if (exchangePackage.getReceiveLimit() != null && exchangePackage.getReceiveLimit() > 0) {
            Long bindCount = codeDetailMapper.selectCount(new QueryWrapper<TExchangeCodeDetail>()
                    .eq("package_id", exchangePackage.getId())
                    .eq("bind_phone", bindPhone)
                    .eq("status", CODE_STATUS_BOUND)
                    .eq("del_flag", 0));
            if (bindCount >= exchangePackage.getReceiveLimit()) {
                throw new ServiceException("该手机号领取次数已达上限");
            }
        }
        detail.setStatus(CODE_STATUS_BOUND);
        detail.setBindUserId(userId);
        detail.setBindPhone(bindPhone);
        detail.setBindTime(LocalDateTime.now());
        codeDetailMapper.updateById(detail);
        BigDecimal amount = getDetailRemainAmount(detail);
        TExchangeCodeUseRecord record = new TExchangeCodeUseRecord();
        record.setDetailId(detail.getId());
        record.setOrderId(0L);
        record.setUserId(userId);
        record.setChangeType(USE_RECORD_TYPE_EXCHANGE);
        record.setUsedAmount(amount);
        record.setGiftUsedAmount(defaultMoney(detail.getGiftAmount()));
        useRecordMapper.insert(record);
        refreshPackageStats(exchangePackage.getId());
        ExchangeCodeBindResultVO resultVO = new ExchangeCodeBindResultVO();
        resultVO.setDetailId(detail.getId());
        resultVO.setPackageId(exchangePackage.getId());
        resultVO.setPackageName(exchangePackage.getPackageName());
        resultVO.setBindPhone(bindPhone);
        return resultVO;
    }
 
    /**
     * 分页查询兑换码余额流水。
     *
     * @param query 查询条件
     * @return 流水分页结果
     */
    @Override
    public Page<TExchangeCodeUseRecord> useRecordPage(ExchangeCodeUseRecordQuery query) {
        Page<TExchangeCodeUseRecord> page = useRecordMapper.selectPage(Page.of(query.getPageCurr(), query.getPageSize()),
                new QueryWrapper<TExchangeCodeUseRecord>()
                        .eq("user_id", query.getUserId())
                        .eq(query.getChangeType() != null, "change_type", query.getChangeType())
                        .orderByDesc("create_time"));
        fillUseRecordBalances(page.getRecords(), query.getUserId());
        List<TExchangeCodeUseRecord> mergedRecords = mergeUseRecords(page.getRecords());
        mergedRecords.forEach(this::fillUseRecordView);
        page.setRecords(mergedRecords);
        return page;
    }
 
    /**
     * 查询兑换码余额流水详情。
     *
     * @param id 流水ID
     * @param userId 用户ID
     * @return 流水详情
     */
    @Override
    public TExchangeCodeUseRecord useRecordDetail(Long id, Long userId) {
        TExchangeCodeUseRecord record = useRecordMapper.selectOne(new QueryWrapper<TExchangeCodeUseRecord>()
                .eq("id", id)
                .eq("user_id", userId)
                .last("limit 1"));
        fillUseRecordBalance(record, userId);
        fillUseRecordView(record);
        return record;
    }
 
    /**
     * 查询用户兑换码余额映射。
     *
     * @param userIds 用户ID集合
     * @return 用户余额映射
     */
    @Override
    public Map<Long, BigDecimal> getUserExchangeCodeBalanceMap(List<Long> userIds) {
        Map<Long, BigDecimal> result = new HashMap<>();
        if (userIds == null || userIds.isEmpty()) {
            return result;
        }
        List<TExchangeCodeDetail> details = codeDetailMapper.selectList(new QueryWrapper<TExchangeCodeDetail>()
                .in("bind_user_id", userIds)
                .eq("status", CODE_STATUS_BOUND)
                .eq("del_flag", 0));
        for (TExchangeCodeDetail detail : details) {
            BigDecimal remainAmount = getDetailRemainAmount(detail);
            if (remainAmount.compareTo(BigDecimal.ZERO) > 0) {
                result.merge(detail.getBindUserId(), remainAmount, BigDecimal::add);
            }
        }
        return result;
    }
 
    /**
     * 扣减用户兑换码余额。
     *
     * @param dto 扣减参数
     * @return 扣减结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExchangeCodeConsumeResultVO consumeBalance(ExchangeCodeConsumeDTO dto) {
        if (dto == null || dto.getUserId() == null || dto.getOrderId() == null || dto.getAmount() == null) {
            throw new ServiceException("扣减参数不能为空");
        }
        ExchangeCodeConsumeResultVO resultVO = new ExchangeCodeConsumeResultVO();
        BigDecimal requestedAmount = dto.getAmount().setScale(2, RoundingMode.HALF_UP);
        if (requestedAmount.compareTo(BigDecimal.ZERO) <= 0) {
            resultVO.setDeductedAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP));
            return resultVO;
        }
        List<TExchangeCodeUseRecord> existingRecords = useRecordMapper.selectList(new QueryWrapper<TExchangeCodeUseRecord>()
                .eq("order_id", dto.getOrderId())
                .gt("order_id", 0)
                .eq("change_type", USE_RECORD_TYPE_CONSUME)
                .eq("del_flag", 0));
        if (!existingRecords.isEmpty()) {
            BigDecimal deducted = existingRecords.stream()
                    .map(TExchangeCodeUseRecord::getUsedAmount)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .setScale(2, RoundingMode.HALF_UP);
            resultVO.setDeductedAmount(deducted);
            return resultVO;
        }
        BigDecimal remainingNeed = requestedAmount;
        BigDecimal deductedAmount = BigDecimal.ZERO;
        List<TExchangeCodeDetail> details = codeDetailMapper.selectList(new QueryWrapper<TExchangeCodeDetail>()
                .eq("bind_user_id", dto.getUserId())
                .eq("status", CODE_STATUS_BOUND)
                .eq("del_flag", 0)
                .orderByAsc("bind_time", "id"));
        for (TExchangeCodeDetail detail : details) {
            if (remainingNeed.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
            BigDecimal remainAmount = getDetailRemainAmount(detail);
            if (remainAmount.compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            BigDecimal useAmount = remainAmount.min(remainingNeed).setScale(2, RoundingMode.HALF_UP);
            detail.setUsedAmount(defaultMoney(detail.getUsedAmount()).add(useAmount).setScale(2, RoundingMode.HALF_UP));
            codeDetailMapper.updateById(detail);
            TExchangeCodeUseRecord record = new TExchangeCodeUseRecord();
            record.setDetailId(detail.getId());
            record.setOrderId(dto.getOrderId());
            record.setUserId(dto.getUserId());
            record.setChangeType(USE_RECORD_TYPE_CONSUME);
            record.setUsedAmount(useAmount);
            record.setGiftUsedAmount(calculateGiftUsedAmount(useAmount, detail));
            useRecordMapper.insert(record);
            remainingNeed = remainingNeed.subtract(useAmount);
            deductedAmount = deductedAmount.add(useAmount);
        }
        resultVO.setDeductedAmount(deductedAmount.setScale(2, RoundingMode.HALF_UP));
        return resultVO;
    }
 
    /**
     * 退款返还用户兑换码余额。
     *
     * @param dto 退款参数
     * @return 退款结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExchangeCodeConsumeResultVO refundBalance(ExchangeCodeConsumeDTO dto) {
        if (dto == null || dto.getUserId() == null || dto.getOrderId() == null || dto.getAmount() == null) {
            throw new ServiceException("参数异常");
        }
        ExchangeCodeConsumeResultVO resultVO = new ExchangeCodeConsumeResultVO();
        BigDecimal remainingRefund = dto.getAmount().setScale(2, RoundingMode.HALF_UP);
        if (remainingRefund.compareTo(BigDecimal.ZERO) <= 0) {
            resultVO.setDeductedAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP));
            return resultVO;
        }
        List<TExchangeCodeUseRecord> existingRecords = useRecordMapper.selectList(new QueryWrapper<TExchangeCodeUseRecord>()
                .eq("order_id", dto.getOrderId())
                .eq("change_type", USE_RECORD_TYPE_REFUND)
                .eq(dto.getRefundNo() != null && !dto.getRefundNo().isEmpty(), "refund_no", dto.getRefundNo())
                .eq("del_flag", 0));
        if (!existingRecords.isEmpty()) {
            BigDecimal refunded = existingRecords.stream()
                    .map(TExchangeCodeUseRecord::getUsedAmount)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add)
                    .setScale(2, RoundingMode.HALF_UP);
            resultVO.setDeductedAmount(refunded);
            return resultVO;
        }
        List<TExchangeCodeUseRecord> consumeRecords = useRecordMapper.selectList(new QueryWrapper<TExchangeCodeUseRecord>()
                .eq("order_id", dto.getOrderId())
                .eq("user_id", dto.getUserId())
                .eq("change_type", USE_RECORD_TYPE_CONSUME)
                .eq("del_flag", 0)
                .orderByDesc("id"));
        BigDecimal refundedAmount = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        for (TExchangeCodeUseRecord consumeRecord : consumeRecords) {
            if (remainingRefund.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
            if (consumeRecord.getDetailId() == null) {
                continue;
            }
            TExchangeCodeDetail detail = codeDetailMapper.selectById(consumeRecord.getDetailId());
            if (detail == null) {
                continue;
            }
            BigDecimal useAmount = defaultMoney(consumeRecord.getUsedAmount());
            BigDecimal refundAmount = remainingRefund.min(useAmount).setScale(2, RoundingMode.HALF_UP);
            detail.setUsedAmount(defaultMoney(detail.getUsedAmount()).subtract(refundAmount).max(BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP));
            codeDetailMapper.updateById(detail);
            TExchangeCodeUseRecord record = new TExchangeCodeUseRecord();
            record.setDetailId(detail.getId());
            record.setOrderId(dto.getOrderId());
            record.setRefundNo(dto.getRefundNo());
            record.setUserId(dto.getUserId());
            record.setChangeType(USE_RECORD_TYPE_REFUND);
            record.setUsedAmount(refundAmount);
            record.setGiftUsedAmount(calculateGiftUsedAmount(refundAmount, detail));
            useRecordMapper.insert(record);
            remainingRefund = remainingRefund.subtract(refundAmount);
            refundedAmount = refundedAmount.add(refundAmount);
        }
        resultVO.setDeductedAmount(refundedAmount.setScale(2, RoundingMode.HALF_UP));
        return resultVO;
    }
 
    /**
     * 根据兑换码明细记录的赠送比例计算本次使用金额中的赠送金额。
     *
     * @param useAmount 本次使用金额
     * @param detail 兑换码明细
     * @return 本次使用金额对应的赠送金额
     */
    private BigDecimal calculateGiftUsedAmount(BigDecimal useAmount, TExchangeCodeDetail detail) {
        if (useAmount == null || detail == null || detail.getGiftRatio() == null) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        return useAmount.multiply(detail.getGiftRatio()).setScale(2, RoundingMode.HALF_UP);
    }
 
    /**
     * 查询兑换码明细当前剩余可用金额。
     *
     * @param detail 兑换码明细
     * @return 剩余可用金额
     */
    private BigDecimal getDetailRemainAmount(TExchangeCodeDetail detail) {
        if (detail == null || detail.getPackageSpecId() == null) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        TExchangeCodePackageSpec spec = packageSpecMapper.selectById(detail.getPackageSpecId());
        if (spec == null || spec.getAmount() == null) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        BigDecimal remainAmount = spec.getAmount().subtract(defaultMoney(detail.getUsedAmount()));
        return remainAmount.compareTo(BigDecimal.ZERO) < 0
                ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)
                : remainAmount.setScale(2, RoundingMode.HALF_UP);
    }
 
    /**
     * 将保存参数转换为兑换码卡包实体。
     *
     * @param dto 卡包保存参数
     * @param entity 待填充的卡包实体
     * @return 填充后的卡包实体
     */
    private TExchangeCodePackage buildPackageEntity(ExchangeCodePackageSaveDTO dto, TExchangeCodePackage entity) {
        entity.setPackageName(dto.getPackageName());
        entity.setCoverPicture(dto.getCoverPicture());
        entity.setDetailsPicture(dto.getDetailsPicture());
        entity.setExchangeDescription(dto.getExchangeDescription());
        entity.setRemark(dto.getRemark());
        entity.setInventory(dto.getInventory());
        entity.setUnlimitedReceiveLimit(dto.getUnlimitedReceiveLimit());
        entity.setReceiveLimit(Objects.equals(dto.getUnlimitedReceiveLimit(), 1) ? null : dto.getReceiveLimit());
        entity.setFinanceReceivedAmount(defaultMoney(dto.getFinanceReceivedAmount()));
        entity.setGiftAmount(defaultMoney(dto.getGiftAmount()));
        entity.setTotalAmount(defaultMoney(dto.getTotalAmount()));
        entity.setExpireTime(dto.getExpireTime());
        entity.setStatus(dto.getStatus());
        return entity;
    }
 
    /**
     * 校验兑换码卡包新增或编辑参数。
     *
     * @param dto 卡包保存参数
     * @param editing 是否为编辑场景
     */
    private void validateSaveDTO(ExchangeCodePackageSaveDTO dto, boolean editing) {
        if (!StringUtils.hasText(dto.getPackageName())) {
            throw new ServiceException("请输入卡包名称");
        }
        if (dto.getInventory() == null || dto.getInventory() <= 0) {
            throw new ServiceException("库存必须大于0");
        }
        if (dto.getExpireTime() != null && dto.getExpireTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException("截止领取时间不能早于当前时间");
        }
        if (!Objects.equals(dto.getUnlimitedReceiveLimit(), 1)
                && (dto.getReceiveLimit() == null || dto.getReceiveLimit() <= 0)) {
            throw new ServiceException("请输入领取限制次数");
        }
        if (dto.getSpecList() == null || dto.getSpecList().isEmpty()) {
            throw new ServiceException("请至少添加一个规格");
        }
        if (dto.getStatus() == null) {
            dto.setStatus(STATUS_DISABLE);
        }
        BigDecimal finance = defaultMoney(dto.getFinanceReceivedAmount());
        BigDecimal gift = defaultMoney(dto.getGiftAmount());
        BigDecimal total = defaultMoney(dto.getTotalAmount());
        if (finance.add(gift).compareTo(total) != 0) {
            throw new ServiceException("财务实收 + 赠送金额 必须等于规格总金额");
        }
        BigDecimal specTotal = BigDecimal.ZERO;
        int quantityTotal = 0;
        for (ExchangeCodePackageSpecDTO spec : dto.getSpecList()) {
            if (spec.getAmount() == null || spec.getAmount().compareTo(BigDecimal.ZERO) < 0) {
                throw new ServiceException("规格金额不正确");
            }
            if (spec.getQuantity() == null || spec.getQuantity() <= 0) {
                throw new ServiceException("规格数量必须大于0");
            }
            BigDecimal subtotal = spec.getAmount().multiply(BigDecimal.valueOf(spec.getQuantity()))
                    .setScale(2, RoundingMode.HALF_UP);
            spec.setSubtotalAmount(subtotal);
            specTotal = specTotal.add(subtotal);
            quantityTotal += spec.getQuantity();
        }
        if (specTotal.compareTo(total) != 0) {
            throw new ServiceException("总额必须等于所有规格金额乘数量之和");
        }
        if (quantityTotal != dto.getInventory()) {
            throw new ServiceException(editing ? "编辑后的库存必须等于规格数量总和" : "库存必须等于规格数量总和");
        }
        allocateDiscount(dto.getSpecList(), gift, total);
    }
 
    /**
     * 按规格小计占比分摊卡包赠送金额。
     *
     * @param specList 规格列表
     * @param giftAmount 赠送金额
     * @param totalAmount 卡包总金额
     */
    private void allocateDiscount(List<ExchangeCodePackageSpecDTO> specList, BigDecimal giftAmount, BigDecimal totalAmount) {
        if (giftAmount.compareTo(BigDecimal.ZERO) == 0 || totalAmount.compareTo(BigDecimal.ZERO) == 0) {
            for (ExchangeCodePackageSpecDTO spec : specList) {
                spec.setDiscountAmount(BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP));
            }
            return;
        }
        BigDecimal allocated = BigDecimal.ZERO;
        for (int i = 0; i < specList.size(); i++) {
            ExchangeCodePackageSpecDTO spec = specList.get(i);
            BigDecimal discount;
            if (i == specList.size() - 1) {
                discount = giftAmount.subtract(allocated).setScale(2, RoundingMode.HALF_UP);
            } else {
                discount = spec.getSubtotalAmount().multiply(giftAmount)
                        .divide(totalAmount, 2, RoundingMode.HALF_UP);
                allocated = allocated.add(discount);
            }
            spec.setDiscountAmount(discount);
        }
    }
 
    /**
     * 保存兑换码规格并按新增库存生成兑换码明细。
     *
     * @param packageId 卡包ID
     * @param specList 规格列表
     * @param inventory 当前库存
     * @param oldInventory 编辑前库存,新增场景为空
     */
    private void saveSpecsAndCodes(Long packageId, List<ExchangeCodePackageSpecDTO> specList, Integer inventory, Integer oldInventory) {
        List<TExchangeCodePackageSpec> specEntities = new ArrayList<>();
        for (int i = 0; i < specList.size(); i++) {
            ExchangeCodePackageSpecDTO spec = specList.get(i);
            TExchangeCodePackageSpec entity = new TExchangeCodePackageSpec();
            entity.setPackageId(packageId);
            entity.setAmount(spec.getAmount());
            entity.setQuantity(spec.getQuantity());
            entity.setSubtotalAmount(spec.getSubtotalAmount());
            entity.setDiscountAmount(spec.getDiscountAmount());
            entity.setSort(spec.getSort() == null ? i + 1 : spec.getSort());
            packageSpecMapper.insert(entity);
            specEntities.add(entity);
        }
        int needCreate = oldInventory == null ? inventory : inventory - oldInventory;
        if (needCreate <= 0) {
            return;
        }
        String batchNo = "PKG" + LocalDateTime.now().format(BATCH_FORMATTER);
        TExchangeCodePackage exchangePackage = this.getById(packageId);
        BigDecimal giftRatio = calculateGiftRatio(exchangePackage);
        List<TExchangeCodePackageSpec> expandList = new ArrayList<>();
        for (TExchangeCodePackageSpec spec : specEntities) {
            for (int i = 0; i < spec.getQuantity(); i++) {
                expandList.add(spec);
            }
        }
        if (expandList.isEmpty()) {
            expandList = Collections.nCopies(needCreate, null);
        }
        for (int i = 0; i < needCreate; i++) {
            TExchangeCodePackageSpec spec = expandList.get(i % expandList.size());
            TExchangeCodeDetail detail = new TExchangeCodeDetail();
            detail.setPackageId(packageId);
            detail.setPackageSpecId(spec == null ? null : spec.getId());
            detail.setCode(generateCode(packageId, i));
            detail.setPassword(generatePassword());
            detail.setStatus(CODE_STATUS_UNBOUND);
            detail.setGiftRatio(giftRatio);
            detail.setGiftAmount(calculateDetailGiftAmount(spec, giftRatio));
            detail.setBatchNo(batchNo);
            codeDetailMapper.insert(detail);
        }
    }
 
    /**
     * 计算卡包赠送金额占总金额的比例。
     *
     * @param exchangePackage 兑换码卡包
     * @return 赠送金额比例
     */
    private BigDecimal calculateGiftRatio(TExchangeCodePackage exchangePackage) {
        if (exchangePackage == null || exchangePackage.getTotalAmount() == null
                || exchangePackage.getTotalAmount().compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO.setScale(6, RoundingMode.HALF_UP);
        }
        return defaultMoney(exchangePackage.getGiftAmount())
                .divide(exchangePackage.getTotalAmount(), 6, RoundingMode.HALF_UP);
    }
 
    /**
     * 计算单个兑换码对应的赠送金额。
     *
     * @param spec 兑换码规格
     * @param giftRatio 赠送金额比例
     * @return 单个兑换码赠送金额
     */
    private BigDecimal calculateDetailGiftAmount(TExchangeCodePackageSpec spec, BigDecimal giftRatio) {
        if (spec == null || spec.getAmount() == null || giftRatio == null) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        return spec.getAmount().multiply(giftRatio).setScale(2, RoundingMode.HALF_UP);
    }
 
    /**
     * 刷新兑换码卡包的已绑定、已失效和未绑定数量。
     *
     * @param packageId 卡包ID
     */
    private void refreshPackageStats(Long packageId) {
        TExchangeCodePackage entity = this.getById(packageId);
        if (entity == null) {
            return;
        }
        Long boundCount = codeDetailMapper.selectCount(new QueryWrapper<TExchangeCodeDetail>()
                .eq("package_id", packageId)
                .eq("status", CODE_STATUS_BOUND)
                .eq("del_flag", 0));
        Long invalidCount = codeDetailMapper.selectCount(new QueryWrapper<TExchangeCodeDetail>()
                .eq("package_id", packageId)
                .eq("status", CODE_STATUS_INVALID)
                .eq("del_flag", 0));
        entity.setBoundCount(boundCount.intValue());
        entity.setInvalidCount(invalidCount.intValue());
        entity.setUnboundCount(entity.getInventory() - entity.getBoundCount() - entity.getInvalidCount());
        this.baseMapper.updateById(entity);
    }
 
    /**
     * 将已过领取截止日期卡包下未绑定的兑换码刷新为已失效。
     *
     * @param packageId 卡包ID
     */
    private void refreshExpiredPackageCodes(Long packageId) {
        if (packageId == null) {
            return;
        }
        TExchangeCodePackage exchangePackage = this.getById(packageId);
        if (exchangePackage == null || exchangePackage.getExpireTime() == null
                || !exchangePackage.getExpireTime().isBefore(LocalDateTime.now())) {
            return;
        }
        TExchangeCodeDetail detail = new TExchangeCodeDetail();
        detail.setStatus(CODE_STATUS_INVALID);
        detail.setInvalidTime(LocalDateTime.now());
        detail.setInvalidReason(EXPIRE_INVALID_REASON);
        codeDetailMapper.update(detail, new QueryWrapper<TExchangeCodeDetail>()
                .eq("package_id", packageId)
                .eq("status", CODE_STATUS_UNBOUND)
                .eq("del_flag", 0));
        refreshPackageStats(packageId);
    }
 
    /**
     * 生成兑换码卡号。
     *
     * @param packageId 卡包ID
     * @param seq 当前批次序号
     * @return 兑换码卡号
     */
    private String generateCode(Long packageId, int seq) {
        return "CD" + packageId + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss")) + String.format("%03d", seq);
    }
 
    /**
     * 生成兑换码密码。
     *
     * @return 兑换码密码
     */
    private String generatePassword() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 8).toUpperCase();
    }
 
    /**
     * 合并同一订单或同一兑换码维度的余额流水展示记录。
     *
     * @param records 原始流水列表
     * @return 合并后的流水列表
     */
    private List<TExchangeCodeUseRecord> mergeUseRecords(List<TExchangeCodeUseRecord> records) {
        if (records == null || records.isEmpty()) {
            return records;
        }
        Map<String, TExchangeCodeUseRecord> recordMap = new LinkedHashMap<>();
        for (TExchangeCodeUseRecord record : records) {
            String key = buildUseRecordMergeKey(record);
            TExchangeCodeUseRecord merged = recordMap.get(key);
            if (merged == null) {
                recordMap.put(key, record);
                continue;
            }
            merged.setUsedAmount(defaultMoney(merged.getUsedAmount()).add(defaultMoney(record.getUsedAmount())).setScale(2, RoundingMode.HALF_UP));
            merged.setGiftUsedAmount(defaultMoney(merged.getGiftUsedAmount()).add(defaultMoney(record.getGiftUsedAmount())).setScale(2, RoundingMode.HALF_UP));
            if (record.getId() != null && merged.getId() != null && record.getId() > merged.getId()) {
                merged.setId(record.getId());
                merged.setDetailId(record.getDetailId());
                merged.setCreateTime(record.getCreateTime());
                merged.setDateTime(record.getDateTime());
                merged.setCurrentBalance(record.getCurrentBalance());
            }
        }
        return new ArrayList<>(recordMap.values());
    }
 
    /**
     * 构建余额流水合并键。
     *
     * @param record 余额流水记录
     * @return 流水合并键
     */
    private String buildUseRecordMergeKey(TExchangeCodeUseRecord record) {
        Long orderId = record.getOrderId() == null ? 0L : record.getOrderId();
        Long detailId = record.getDetailId() == null ? 0L : record.getDetailId();
        Integer changeType = record.getChangeType() == null ? 0 : record.getChangeType();
        String refundNo = record.getRefundNo() == null ? "" : record.getRefundNo();
        if (orderId > 0) {
            return orderId + "_" + changeType + "_" + refundNo;
        }
        return detailId + "_" + changeType + "_" + refundNo;
    }
 
    /**
     * 填充单条余额流水发生后的用户当前余额。
     *
     * @param record 余额流水记录
     * @param userId 用户ID
     */
    private void fillUseRecordBalance(TExchangeCodeUseRecord record, Long userId) {
        if (record == null || userId == null || record.getId() == null) {
            return;
        }
        record.setCurrentBalance(calculateCurrentBalanceAfterRecord(userId, record.getId()));
    }
 
    /**
     * 批量填充余额流水发生后的用户当前余额。
     *
     * @param records 余额流水列表
     * @param userId 用户ID
     */
    private void fillUseRecordBalances(List<TExchangeCodeUseRecord> records, Long userId) {
        if (records == null || records.isEmpty() || userId == null) {
            return;
        }
        List<TExchangeCodeUseRecord> allRecords = useRecordMapper.selectList(new QueryWrapper<TExchangeCodeUseRecord>()
                .eq("user_id", userId)
                .orderByDesc("id"));
        Map<Long, BigDecimal> balanceMap = new HashMap<>();
        BigDecimal balance = getCurrentExchangeCodeBalance(userId);
        for (TExchangeCodeUseRecord item : allRecords) {
            balanceMap.put(item.getId(), balance);
            balance = rollbackUseRecordChange(balance, item);
        }
        for (TExchangeCodeUseRecord item : records) {
            item.setCurrentBalance(balanceMap.getOrDefault(item.getId(), BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)));
        }
    }
 
 
    private BigDecimal calculateCurrentBalanceAfterRecord(Long userId, Long recordId) {
        BigDecimal balance = getCurrentExchangeCodeBalance(userId);
        List<TExchangeCodeUseRecord> records = useRecordMapper.selectList(new QueryWrapper<TExchangeCodeUseRecord>()
                .eq("user_id", userId)
                .gt("id", recordId)
                .orderByDesc("id"));
        for (TExchangeCodeUseRecord item : records) {
            balance = rollbackUseRecordChange(balance, item);
        }
        return balance;
    }
 
    private BigDecimal rollbackUseRecordChange(BigDecimal balance, TExchangeCodeUseRecord record) {
        BigDecimal amount = defaultMoney(record == null ? null : record.getUsedAmount());
        Integer changeType = record == null ? null : record.getChangeType();
        if (USE_RECORD_TYPE_CONSUME.equals(changeType)) {
            return balance.add(amount).setScale(2, RoundingMode.HALF_UP);
        }
        return balance.subtract(amount).setScale(2, RoundingMode.HALF_UP);
    }
 
    private BigDecimal getCurrentExchangeCodeBalance(Long userId) {
        Map<Long, BigDecimal> balanceMap = getUserExchangeCodeBalanceMap(Collections.singletonList(userId));
        return defaultMoney(balanceMap.get(userId));
    }
 
    /**
     * 填充余额流水前端展示字段。
     *
     * @param record 余额流水记录
     */
    private void fillUseRecordView(TExchangeCodeUseRecord record) {
        if (record == null) {
            return;
        }
        record.setUid(String.valueOf(record.getId()));
        record.setDateTime(record.getCreateTime());
        record.setChangeAmount(defaultMoney(record.getUsedAmount()));
        if (record.getCurrentBalance() == null) {
            record.setCurrentBalance(defaultMoney(record.getUsedAmount()));
        }
        if (record.getChangeType() == null) {
            record.setChangeType(record.getOrderId() == null || record.getOrderId() == 0
                    ? USE_RECORD_TYPE_EXCHANGE : USE_RECORD_TYPE_CONSUME);
        }
        if (record.getDetailId() != null) {
            TExchangeCodeDetail detail = codeDetailMapper.selectById(record.getDetailId());
            if (detail != null) {
                record.setCode(detail.getCode());
            }
        }
        if (record.getOrderId() != null && record.getOrderId() > 0) {
            record.setOrderCode(String.valueOf(record.getOrderId()));
        }
    }
 
    /**
     * 根据使用金额和赠送比例填充流水的总使用金额与赠送使用金额。
     *
     * @param record 余额流水记录
     * @param amount 使用金额
     * @param giftRatio 赠送金额比例
     */
    private void fillUseRecordAmount(TExchangeCodeUseRecord record, BigDecimal amount, BigDecimal giftRatio) {
        BigDecimal usedAmount = defaultMoney(amount);
        BigDecimal ratio = giftRatio == null ? BigDecimal.ZERO : giftRatio;
        if (ratio.compareTo(BigDecimal.ZERO) < 0) {
            ratio = BigDecimal.ZERO;
        }
        BigDecimal giftUsedAmount = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        if (ratio.compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal divisor = BigDecimal.ONE.add(ratio);
            BigDecimal principalAmount = usedAmount.divide(divisor, 2, RoundingMode.HALF_UP);
            giftUsedAmount = usedAmount.subtract(principalAmount).setScale(2, RoundingMode.HALF_UP);
        }
        record.setUsedAmount(usedAmount);
        record.setGiftUsedAmount(giftUsedAmount);
    }
 
    /**
     * 将金额空值归零并统一保留两位小数。
     *
     * @param amount 原始金额
     * @return 标准金额
     */
    private BigDecimal defaultMoney(BigDecimal amount) {
        return amount == null ? BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP)
                : amount.setScale(2, RoundingMode.HALF_UP);
    }
}