KKSU
2025-01-03 4275ffd2707f4c27abdfeff847735140a0c7a69e
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
package cc.mrbird.febs.mall.service.impl;
 
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.enumerates.FlowTypeEnum;
import cc.mrbird.febs.common.enumerates.RunVipDataDictionaryEnum;
import cc.mrbird.febs.common.enumerates.RunVipMoneyFlowTypeEnum;
import cc.mrbird.febs.common.enumerates.YesOrNoEnum;
import cc.mrbird.febs.common.exception.FebsException;
import cc.mrbird.febs.common.utils.LoginUserUtil;
import cc.mrbird.febs.common.utils.MallUtils;
import cc.mrbird.febs.mall.conversion.RunVipConversion;
import cc.mrbird.febs.mall.dto.*;
import cc.mrbird.febs.mall.entity.*;
import cc.mrbird.febs.mall.mapper.*;
import cc.mrbird.febs.mall.service.IApiMallMemberWalletService;
import cc.mrbird.febs.mall.service.IMallMoneyFlowService;
import cc.mrbird.febs.mall.service.IRunVipService;
import cc.mrbird.febs.mall.vo.*;
import cc.mrbird.febs.rabbit.producter.AgentProducer;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
 
@Slf4j
@Service
@RequiredArgsConstructor
public class RunVipServiceImpl extends ServiceImpl<RunVipMapper, RunVip> implements IRunVipService {
 
    private final DataDictionaryCustomMapper dataDictionaryCustomMapper;
    private final MallMemberPaymentMapper mallMemberPaymentMapper;
    private final MallChargeMapper mallChargeMapper;
    private final AgentProducer agentProducer;
    private final MallMoneyFlowMapper mallMoneyFlowMapper;
    private final MallMemberWalletMapper mallMemberWalletMapper;
    private final MallMemberMapper mallMemberMapper;
    private final IApiMallMemberWalletService walletService;
    private final IMallMoneyFlowService mallMoneyFlowService;
    private final RunVipGrowMapper runVipGrowMapper;
    @Override
    public List<ApiRunVipVo> vipInfo() {
        Long memberId = LoginUserUtil.getLoginUser().getId();
        List<ApiRunVipVo> apiRunVipVos = new ArrayList<>();
        MallMember mallMember = mallMemberMapper.selectById(memberId);
        if (StrUtil.isEmpty(mallMember.getLevel())) {
            return apiRunVipVos;
        }
        String level = mallMember.getLevel();
        //获取当前用户的VIP等级
        RunVip runVip = this.baseMapper.selectOne(new LambdaQueryWrapper<RunVip>().eq(RunVip::getVipCode, level));
        //获取大于当前用户等级序号的所有的VIP等级
        LambdaQueryWrapper<RunVip> runVipLambdaQueryWrapper = new LambdaQueryWrapper<>();
        runVipLambdaQueryWrapper.eq(RunVip::getState, YesOrNoEnum.YES.getValue());
        runVipLambdaQueryWrapper.ge(RunVip::getOrderNumber, runVip.getOrderNumber());
        List<RunVip> runVips = this.baseMapper.selectList(runVipLambdaQueryWrapper);
        apiRunVipVos = RunVipConversion.INSTANCE.entityToVos(runVips);
 
        return apiRunVipVos;
    }
 
    @Override
    public FebsResponse goCharge(ApiGoChargeDto apiGoChargeDto) {
 
        Long memberId = LoginUserUtil.getLoginUser().getId();
        MallMember mallMember = mallMemberMapper.selectById(memberId);
        if (StrUtil.isBlank(mallMember.getTradePassword())) {
            throw new FebsException("未设置资金密码");
        }
 
        if (!mallMember.getTradePassword().equals(SecureUtil.md5(apiGoChargeDto.getTradeWord()))) {
            throw new FebsException("资金密码错误");
        }
        Long runVipId = apiGoChargeDto.getRunVipId();
        RunVip runVipNext = this.baseMapper.selectById(runVipId);
        if(runVipNext.getState() != YesOrNoEnum.YES.getValue()){
            throw new FebsException("会员套餐已下架");
        }
        //价格
        BigDecimal presentAmount = runVipNext.getPresentPrice().multiply(new BigDecimal(apiGoChargeDto.getVipCnt())).setScale(2,BigDecimal.ROUND_DOWN);
        //减免价格
        RunVip runVip = this.baseMapper.selectOne(new LambdaQueryWrapper<RunVip>().eq(RunVip::getVipCode, mallMember.getLevel()));
        BigDecimal reduceAmount = runVip.getPresentPrice();
        RunVipGrow runVipGrow = runVipGrowMapper.selectList(
                new LambdaQueryWrapper<RunVipGrow>()
                        .eq(RunVipGrow::getMemberId, memberId)
                        .eq(RunVipGrow::getLevelNow, mallMember.getLevel())
                        .orderByDesc(RunVipGrow::getId)
        ).stream().findFirst().orElse(null);
        if(runVipGrow != null){
            BigDecimal amountNow = runVipGrow.getAmountNow();
            reduceAmount = reduceAmount.add(amountNow);
        }
        presentAmount = presentAmount.subtract(reduceAmount);
 
        Long addressId = apiGoChargeDto.getAddressId();
        MallMemberPayment mallMemberPayment = mallMemberPaymentMapper.selectById(addressId);
        if(ObjectUtil.isEmpty(mallMemberPayment)){
            return new FebsResponse().fail().message("请先绑定你的地址");
        }
 
        //判断系统的充值地址
        String trcType = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                RunVipDataDictionaryEnum.CHARGE_TYPE_TRC.getType(),
                RunVipDataDictionaryEnum.CHARGE_TYPE_TRC.getCode()
        ).getValue();
        String sysAddress = "";
        if(trcType.equals(mallMemberPayment.getBankNo())){
            sysAddress = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                    RunVipDataDictionaryEnum.CHARGE_SYS_ADDRESS_TRC.getType(),
                    RunVipDataDictionaryEnum.CHARGE_SYS_ADDRESS_TRC.getCode()
            ).getValue();
        }else{
            sysAddress = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                    RunVipDataDictionaryEnum.CHARGE_SYS_ADDRESS_BSC.getType(),
                    RunVipDataDictionaryEnum.CHARGE_SYS_ADDRESS_BSC.getCode()
            ).getValue();
        }
        String failMinutes = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                RunVipDataDictionaryEnum.CHARGE_SYS_FAIL_TIME.getType(),
                RunVipDataDictionaryEnum.CHARGE_SYS_FAIL_TIME.getCode()
        ).getValue();
        DateTime failTime = DateUtil.offsetMinute(DateUtil.date(), Integer.parseInt(failMinutes));
 
        MallCharge mallCharge = new MallCharge();
        mallCharge.setMemberId(memberId);
        mallCharge.setOrderNo(MallUtils.getOrderNum());
        mallCharge.setState(YesOrNoEnum.ING.getValue());
        mallCharge.setType(mallMemberPayment.getBankNo());
        mallCharge.setAddress(mallMemberPayment.getBank());
        mallCharge.setAmount(presentAmount);
        mallCharge.setFailTime(failTime);
        mallCharge.setSysAddress(sysAddress);
        mallCharge.setVipCode(runVipNext.getVipCode());
        mallCharge.setVipName(runVipNext.getVipName());
        mallCharge.setVipCnt(apiGoChargeDto.getVipCnt());
        mallChargeMapper.insert(mallCharge);
 
        ApiGoChargeVo apiGoChargeVo = new ApiGoChargeVo();
        apiGoChargeVo.setFailTime(mallCharge.getFailTime());
        apiGoChargeVo.setAddress(mallCharge.getAddress());
        apiGoChargeVo.setAmount(mallCharge.getAmount());
        apiGoChargeVo.setSysAddress(mallCharge.getSysAddress());
        apiGoChargeVo.setSysAddressType(mallCharge.getType());
 
        /**
         * 充值接口调用后,发送一个延时队列
         *  功能:延迟时间为【failMinutes】后,更新充值记录为失败。
         */
        ApiMemberChargeFailDto apiMemberChargeFailDto = new ApiMemberChargeFailDto();
        apiMemberChargeFailDto.setChargeId(mallCharge.getId());
        apiMemberChargeFailDto.setFailTime(Integer.parseInt(failMinutes) * 60L* 1000L);
        agentProducer.sendMemberChargeFailMsg(apiMemberChargeFailDto);
 
        return new FebsResponse().success().data(apiGoChargeVo);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public FebsResponse balanceBuy(ApiBalanceBuyDto apiBalanceBuyDto) {
        Long memberId = LoginUserUtil.getLoginUser().getId();
        MallMember mallMember = mallMemberMapper.selectById(memberId);
        if (StrUtil.isBlank(mallMember.getTradePassword())) {
            throw new FebsException("未设置资金密码");
        }
 
        if (!mallMember.getTradePassword().equals(SecureUtil.md5(apiBalanceBuyDto.getTradeWord()))) {
            throw new FebsException("资金密码错误");
        }
        Long runVipId = apiBalanceBuyDto.getRunVipId();
        RunVip runVipNext = this.baseMapper.selectById(runVipId);
        if(runVipNext.getState() != YesOrNoEnum.YES.getValue()){
            throw new FebsException("会员套餐已下架");
        }
 
        //价格
        BigDecimal presentAmount = runVipNext.getPresentPrice().setScale(2,BigDecimal.ROUND_DOWN);
        //减免价格
        RunVip runVip = this.baseMapper.selectOne(new LambdaQueryWrapper<RunVip>().eq(RunVip::getVipCode, mallMember.getLevel()));
        BigDecimal reduceAmount = runVip.getPresentPrice();
        RunVipGrow runVipGrow = runVipGrowMapper.selectList(
                new LambdaQueryWrapper<RunVipGrow>()
                        .eq(RunVipGrow::getMemberId, memberId)
                        .eq(RunVipGrow::getLevelNow, mallMember.getLevel())
                        .orderByDesc(RunVipGrow::getId)
        ).stream().findFirst().orElse(null);
        if(runVipGrow != null){
            BigDecimal amountNow = runVipGrow.getAmountNow();
            reduceAmount = reduceAmount.add(amountNow);
        }
        presentAmount = presentAmount.subtract(reduceAmount);
 
        MallMemberWallet mallMemberWallet = mallMemberWalletMapper.selectWalletByMemberId(memberId);
        if(mallMemberWallet.getCommission().compareTo(BigDecimal.ZERO) <= 0){
            throw new FebsException("余额不足");
        }
        if(mallMemberWallet.getCommission().compareTo(presentAmount) < 0){
            throw new FebsException("余额不足");
        }
 
        String orderNo = MallUtils.getOrderNum();
        walletService.reduceCommission(presentAmount,memberId);
        mallMoneyFlowService.runVipMoneyFlowAdd(
                memberId,
                memberId,
                orderNo,
                FlowTypeEnum.COMMISSION.getValue(),
                RunVipMoneyFlowTypeEnum.COMMISSION_PAY.getValue(),
                presentAmount.negate(),
                StrUtil.format(RunVipMoneyFlowTypeEnum.COMMISSION_PAY.getDescription(),presentAmount),
                YesOrNoEnum.YES.getValue()
        );
 
        MallCharge mallCharge = new MallCharge();
        mallCharge.setMemberId(memberId);
        mallCharge.setOrderNo(orderNo);
        mallCharge.setState(YesOrNoEnum.YES.getValue());
        mallCharge.setType(StrUtil.format(RunVipMoneyFlowTypeEnum.COMMISSION_PAY.getDescription(),presentAmount));
        mallCharge.setAddress(mallMember.getPhone());
        mallCharge.setAmount(presentAmount);
        mallCharge.setVipCode(runVipNext.getVipCode());
        mallCharge.setVipName(runVipNext.getVipName());
        mallCharge.setVipCnt(apiBalanceBuyDto.getVipCnt());
        mallChargeMapper.insert(mallCharge);
 
        agentProducer.sendBuyVipSuccessMsg(mallCharge.getId());
 
        return new FebsResponse().success().message("操作成功");
    }
 
    @Override
    public FebsResponse goChargeInfo(ApiGoChargeInfoDto apiGoChargeInfoDto) {
        Long memberId = LoginUserUtil.getLoginUser().getId();
        String orderNo = apiGoChargeInfoDto.getOrderNo();
 
        LambdaQueryWrapper<MallCharge> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(MallCharge::getMemberId,memberId);
        objectLambdaQueryWrapper.eq(MallCharge::getOrderNo,orderNo);
        MallCharge mallCharge = mallChargeMapper.selectOne(objectLambdaQueryWrapper);
 
        ApiGoChargeVo apiGoChargeVo = new ApiGoChargeVo();
        if(null == mallCharge){
            throw new FebsException("记录不存在");
        }
        apiGoChargeVo.setFailTime(mallCharge.getFailTime());
        apiGoChargeVo.setAddress(mallCharge.getAddress());
        apiGoChargeVo.setAmount(mallCharge.getAmount());
        apiGoChargeVo.setSysAddress(mallCharge.getSysAddress());
        apiGoChargeVo.setSysAddressType(mallCharge.getType());
        return new FebsResponse().success().data(apiGoChargeVo);
    }
 
    @Override
    public List<ApiChargeVo> getChargeList(ApiChargeListDto apiChargeListDto) {
        Long memberId = LoginUserUtil.getLoginUser().getId();
        apiChargeListDto.setMemberId(memberId);
        Page<ApiChargeVo> page = new Page<>(apiChargeListDto.getPageNum(), apiChargeListDto.getPageSize());
        return mallChargeMapper.selectChargeListInPage(apiChargeListDto, page);
    }
 
    @Override
    public List<ApiGetRunDateVo> getRunDate(ApiGetRunDateDto queryDto) {
 
        Long memberId = LoginUserUtil.getLoginUser().getId();
        DateTime dateTime = DateUtil.parseDate(queryDto.getDateStr());
 
        DateTime startTime = DateUtil.beginOfMonth(dateTime);
        DateTime endTime = DateUtil.endOfMonth(dateTime);
        long between = DateUtil.between(startTime, endTime, DateUnit.DAY);
        List<ApiGetRunDateVo> apiGetRunDateVos = generateDateList(startTime, between);
 
        List<MallMoneyFlow> mallMoneyFlows = mallMoneyFlowMapper.selectList(
                new LambdaQueryWrapper<MallMoneyFlow>()
                        .eq(MallMoneyFlow::getMemberId, memberId)
                        .eq(MallMoneyFlow::getFlowType, FlowTypeEnum.SCORE.getValue())
                        .eq(MallMoneyFlow::getType, RunVipMoneyFlowTypeEnum.SCORE_OUT_BALANCE.getValue())
                        .ge(MallMoneyFlow::getCreatedTime, startTime)
                        .le(MallMoneyFlow::getCreatedTime, endTime)
        );
        if(CollUtil.isNotEmpty(mallMoneyFlows)){
            calculateProfits(apiGetRunDateVos,mallMoneyFlows);
        }
 
        return apiGetRunDateVos;
    }
 
    /**
     * 生成日期列表
     *
     * @param startDate 开始日期
     * @param days      从开始日期算起的天数
     * @return 一个包含日期信息的ApiGetRunDateVo对象列表
     */
    private List<ApiGetRunDateVo> generateDateList(DateTime startDate, long days) {
        // 使用IntStream生成从0到days(包含days)的整数流,表示每一天
        return IntStream.range(0, (int) days + 1)
                // 将每个整数映射为一个ApiGetRunDateVo对象
                .mapToObj(i -> {
                    // 创建ApiGetRunDateVo对象
                    ApiGetRunDateVo apiGetRunDateVo = new ApiGetRunDateVo();
                    // 计算日期:从起始日期开始偏移i天
                    DateTime dateTime = DateUtil.offsetDay(startDate, i);
                    // 格式化日期为"yyyy-MM-dd"字符串,并设置到对象中
                    apiGetRunDateVo.setDateStr(DateUtil.format(dateTime, "yyyy-MM-dd"));
                    // 初始化碳积分为0
                    apiGetRunDateVo.setScore(BigDecimal.ZERO);
                    // 返回构建好的对象
                    return apiGetRunDateVo;
                })
                // 将流中的对象收集到一个列表中
                .collect(Collectors.toList());
    }
    /**
     * 计算每日累计碳积分
     *
     * @param dateList 日期列表,包含了每日的碳积分信息
     * @param mallMoneyFlows 商城资金流列表,包含了每笔碳积分信息
     */
    private void calculateProfits(List<ApiGetRunDateVo> dateList, List<MallMoneyFlow> mallMoneyFlows) {
        // 将日期列表转换为映射,以便通过日期快速访问每日碳积分信息
        Map<String, ApiGetRunDateVo> dateMap = dateList.stream()
                .collect(Collectors.toMap(ApiGetRunDateVo::getDateStr, vo -> vo));
 
        // 遍历mallMoneyFlows
        for (MallMoneyFlow item : mallMoneyFlows) {
            // 格式化当前项的创建时间,提取日期
            String date = DateUtil.format(item.getCreatedTime(), "yyyy-MM-dd");
            // 从日期映射中获取对应的每日碳积分信息
            ApiGetRunDateVo apiGetRunDateVo = dateMap.get(date);
            // 如果找到了对应的每日碳积分信息
            if (apiGetRunDateVo != null) {
                // 获取当前日期的碳积分
                BigDecimal score = apiGetRunDateVo.getScore();
                // 计算新的碳积分,将碳积分与碳积分相加,并向下取整到个位数
                BigDecimal profit = score.add(item.getAmount().abs()).setScale(0,BigDecimal.ROUND_DOWN);
                // 更新每日碳积分信息的利润值
                apiGetRunDateVo.setScore(profit);
            }
        }
    }
 
    @Override
    public ApiRunDataVo runData() {
        Long memberId = LoginUserUtil.getLoginUser().getId();
        ApiRunDataVo apiRunDataVo = new ApiRunDataVo();
        MallMember mallMember = mallMemberMapper.selectById(memberId);
        String level = mallMember.getLevel();
        RunVip runVip = this.baseMapper.selectOne(new LambdaQueryWrapper<RunVip>().eq(RunVip::getVipCode, level));
        apiRunDataVo.setAimScore(runVip.getGrowthCnt());
 
        List<MallMoneyFlow> mallMoneyFlows = mallMoneyFlowMapper.selectList(
                new LambdaQueryWrapper<MallMoneyFlow>()
                        .eq(MallMoneyFlow::getMemberId, memberId)
                        .eq(MallMoneyFlow::getFlowType, FlowTypeEnum.SCORE.getValue())
                        .in(MallMoneyFlow::getType, RunVipMoneyFlowTypeEnum.GET_SCORE.getValue(),RunVipMoneyFlowTypeEnum.SYS_SCORE.getValue())
                        .ge(MallMoneyFlow::getCreatedTime, DateUtil.beginOfDay(DateUtil.date()))
                        .le(MallMoneyFlow::getCreatedTime, DateUtil.endOfDay(DateUtil.date()))
        );
        if(CollUtil.isNotEmpty(mallMoneyFlows)){
            BigDecimal reduce = mallMoneyFlows.stream().map(MallMoneyFlow::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            apiRunDataVo.setScore(reduce.intValue());
        }
 
        MallMemberWallet mallMemberWallet = mallMemberWalletMapper.selectWalletByMemberId(memberId);
        apiRunDataVo.setBalance(mallMemberWallet.getBalance());
        apiRunDataVo.setRealScore(mallMemberWallet.getScore().intValue());
        return apiRunDataVo;
    }
 
    @Override
    public ApiRunHealthVo runHealth() {
        Long memberId = LoginUserUtil.getLoginUser().getId();
        ApiRunHealthVo apiRunHealthVo = new ApiRunHealthVo();
 
        MallMemberWallet mallMemberWallet = mallMemberWalletMapper.selectWalletByMemberId(memberId);
        int realScore = mallMemberWallet.getScore().intValue();
        apiRunHealthVo.setScore(realScore);
        List<MallMoneyFlow> mallMoneyFlows = mallMoneyFlowMapper.selectList(
                new LambdaQueryWrapper<MallMoneyFlow>()
                        .eq(MallMoneyFlow::getMemberId, memberId)
                        .eq(MallMoneyFlow::getFlowType, FlowTypeEnum.SCORE.getValue())
                        .in(MallMoneyFlow::getType, RunVipMoneyFlowTypeEnum.GET_SCORE.getValue(),RunVipMoneyFlowTypeEnum.SYS_SCORE.getValue())
                        .ge(MallMoneyFlow::getCreatedTime, DateUtil.beginOfDay(DateUtil.date()))
                        .le(MallMoneyFlow::getCreatedTime, DateUtil.endOfDay(DateUtil.date()))
        );
        if(CollUtil.isNotEmpty(mallMoneyFlows)){
            BigDecimal reduce = mallMoneyFlows.stream().map(MallMoneyFlow::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            apiRunHealthVo.setScoreTotal(reduce.intValue());
        }
        List<MallMoneyFlow> mallMoneyFlowScoreOuts = mallMoneyFlowMapper.selectList(
                new LambdaQueryWrapper<MallMoneyFlow>()
                        .eq(MallMoneyFlow::getMemberId, memberId)
                        .eq(MallMoneyFlow::getFlowType, FlowTypeEnum.SCORE.getValue())
                        .eq(MallMoneyFlow::getType, RunVipMoneyFlowTypeEnum.SCORE_OUT_BALANCE.getValue())
                        .ge(MallMoneyFlow::getCreatedTime, DateUtil.beginOfDay(DateUtil.date()))
                        .le(MallMoneyFlow::getCreatedTime, DateUtil.endOfDay(DateUtil.date()))
        );
        if(CollUtil.isNotEmpty(mallMoneyFlowScoreOuts)){
            BigDecimal reduce = mallMoneyFlowScoreOuts.stream().map(MallMoneyFlow::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add).abs();
            apiRunHealthVo.setScoreUsed(reduce.intValue());
        }
        return apiRunHealthVo;
    }
 
    @Override
    public FebsResponse growInfo() {
        Long memberId = LoginUserUtil.getLoginUser().getId();
        ApiGrowInfoVo apiGrowInfoVo = new ApiGrowInfoVo();
        MallMember mallMember = mallMemberMapper.selectById(memberId);
        String memberLevel = mallMember.getLevel();
 
        RunVipGrow runVipGrow = runVipGrowMapper.selectOne(
                new LambdaQueryWrapper<RunVipGrow>()
                        .eq(RunVipGrow::getMemberId, memberId)
                        .orderByDesc(RunVipGrow::getId)
                        .last("limit 1")
        );
 
        //有升级权益的记录、当前等级和最新的升级记录是同一个
        if(runVipGrow != null && memberLevel.equals(runVipGrow.getLevelNow())){
            apiGrowInfoVo.setLevelNow(runVipGrow.getLevelNow());
            apiGrowInfoVo.setAmountNow(runVipGrow.getAmountNow());
            apiGrowInfoVo.setLevelNext(runVipGrow.getLevelNext());
            apiGrowInfoVo.setAmountAll(runVipGrow.getAmountAll());
        }else{
            List<RunVip> runVips = this.baseMapper.selectList(null);
            Map<String, RunVip> runVipMap = runVips.stream()
                    .collect(Collectors.toMap(RunVip::getVipCode, runVip -> runVip));
            RunVip runVipNow = runVipMap.get(memberLevel);
            apiGrowInfoVo.setLevelNow(runVipNow.getVipCode());
            apiGrowInfoVo.setAmountNow(runVipNow.getPresentPrice());
 
 
            //获取runVips中的orderNumber为runVipNow.getOrderNumber() + 1的那个元素
            RunVip runVipNext = runVips.stream().filter(runVip -> runVip.getOrderNumber() == runVipNow.getOrderNumber() + 1).findFirst().orElse(null);
            if(runVipNext != null){
                apiGrowInfoVo.setLevelNext(runVipNext.getVipCode());
                apiGrowInfoVo.setAmountAll(runVipNext.getPresentPrice());
            }
        }
        return new FebsResponse().success().data(apiGrowInfoVo);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public FebsResponse growBuy(ApiGrowBuyDto apiGrowBuyDto) {
        Long memberId = LoginUserUtil.getLoginUser().getId();
 
        BigDecimal amount = apiGrowBuyDto.getAmount();
        if(BigDecimal.ZERO.compareTo(amount) >= 0){
            throw new FebsException("金额异常");
        }
 
        MallMember mallMember = mallMemberMapper.selectById(memberId);
        if (StrUtil.isBlank(mallMember.getTradePassword())) {
            throw new FebsException("未设置资金密码");
        }
 
        if (!mallMember.getTradePassword().equals(SecureUtil.md5(apiGrowBuyDto.getTradeWord()))) {
            throw new FebsException("资金密码错误");
        }
 
        MallMemberWallet mallMemberWallet = mallMemberWalletMapper.selectWalletByMemberId(memberId);
        if(mallMemberWallet.getCommission().compareTo(amount) < 0){
            throw new FebsException("余额不足");
        }
 
        String memberLevel = mallMember.getLevel();
        String levelNext = apiGrowBuyDto.getLevelNext();
 
        List<RunVip> runVips = this.baseMapper.selectList(null);
        Map<String, RunVip> runVipMap = runVips.stream()
                .collect(Collectors.toMap(RunVip::getVipCode, runVip -> runVip));
        RunVip runVip = runVipMap.get(memberLevel);
        RunVip runVipNext = runVipMap.get(levelNext);
        if(runVipNext == null){
            throw new FebsException("无法升级会员权益");
        }
        if(runVip.getOrderNumber() < runVipNext.getOrderNumber()){
            throw new FebsException("用户无法升级");
        }
 
        walletService.reduceCommission(amount,memberId);
        String orderNo = MallUtils.getOrderNum("QY");
        mallMoneyFlowService.runVipMoneyFlowAdd(
                memberId,
                memberId,
                orderNo,
                FlowTypeEnum.COMMISSION.getValue(),
                RunVipMoneyFlowTypeEnum.COMMISSION_PAY_GROW.getValue(),
                amount.negate(),
                StrUtil.format(RunVipMoneyFlowTypeEnum.COMMISSION_PAY_GROW.getDescription(),amount),
                YesOrNoEnum.YES.getValue()
        );
 
        RunVipGrow runVipGrow = runVipGrowMapper.selectOne(
                new LambdaQueryWrapper<RunVipGrow>()
                        .eq(RunVipGrow::getMemberId, memberId)
                        .eq(RunVipGrow::getLevelNow, memberLevel)
                        .eq(RunVipGrow::getLevelNext, levelNext)
        );
 
        MallCharge mallCharge = new MallCharge();
        mallCharge.setMemberId(memberId);
        mallCharge.setOrderNo(orderNo);
        mallCharge.setState(YesOrNoEnum.YES.getValue());
        mallCharge.setType(StrUtil.format(RunVipMoneyFlowTypeEnum.COMMISSION_PAY_GROW.getDescription(),amount));
        mallCharge.setAddress(mallMember.getPhone());
        mallCharge.setAmount(amount);
        mallCharge.setVipCnt(1);
        mallCharge.setVipName(runVip.getVipName()+"权益");
        mallCharge.setVipCode(runVip.getVipCode());
        //有升级权益的记录
        if(runVipGrow != null){
            //判断金额是否满足升级条件
            BigDecimal amountNow = runVipGrow.getAmountNow();
            BigDecimal amountAll = runVipGrow.getAmountAll();
            BigDecimal subtract = amountAll.subtract(amountNow);
 
            if(subtract.compareTo(amount) <= 0){
                runVipGrow.setAmountNow(amountAll);
 
                mallCharge.setVipCode(runVipGrow.getLevelNext());
            }else{
                runVipGrow.setAmountNow(amountNow.add(amount).setScale(2, RoundingMode.DOWN));
 
                mallCharge.setVipCode(memberLevel);
            }
            runVipGrow.setAmount(amount);
            runVipGrowMapper.updateById(runVipGrow);
        }else{
            runVipGrow = new RunVipGrow();
            runVipGrow.setMemberId(memberId);
            runVipGrow.setLevelNow(memberLevel);
            runVipGrow.setLevelNext(runVipNext.getVipCode());
            runVipGrow.setAmountAll(runVipNext.getPresentPrice());
            runVipGrow.setAmount(amount);
            runVipGrow.setAmountNow(amount);
            runVipGrowMapper.insert(runVipGrow);
 
            if(runVipGrow.getAmountAll().compareTo(amount) <= 0){
                mallCharge.setVipCode(runVipGrow.getLevelNext());
            }
        }
        mallChargeMapper.insert(mallCharge);
 
        agentProducer.sendBuyVipSuccessMsg(mallCharge.getId());
 
        return new FebsResponse().success().message("操作成功");
    }
 
    @Override
    public FebsResponse growCharge(ApiGrowChargeDto apiGrowChargeDto) {
        Long memberId = LoginUserUtil.getLoginUser().getId();
 
        ApiGoChargeVo apiGoChargeVo = new ApiGoChargeVo();
 
        BigDecimal amount = apiGrowChargeDto.getAmount();
        if(BigDecimal.ZERO.compareTo(amount) >= 0){
            throw new FebsException("金额异常");
        }
 
        MallMember mallMember = mallMemberMapper.selectById(memberId);
        if (StrUtil.isBlank(mallMember.getTradePassword())) {
            throw new FebsException("未设置资金密码");
        }
 
        if (!mallMember.getTradePassword().equals(SecureUtil.md5(apiGrowChargeDto.getTradeWord()))) {
            throw new FebsException("资金密码错误");
        }
 
        String memberLevel = mallMember.getLevel();
        String levelNext = apiGrowChargeDto.getLevelNext();
 
        List<RunVip> runVips = this.baseMapper.selectList(null);
        Map<String, RunVip> runVipMap = runVips.stream()
                .collect(Collectors.toMap(RunVip::getVipCode, runVip -> runVip));
        RunVip runVip = runVipMap.get(memberLevel);
        RunVip runVipNext = runVipMap.get(levelNext);
        if(runVipNext == null){
            throw new FebsException("无法升级会员权益");
        }
        if(runVip.getOrderNumber() < runVipNext.getOrderNumber()){
            throw new FebsException("用户无法升级");
        }
 
        Long addressId = apiGrowChargeDto.getAddressId();
        MallMemberPayment mallMemberPayment = mallMemberPaymentMapper.selectById(addressId);
        if(ObjectUtil.isEmpty(mallMemberPayment)){
            return new FebsResponse().fail().message("请先绑定你的地址");
        }
 
        //判断系统的充值地址
        String trcType = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                RunVipDataDictionaryEnum.CHARGE_TYPE_TRC.getType(),
                RunVipDataDictionaryEnum.CHARGE_TYPE_TRC.getCode()
        ).getValue();
        String sysAddress = "";
        if(trcType.equals(mallMemberPayment.getBankNo())){
            sysAddress = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                    RunVipDataDictionaryEnum.CHARGE_SYS_ADDRESS_TRC.getType(),
                    RunVipDataDictionaryEnum.CHARGE_SYS_ADDRESS_TRC.getCode()
            ).getValue();
        }else{
            sysAddress = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                    RunVipDataDictionaryEnum.CHARGE_SYS_ADDRESS_BSC.getType(),
                    RunVipDataDictionaryEnum.CHARGE_SYS_ADDRESS_BSC.getCode()
            ).getValue();
        }
        String failMinutes = dataDictionaryCustomMapper.selectDicDataByTypeAndCode(
                RunVipDataDictionaryEnum.CHARGE_SYS_FAIL_TIME.getType(),
                RunVipDataDictionaryEnum.CHARGE_SYS_FAIL_TIME.getCode()
        ).getValue();
        DateTime failTime = DateUtil.offsetMinute(DateUtil.date(), Integer.parseInt(failMinutes));
 
        MallCharge mallCharge = new MallCharge();
        String orderNo = MallUtils.getOrderNum("QY");
        mallCharge.setMemberId(memberId);
        mallCharge.setOrderNo(orderNo);
        mallCharge.setState(YesOrNoEnum.ING.getValue());
        mallCharge.setType(mallMemberPayment.getBankNo());
        mallCharge.setAddress(mallMemberPayment.getBank());
        mallCharge.setFailTime(failTime);
        mallCharge.setSysAddress(sysAddress);
 
        mallCharge.setAmount(amount);
        mallCharge.setVipCnt(1);
        mallCharge.setVipName(runVip.getVipName()+"权益");
        mallCharge.setVipCode(runVip.getVipCode());
 
        RunVipGrow runVipGrow = runVipGrowMapper.selectOne(
                new LambdaQueryWrapper<RunVipGrow>()
                        .eq(RunVipGrow::getMemberId, memberId)
                        .eq(RunVipGrow::getLevelNow, memberLevel)
                        .eq(RunVipGrow::getLevelNext, levelNext)
        );
 
        //有升级权益的记录、当前等级和最新的升级记录是同一个
        if(runVipGrow != null){
            //判断金额是否满足升级条件
            BigDecimal amountNow = runVipGrow.getAmountNow();
            BigDecimal amountAll = runVipGrow.getAmountAll();
            BigDecimal subtract = amountAll.subtract(amountNow);
 
            if(subtract.compareTo(amount) <= 0){
                mallCharge.setVipCode(runVipGrow.getLevelNext());
            }
        }else{
            if(runVipNext.getPresentPrice().compareTo(amount) <= 0){
                mallCharge.setVipCode(runVipNext.getVipCode());
            }
        }
 
        mallChargeMapper.insert(mallCharge);
 
        apiGoChargeVo.setFailTime(mallCharge.getFailTime());
        apiGoChargeVo.setAddress(mallCharge.getAddress());
        apiGoChargeVo.setAmount(mallCharge.getAmount());
        apiGoChargeVo.setSysAddress(mallCharge.getSysAddress());
        apiGoChargeVo.setSysAddressType(mallCharge.getType());
 
        /**
         * 充值接口调用后,发送一个延时队列
         *  功能:延迟时间为【failMinutes】后,更新充值记录为失败。
         */
        ApiMemberChargeFailDto apiMemberChargeFailDto = new ApiMemberChargeFailDto();
        apiMemberChargeFailDto.setChargeId(mallCharge.getId());
        apiMemberChargeFailDto.setFailTime(Integer.parseInt(failMinutes) * 60L* 1000L);
        agentProducer.sendMemberChargeFailMsg(apiMemberChargeFailDto);
        return new FebsResponse().success().data(apiGoChargeVo);
    }
 
    @Override
    public FebsResponse reduceAmount() {
        Long memberId = LoginUserUtil.getLoginUser().getId();
        ApiReduceAmountVo apiReduceAmountVo = new ApiReduceAmountVo();
        MallMember mallMember = mallMemberMapper.selectById(memberId);
        //减免价格
        RunVip runVip = this.baseMapper.selectOne(new LambdaQueryWrapper<RunVip>().eq(RunVip::getVipCode, mallMember.getLevel()));
        BigDecimal reduceAmount = runVip.getPresentPrice();
        RunVipGrow runVipGrow = runVipGrowMapper.selectList(
                new LambdaQueryWrapper<RunVipGrow>()
                        .eq(RunVipGrow::getMemberId, memberId)
                        .eq(RunVipGrow::getLevelNow, mallMember.getLevel())
                        .orderByDesc(RunVipGrow::getId)
        ).stream().findFirst().orElse(null);
        if(runVipGrow != null){
            BigDecimal amountNow = runVipGrow.getAmountNow();
            reduceAmount = reduceAmount.add(amountNow);
        }
        apiReduceAmountVo.setReduceAmount(reduceAmount);
        return new FebsResponse().success().data(apiReduceAmountVo);
    }
}