chenjiahe
2024-03-01 cfedbfad423aa6fd758da748967122819b1787e2
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
package com.hx.phip.tool.refund;
 
import com.alibaba.fastjson.JSON;
import com.hx.common.service.CommonService;
import com.hx.exception.TipsException;
import com.hx.mybatisTool.SqlSentence;
import com.hx.phiappt.common.*;
import com.hx.phiappt.constants.enums.GroupTypeEnum;
import com.hx.phiappt.constants.tool.RefundToolUtil;
import com.hx.phiappt.model.BaseEntity;
import com.hx.phiappt.model.activity.ActivityAction;
import com.hx.phiappt.model.activity.ActivityRule;
import com.hx.phiappt.model.cardItem.CardEquity;
import com.hx.phiappt.model.cardItem.CardItemInfo;
import com.hx.phiappt.model.coupon.CouponNumber;
import com.hx.phiappt.model.coupon.CouponOrderDiscountLog;
import com.hx.phiappt.model.order.*;
import com.hx.phiappt.model.refund.*;
import com.hx.phiappt.model.user.UserCard;
import com.hx.phiappt.model.user.UserCardUsed;
import com.hx.phiappt.model.user.UserProjectItem;
import com.hx.phiappt.model.userMoney.UserMoneyUnclaimed;
import com.hx.phip.dao.mapper.*;
import com.hx.phip.service.order.impl.OrderRefundServiceImpl;
import com.hx.phip.tool.order.OrderTool;
import com.hx.phip.tool.user.UserCardTool;
import com.hx.phip.tool.user.UserProjectTool;
import com.hx.phip.util.api.UserMoneyUtil;
import com.hx.phip.vo.order.refund.RefundCarryVo;
import com.hx.phip.vo.user.UserCardItemInfoVo;
import com.hx.util.StringUtils;
import com.platform.exception.PlatTipsException;
import com.platform.resultTool.PlatformCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
/**
 * 订单退款单作废工具
 * @author CJH
 */
public class OrderRefundCancelTool {
 
    /**log4j日志*/
    private static final Logger logger = LoggerFactory.getLogger(OrderRefundServiceImpl.class.getName());
 
    /**操作类型-0退款执行*/
    public static final int OPT_TYPE_EXECUTE = 0;
    /**操作类型—1作废退款*/
    public static final int OPT_TYPE_CANCEL = 1;
 
    public static final String REFUND_REMARK = "订单退款";
 
 
    /**处理总退款方式数据*/
    public static List<RefundRecordMethod> refundRecordMotnedHandle(RefundRecord refundRecord,OrdersTotal ordersTotal,StringBuilder orderNodeBuilder,CommonService commonService){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        //获取总退款方式
        values.put("refundRecordId",refundRecord.getId());
        sqlSentence.sqlSentence("SELECT * FROM refund_record_method WHERE isDel = 0 AND refundRecordId = #{m.refundRecordId}",values);
        List<RefundRecordMethod> refundRecordMethodList = commonService.selectList(RefundRecordMethodMapper.class,sqlSentence);
        //退款的支付方式记录数据,总的
        values.clear();
        values.put("refundRecordId",refundRecord.getId());
        sqlSentence.sqlSentence("SELECT * FROM refund_record_consume_pay WHERE isDel = 0 AND refundRecordId = #{m.refundRecordId} AND refundRecordItemId IS NULL",values);
        List<RefundRecordConsumePay> refundConsumePayList = commonService.selectList(RefundRecordConsumePayMapper.class,sqlSentence);
 
        for(RefundRecordConsumePay refundRecordConsumePay:refundConsumePayList){
            //更新支付记录退款信息
            values.clear();
            values.put("refundTotal",refundRecordConsumePay.getRefundTotal().negate());
            values.put("id",refundRecordConsumePay.getConsumePayId());
            sqlSentence.sqlUpdate("refundTotal = refundTotal + #{m.refundTotal} WHERE id = #{m.id} AND refundTotal + #{m.refundTotal} >= 0",values);
            if(commonService.updateWhere(ConsumePayMapper.class,sqlSentence) != 1){
                throw new TipsException("退款金额错误[33]!");
            }
 
            //更新支付记录退款信息
            values.clear();
            values.put("status",RefundRecordConsumePay.NO);
            values.put("statusOld",RefundRecordConsumePay.YES);
            values.put("id",refundRecordConsumePay.getId());
            sqlSentence.sqlUpdate("status = #{m.status} WHERE id = #{m.id} AND status = #{m.statusOld}",values);
            if(commonService.updateWhere(RefundRecordConsumePayMapper.class,sqlSentence) != 1){
                throw new TipsException("退款金额记录状态错误!");
            }
 
        }
 
        //处理扣减账号资金
        for(RefundRecordMethod refundRecordMethod:refundRecordMethodList){
            if(PayMethodTypeConstants.PAY_STORED.equals(refundRecordMethod.getRefundNumberNo())){
                //储值金额 
                //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                if(refundRecordMethod.getActualTotal().compareTo(BigDecimal.ZERO)>0){
                    UserMoneyUtil.setNewUserMoneyUnclaimed(ordersTotal.getPayUserId()==null?ordersTotal.getUserId():ordersTotal.getPayUserId(),refundRecord.getInvalidRemarks(),"作废退款:支付方式储值金额扣减",refundRecord.getInvalidId(),refundRecord.getOrderId(),refundRecord.getInvalidAppCode(),refundRecord.getId(),refundRecordMethod.getRealRefundTotal().negate(), UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND, OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.NO);
                    OrderLog orderLog = RefundToolUtil.setOrderLog(refundRecord, refundRecord.getInvalidId(), refundRecord.getInvalidName(), refundRecordMethod.getName()+"作废退款金额:"+refundRecordMethod.getRealRefundTotal(), 1, OrderLogConstants.LOG_TYPE_REFUND_UNDO);
                    commonService.insert(OrderLogMapper.class,orderLog);
                    if(orderNodeBuilder != null){
                        orderNodeBuilder.append("-[作废退款]扣减退款金额(储值金):").append(refundRecordMethod.getRealRefundTotal());
                    }
                }
            }else if(PayMethodTypeConstants.PAY_ADD_FUND.equals(refundRecordMethod.getRefundNumberNo())){
                //增值金
                //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                if(refundRecordMethod.getActualTotal().compareTo(BigDecimal.ZERO)!=0){
                    UserMoneyUtil.setNewUserMoneyUnclaimed(ordersTotal.getPayUserId()==null?ordersTotal.getUserId():ordersTotal.getPayUserId(),refundRecord.getRemarks(),"作废退款:支付方式增值金退回",refundRecord.getInvalidId(),refundRecord.getOrderId(),refundRecord.getInvalidAppCode(),refundRecord.getId(),refundRecordMethod.getRealRefundTotal().negate(), UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND, OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.NO);
                    OrderLog orderLog = RefundToolUtil.setOrderLog(refundRecord,refundRecord.getInvalidId(),refundRecord.getInvalidName(),refundRecordMethod.getName(),1, OrderLogConstants.LOG_TYPE_REFUND_UNDO);
                    commonService.insert(OrderLogMapper.class,orderLog);
                    if(orderNodeBuilder != null){
                        orderNodeBuilder.append("-[作废退款]扣减退款金额(增值金):").append(refundRecordMethod.getRealRefundTotal());
                    }
                }
            }else if(PayMethodTypeConstants.PAY_INTEGRAL.equals(refundRecordMethod.getRefundNumberNo())){
                //积分
                //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                if(refundRecordMethod.getActualTotal().compareTo(BigDecimal.ZERO)!=0){
                    UserMoneyUtil.setNewUserMoneyUnclaimed(ordersTotal.getPayUserId()==null?ordersTotal.getUserId():ordersTotal.getPayUserId(),refundRecord.getRemarks(),"作废退款:支付方式积分退回",refundRecord.getInvalidId(),refundRecord.getOrderId(),refundRecord.getInvalidAppCode(),refundRecord.getId(),refundRecordMethod.getRealRefundTotal().negate(), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.NO);
                    OrderLog orderLog = RefundToolUtil.setOrderLog(refundRecord,refundRecord.getInvalidId(),refundRecord.getInvalidName(),refundRecordMethod.getName()+"作废退款金额:"+refundRecordMethod.getRealRefundTotal(),1, OrderLogConstants.LOG_TYPE_REFUND_UNDO);
                    commonService.insert(OrderLogMapper.class,orderLog);
                    if(orderNodeBuilder != null){
                        orderNodeBuilder.append("-[作废退款]扣减退款金额(积分):").append(refundRecordMethod.getRealRefundTotal());
                    }
                }
            }else {
                //现金支付
                if(refundRecordMethod.getActualTotal().compareTo(BigDecimal.ZERO)<1){
                    continue;
                }
                OrderLog orderLog = RefundToolUtil.setOrderLog(refundRecord,refundRecord.getInvalidId(),refundRecord.getInvalidName(),refundRecordMethod.getName()+"作废退款金额:"+refundRecordMethod.getRealRefundTotal(),1, OrderLogConstants.LOG_TYPE_REFUND_UNDO);
                orderLog.setOrderId(ordersTotal.getId());
                commonService.insert(OrderLogMapper.class,orderLog);
            }
        }
        return refundRecordMethodList;
    }
 
    /**充值单特需处理
     * @param ordersTotal 订单
     * @param refundRecord 退款单
     * @param optType 操作类型:0退款执行,1作废退款
     * @param optName 操作名称,如:申请退款、作废退款、审核拒绝
     * @param commonService 映射
     */
    public static void rechargeHandle(OrdersTotal ordersTotal, RefundRecord refundRecord,int optType,String optName,StringBuilder orderNodeBuilder, CommonService commonService){
 
        if(!OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,不是充值单!");
        }
        if(ordersTotal.getTotal().compareTo(BigDecimal.ZERO) < 1){
            return;
        }
        OrderLog orderLog;
        if(optType == OPT_TYPE_EXECUTE){
            //充值金额扣减
            UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),REFUND_REMARK+"["+ordersTotal.getOrderNo()+"]","退款单:"+refundRecord.getCode()+";"+optName+",扣减充值资金:"+ordersTotal.getTotal(),refundRecord.getOperatorId(),refundRecord.getOrderId(),refundRecord.getInvalidAppCode(),refundRecord.getId(),ordersTotal.getTotal().negate(), UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND, OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.NO);
            orderLog = RefundToolUtil.setOrderLog(refundRecord, refundRecord.getOperatorId(), refundRecord.getOperatorName(), "充值单:"+ordersTotal.getOrderNo()+";"+optName+",预扣除金额:"+ordersTotal.getTotal(), 0, OrderLogConstants.LOG_TYPE_REFUND);
 
        }else if(optType == OPT_TYPE_CANCEL){
            //充值金额回退
            UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),REFUND_REMARK+"["+ordersTotal.getOrderNo()+"]","退款单:"+refundRecord.getCode()+";"+optName+",退回充值资金:"+ordersTotal.getTotal(),refundRecord.getInvalidId(),refundRecord.getOrderId(),refundRecord.getInvalidAppCode(),refundRecord.getId(),ordersTotal.getTotal(), UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND, OperationReasonConstants.OP_REASON_REFUND_CANCEL,commonService,UserMoneyUnclaimed.NO);
            orderLog = RefundToolUtil.setOrderLog(refundRecord, refundRecord.getOperatorId(), refundRecord.getOperatorName(), "充值单:"+ordersTotal.getOrderNo()+";"+optName+",退回预扣除金额:"+ordersTotal.getTotal(), 0, OrderLogConstants.LOG_TYPE_REFUND);
        }else{
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作类型错误[1]["+optType+"]!");
        }
        if(orderNodeBuilder !=null){
            orderNodeBuilder.append("-[").append(optName).append("]充值单充值金操作(储值金):").append(ordersTotal.getTotal());
        }
        orderLog.setOrderId(ordersTotal.getId());
        commonService.insert(OrderLogMapper.class,orderLog);
    }
 
    /**活动规则处理
     * @param ordersTotal 订单
     * @param refundRecord 退款单
     * @param optType 操作类型:0退款执行,1作废退款
     * @param optName 操作名称,如:申请退款、作废退款、审核拒绝
     * @param commonService 映射
     */
    public static void activityRuleHandle(OrdersTotal ordersTotal, RefundRecord refundRecord,int optType,String optName,StringBuilder orderNodeBuilder,CommonService commonService){
 
        //先获取活动规则
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        values.put("orderId",ordersTotal.getId());
        sqlSentence.sqlSentence("SELECT * FROM orders_activity_info WHERE isDel = 0 AND orderId = #{m.orderId}",values);
        List<OrdersActivityInfo> ordersActivityInfoList = commonService.selectList(OrdersActivityInfoMapper.class,sqlSentence);
        if(ordersActivityInfoList.size() > 0){
            //订单活动信息处理
            activityRulePollingHandle2(ordersActivityInfoList,optType,optName,ordersTotal,refundRecord,orderNodeBuilder,commonService);
        }else{
            //没有订单活动信息处理,就获取保存在订单里面的活动标识
            values.clear();
            values.put("orderId",ordersTotal.getId());
            sqlSentence.sqlSentence("SELECT * FROM orders_info WHERE isDel = 0 AND orderId = #{m.orderId}",values);
            OrderInfo orderInfo = commonService.selectOne(OrderInfoMapper.class,sqlSentence);
            if(orderInfo!=null && StringUtils.noNull(orderInfo.getActivityId())){
                activityRulePollingHandle1(orderInfo.getActivityId(),optType,optName,ordersTotal,refundRecord,orderNodeBuilder,commonService);
            }
        }
    }
 
    /**处理活动标识保存在订单里面的
     * @param activityId 活动标识
     * @param optType 操作类型:0退款执行,1退款作废
     * @param optName 操作名称,如:申请退款、作废退款、审核拒绝
     * @param ordersTotal 订单
     * @param refundRecord 退款单
     * @param commonService 映射
     */
    public static void activityRulePollingHandle1(String activityId,int optType,String optName,OrdersTotal ordersTotal,RefundRecord refundRecord
            ,StringBuilder orderNodeBuilder,CommonService commonService){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        //查找活动规则,没有找到就跳出循环
        ActivityRule activityRule = commonService.selectOneByKeyBlob(ActivityRuleMapper.class,activityId);
        if(activityRule == null){
            return;
        }
 
        values.put("activityRuleId",activityRule.getId());
        values.put("type", ActivityAction.TYPE_INTEGRAL);
        values.put("type1",ActivityAction.TYPE_VALUEADDEDFUND);
        values.put("type2",ActivityAction.TYPE_COUPON);
        sqlSentence.sqlSentence("select * from activity_action where activityRuleId=#{m.activityRuleId} and (type=#{m.type} or type=#{m.type1} or type=#{m.type2}) and isDel=0",values);
        List<ActivityAction> activityActions = commonService.selectList(ActivityActionMapper.class, sqlSentence);
        if(activityActions!=null && activityActions.size()>0){
            for (ActivityAction activityAction : activityActions) {
                if(ActivityAction.TYPE_INTEGRAL.equals(activityAction.getType())){
                    //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                    if(new BigDecimal(activityAction.getWorth()).compareTo(BigDecimal.ZERO) == 0){
                        continue;
                    }
                    if(optType == OPT_TYPE_EXECUTE){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"订单:"+ordersTotal.getOrderNo()+";"+optName+",预扣除活动规则赠送储值金金额:"+activityAction.getWorth(),refundRecord.getOperatorId(),refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),new BigDecimal(activityAction.getWorth()).negate(), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                    }else if(optType == OPT_TYPE_CANCEL){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"订单:"+ordersTotal.getOrderNo()+";"+optName+",返还赠送储值金预扣除金额:"+activityAction.getWorth(),refundRecord.getInvalidId(),refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),new BigDecimal(activityAction.getWorth()), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_REFUND_CANCEL,commonService,UserMoneyUnclaimed.YES);
                    }else{
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作类型错误[2]["+optType+"]!");
                    }
                    if(orderNodeBuilder !=null){
                        orderNodeBuilder.append("-[").append(optName).append("]处理活动赠送(积分):").append(activityAction.getWorth());
                    }
                }else if(ActivityAction.TYPE_VALUEADDEDFUND.equals(activityAction.getType())){
                    //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                    if(new BigDecimal(activityAction.getWorth()).compareTo(BigDecimal.ZERO) == 0 ){
                        continue;
                    }
                    if(optType == OPT_TYPE_EXECUTE){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"订单:"+ordersTotal.getOrderNo()+";"+optName+",预扣除活动规则赠送增值金金额:"+activityAction.getWorth(),refundRecord.getOperatorId(),refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),new BigDecimal(activityAction.getWorth()).negate(), UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                    }else if(optType == OPT_TYPE_CANCEL){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"订单:"+ordersTotal.getOrderNo()+";"+optName+",返还赠送增值金预扣除金额:"+activityAction.getWorth(),refundRecord.getInvalidId(),refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),new BigDecimal(activityAction.getWorth()), UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND,OperationReasonConstants.OP_REASON_REFUND_CANCEL,commonService,UserMoneyUnclaimed.YES);
                    }else{
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作类型错误[3]["+optType+"]!");
                    }
                    if(orderNodeBuilder !=null){
                        orderNodeBuilder.append("-[").append(optName).append("]处理活动赠送(增值金):").append(activityAction.getWorth());
                    }
                }else if(ActivityAction.TYPE_COUPON.equals(activityAction.getType())){
                    values.put("oldValidState",optType==OPT_TYPE_EXECUTE? BaseEntity.YES:BaseEntity.NO);
                    values.put("newValidState",optType==OPT_TYPE_EXECUTE?BaseEntity.NO:BaseEntity.YES);
                    values.put("couponId",activityAction.getCrmCouponId());
                    values.put("commonId",ordersTotal.getId());
                    sqlSentence.sqlSentence(" validState=#{m.newValidState} where couponId=#{m.couponId} and commonId=#{m.commonId} and validState=#{m.oldValidState} ",values);
                    if(commonService.updateWhere(CouponNumberMapper.class,sqlSentence) != 0){
                        if(orderNodeBuilder !=null){
                            orderNodeBuilder.append("-[").append(optName).append("]处理活动赠送(优惠券):").append(activityAction.getWorthName());
                        }
                    }
                }
            }
        }
    }
 
    /**处理活动保存在订单活动信息里面的
     * @param ordersActivityInfoList 订单活动数据
     * @param optType 操作类型:0退款退回,1作废退款
     * @param optName 操作名称,如:申请退款、作废退款、审核拒绝
     * @param ordersTotal 订单
     * @param refundRecord 退款单
     * @param commonService 映射
     */
    public static void activityRulePollingHandle2(List<OrdersActivityInfo> ordersActivityInfoList,int optType,String optName,OrdersTotal ordersTotal
            ,RefundRecord refundRecord,StringBuilder orderNodeBuilder,CommonService commonService){
        if(ordersActivityInfoList == null || ordersActivityInfoList.size()==0){
            return;
        }
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        //是否变更订单活动状态
        boolean changeStatus;
        //获取订单活动条目
        List<OrdersActivityInfoItem> ordersActivityInfoItemList;
        for(OrdersActivityInfo ordersActivityInfo:ordersActivityInfoList){
            values.clear();
            values.put("activityInfoId",ordersActivityInfo.getId());
            values.put("performStatus",OrdersActivityInfoItem.STATUS_PERFORM_SEND_OUT);
            values.put("handleStatus",optType==OPT_TYPE_EXECUTE?OrdersActivityInfoItem.HANDLE_STATUS_SUCCESS:OrdersActivityInfoItem.HANDLE_STATUS_CANCEL);
            sqlSentence.sqlSentence("SELECT * FROM orders_activity_info_item WHERE isDel = 0 AND activityInfoId = #{m.activityInfoId} AND performStatus = #{m.performStatus} AND handleStatus = #{m.handleStatus}",values);
            ordersActivityInfoItemList = commonService.selectList(OrdersActivityInfoItemMapper.class,sqlSentence);
            for(OrdersActivityInfoItem ordersActivityInfoItem:ordersActivityInfoItemList){
                changeStatus = false;
                if(ActivityAction.TYPE_INTEGRAL.equals(ordersActivityInfoItem.getType())){
                    //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                    if(new BigDecimal(ordersActivityInfoItem.getWorth()).compareTo(BigDecimal.ZERO) == 0){
                        continue;
                    }
                    if(optType == OPT_TYPE_EXECUTE){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"订单:"+ordersTotal.getOrderNo()+";"+optName+",预扣除活动规则赠送储值金金额:"+ordersActivityInfoItem.getWorth(),refundRecord.getOperatorId(),refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),new BigDecimal(ordersActivityInfoItem.getWorth()).negate(), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                    }else if(optType == OPT_TYPE_CANCEL){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"订单:"+ordersTotal.getOrderNo()+";"+optName+",返还赠送储值金预扣除金额:"+ordersActivityInfoItem.getWorth(),refundRecord.getInvalidId(),refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),new BigDecimal(ordersActivityInfoItem.getWorth()), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                    }else{
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作类型错误[2]["+optType+"]!");
                    }
                    if(orderNodeBuilder !=null){
                        orderNodeBuilder.append("-[").append(optName).append("]处理活动赠送(积分):").append(ordersActivityInfoItem.getWorth());
                    }
                    changeStatus = true;
                }else if(ActivityAction.TYPE_VALUEADDEDFUND.equals(ordersActivityInfoItem.getType())){
                    //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                    if(new BigDecimal(ordersActivityInfoItem.getWorth()).compareTo(BigDecimal.ZERO) == 0 ){
                        continue;
                    }
                    if(optType == OPT_TYPE_EXECUTE){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"订单:"+ordersTotal.getOrderNo()+";"+optName+",预扣除活动规则赠送增值金金额:"+ordersActivityInfoItem.getWorth(),refundRecord.getOperatorId(),refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),new BigDecimal(ordersActivityInfoItem.getWorth()).negate(), UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                    }else if(optType == OPT_TYPE_CANCEL){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"订单:"+ordersTotal.getOrderNo()+";"+optName+",返还赠送增值金预扣除金额:"+ordersActivityInfoItem.getWorth(),refundRecord.getInvalidId(),refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),new BigDecimal(ordersActivityInfoItem.getWorth()), UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                    }else{
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作类型错误[3]["+optType+"]!");
                    }
                    if(orderNodeBuilder !=null){
                        orderNodeBuilder.append("-[").append(optName).append("]处理活动赠送(增值金):").append(ordersActivityInfoItem.getWorth());
                    }
                    changeStatus = true;
                }else if(ActivityAction.TYPE_COUPON.equals(ordersActivityInfoItem.getType())){
                    values.clear();
                    values.put("oldValidState",optType==OPT_TYPE_EXECUTE? BaseEntity.YES:BaseEntity.NO);
                    values.put("newValidState",optType==OPT_TYPE_EXECUTE?BaseEntity.NO:BaseEntity.YES);
                    values.put("id",ordersActivityInfoItem.getCouponNumberId());
                    sqlSentence.sqlSentence(" validState=#{m.newValidState} where id=#{m.id} AND validState = #{m.oldValidState} ",values);
                    //优惠券不判断回退
                    if(commonService.updateWhere(CouponNumberMapper.class,sqlSentence) != 0){
                        if(orderNodeBuilder !=null){
                            orderNodeBuilder.append("-[").append(optName).append("]处理活动赠送(优惠券):").append(ordersActivityInfoItem.getWorthName());
                        }
                        changeStatus = true;
                    }
                }
                if(changeStatus){
                    //更新订单活动信息状态
                    values.clear();
                    values.put("handleStatus",optType==OPT_TYPE_EXECUTE?OrdersActivityInfoItem.HANDLE_STATUS_CANCEL:OrdersActivityInfoItem.HANDLE_STATUS_SUCCESS);
                    values.put("handleStatusOld",optType==OPT_TYPE_EXECUTE?OrdersActivityInfoItem.HANDLE_STATUS_SUCCESS:OrdersActivityInfoItem.HANDLE_STATUS_CANCEL);
                    values.put("performStatusOld",OrdersActivityInfoItem.STATUS_PERFORM_SEND_OUT);
                    values.put("id",ordersActivityInfoItem.getId());
                    sqlSentence.sqlSentence("handleStatus = #{m.handleStatus} WHERE id = #{m.id} AND handleStatus = #{m.handleStatusOld} AND performStatus = #{m.performStatusOld}",values);
                    if(commonService.updateWhere(OrdersActivityInfoItemMapper.class,sqlSentence) != 1){
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"活动条目状态变化错误:");
                    }
                }
            }
        }
    }
 
    /**
     * 退款作废-处理优惠券
     * @param ordersTotal 订单
     * @param refundRecord 退款总数据
     * @param commonService 映射
     */
    public static void handCoupon(OrdersTotal ordersTotal,RefundRecord refundRecord,StringBuilder orderNodeBuilder,CommonService commonService) {
 
        //回退的优惠券变成使用状态
        //如果该优惠券在别的订单使用了,那么就不再理会
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> values = new HashMap<>();
 
        values.put("refundRecordId",refundRecord.getId());
        sqlSentence.sqlSentence("select * from refund_record_coupon where refundRecordId = #{m.refundRecordId} and isDel=0 ",values);
        List<RefundRecordCoupon> refundRecordCouponList=commonService.selectList(RefundRecordCouponMapper.class,sqlSentence);
 
        CouponOrderDiscountLog couponOrderDiscountLog;
        for (RefundRecordCoupon refundRecordCoupon : refundRecordCouponList) {
 
            couponOrderDiscountLog=commonService.selectOneByKey(CouponOrderDiscountLogMapper.class,refundRecordCoupon.getCouponOrderId());
            if(couponOrderDiscountLog==null){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单优惠卷标识不正确");
            }
 
            //领建优惠券跳过回退
            if(PartialRefundUtil.HIS_COUPON_CODE.equals(couponOrderDiscountLog.getCouponNumberId())){
                //变更订单优惠券记录状态
                values.clear();
                values.put("status", BaseEntity.NO);
                values.put("oldStatus", BaseEntity.YES);
                values.put("id", couponOrderDiscountLog.getId());
                sqlSentence.sqlSentence("status = #{m.status} WHERE id = #{m.id} AND status = #{m.oldStatus}",values);
                if(commonService.updateWhere(CouponOrderDiscountLogMapper.class,sqlSentence) != 1){
                    throw new TipsException("优惠券回退失败!");
                }
            }else{
                //优惠券状态变化
                values.clear();
                values.put("isUse", BaseEntity.YES);
                values.put("isUseOld", BaseEntity.NO);
                values.put("useTime", couponOrderDiscountLog.getCreateTime());
                values.put("useType", CouponNumber.USE_TYPE_USER);
                values.put("id", couponOrderDiscountLog.getCouponNumberId());
                sqlSentence.sqlSentence("  isUse=#{m.isUse},useTime=#{m.useTime},useType=#{m.useType},isUse=#{m.isUse} WHERE id = #{m.id} AND isUse = #{m.isUseOld}",values);
                if(commonService.updateWhere(CouponNumberMapper.class,sqlSentence) != 0){
                    if(orderNodeBuilder != null){
                        orderNodeBuilder.append("-[作废退款]使用优惠券处理:"+couponOrderDiscountLog.getTitle());
                    }
                    //变更订单优惠券记录状态
                    values.clear();
                    values.put("status", BaseEntity.NO);
                    values.put("oldStatus", BaseEntity.YES);
                    values.put("id", couponOrderDiscountLog.getId());
                    sqlSentence.sqlSentence("status = #{m.status} WHERE id = #{m.id} AND status = #{m.oldStatus}",values);
                    if(commonService.updateWhere(CouponOrderDiscountLogMapper.class,sqlSentence) != 1) {
                        throw new TipsException("优惠券回退失败!");
                    }
                }
            }
        }
    }
 
    /**作废退款-爆款活动赠送处理*/
    public static void burstActivityHandle(StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord,CommonService commonService){
        //不是爆款活动
        if(ordersTotal.getActivityPageType() != OrderTotalConstants.ACTIVITY_TYPE_BURST){
            return;
        }
 
        //查找是否处理了赠送的增值金
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
        values.put("isDel",102);
        values.put("orderId",refundRecord.getOrderId());
        sqlSentence.sqlSentence("SELECT * FROM refund_user_assets rua WHERE rua.isDel = #{m.isDel} AND rua.status = 1 AND rua.amountStatus IN(1,3) AND rua.orderId = #{m.orderId}",values);
        List<RefundUserAssets> refundUserAssetsList = commonService.selectList(RefundUserAssetsMapper.class,sqlSentence);
        if(refundUserAssetsList.size() == 0){
            return;
        }
 
        for(RefundUserAssets refundUserAssets:refundUserAssetsList){
            //判断是否已经存在了别的赠送记录
            if(OrderTool.getActivityGive(refundUserAssets.getUserId(),ordersTotal.getActivityPageCode(),commonService).size() == 0){
                //是否有扣减用户资产
                if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NORMAL){
                    orderNodeBuilder.append(",活动赠送增加成功");
                    UserMoneyUtil.setNewUserMoneyUnclaimed(refundUserAssets.getUserId(),refundRecord.getRemarks(),"退款作废:活动赠送资金回退作废",refundUserAssets.getOperatorId()
                            ,refundRecord.getOrderId(),refundRecord.getOperatorAppCode(),refundUserAssets.getId(),refundUserAssets.getAmount().negate(),refundUserAssets.getAmountType()
                            ,OperationReasonConstants.OP_REASON_BRING_NEW_USER_GIFT_RETRU_CANCEL,commonService,UserMoneyUnclaimed.YES);
                }else if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NOT_RECEIVE){
                    //用户未领取记录,还原
                    orderNodeBuilder.append(",活动赠送用户未领取,作废的领取记录还原");
                    values.clear();
                    values.put("id",refundUserAssets.getUserMoneyUnclaimedId());
                    values.put("status",UserMoneyUnclaimed.STATUS_WAI);
                    sqlSentence.sqlUpdate("isDel = 0,isValid = 1 WHERE id = #{m.id} AND isDel = 1 AND isValid = 0 AND status = #{m.status}",values);
                    if(commonService.updateWhere(UserMoneyUnclaimedMapper.class,sqlSentence) != 1){
                        throw new TipsException("活动赠送资产记录状态已变化[作废]!");
                    }
                }
            }
 
            //记录作废
            values.clear();
            values.put("id",refundUserAssets.getId());
            values.put("status",RefundUserAssets.STATUS_CANCEL);
            values.put("oldStatus",RefundUserAssets.STATUS_NORMAL);
            sqlSentence.sqlSentence("status = #{m.status} WHERE id = #{m.id} AND status = #{m.oldStatus}",values);
            if(commonService.updateWhere(RefundUserAssetsMapper.class,sqlSentence) != 1){
                throw new TipsException("活动赠送资产退款记录状态已变化[作废]!");
            }
        }
    }
 
    /**退款子项处理*/
    public static void refundRecordItemHandle(OrdersTotal ordersTotal,RefundRecord refundRecord,CommonService commonService){
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        //获取退款子单
        values.put("refundRecordId",refundRecord.getId());
        sqlSentence.sqlSentence("SELECT * FROM refund_record_item WHERE isDel = 0 AND refundRecordId = #{m.refundRecordId}",values);
        List<RefundRecordItem> refundRecordItems =commonService.selectList(RefundRecordItemMapper.class,sqlSentence);
        if(refundRecordItems == null || refundRecordItems.size() == 0){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到退款子订单信息");
        }
 
        for (RefundRecordItem refundRecordItem: refundRecordItems) {
            //商品类型判断
            switch (refundRecordItem.getType()){
                case OrderItemConstants.TYPE_RETAIL:
                    //商品/药品
                    rerailHandleOne(refundRecordItem,commonService);
                    break;
                case OrderItemConstants.TYPE_DRUG:
                    //处方单药品
                    rerailHandleOne(refundRecordItem,commonService);
                    break;
                case OrderItemConstants.TYPE_PROJECT:
                    //项目
                    projectHandleOne(refundRecordItem,refundRecord,commonService);
                    break;
                case OrderItemConstants.TYPE_PROMOTION:
                    //促销
                    handRefundPromotion( refundRecordItem, refundRecord, commonService);
                    break;
                case OrderItemConstants.TYPE_CARD:
                    //卡项
                    cardHandleOne( refundRecord,  refundRecordItem, commonService);
                    break;
                case OrderItemConstants.CARD_BAG:
                    //卡包
                    handRefundPromotion( refundRecordItem, refundRecord, commonService);
                    break;
                default:
                    //其他
                    rerailHandleOne(refundRecordItem,commonService);
                    break;
            }
        }
    }
 
 
    /**一级订单-商品/药品处理*/
    public static void rerailHandleOne(RefundRecordItem refundRecordItem,CommonService commonService){
        //判断操作完了去修改子订单状态
        OrderItem orderItem=commonService.selectOneByKey(OrderItemMapper.class,refundRecordItem.getOrderItemId());
        if (orderItem==null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"未找到子订单信息");
        }
 
        //剩余可退款数量
        if(refundRecordItem.getRefundNum() > orderItem.getHasReNum()){
            throw new TipsException(orderItem.getGoodsName()+"["+orderItem.getGoodsNo()+"]"+"作废退款数量不能大于已退款数量!");
        }
 
        //变更退款子项信息
        int refundStatus;
        if (orderItem.getHasReNum().equals(refundRecordItem.getRefundNum())){
            refundStatus = OrderTotalConstants.STATUS_REFUND_NONE;
        }else{
            refundStatus = OrderTotalConstants.STATUS_REFUND_PART;
        }
        RefundCarryVo refundCarryVo = new RefundCarryVo();
        refundCarryVo.setRefundTotal(refundRecordItem.getRealRefundTotal().negate());
        refundCarryVo.setIntegralTotal(refundRecordItem.getRealRefundIntegral().negate());
        refundCarryVo.setDeductionTotal(refundRecordItem.getDeductionTotal().negate());
        refundCarryVo.setCashTotal(refundRecordItem.getCashTotal().negate());
        refundCarryVo.setCashPurenessTotal(refundRecordItem.getCashPurenessTotal().negate());
        refundCarryVo.setRechargeTotal(refundRecordItem.getRechargeTotal().negate());
        refundCarryVo.setIncrementTotal(refundRecordItem.getIncrementTotal().negate());
 
        //更新子订单信息
        PartialRefundUtil.updateOrderItemOne(orderItem,refundStatus,refundCarryVo,-refundRecordItem.getRealRefundNum(), commonService);
    }
 
    /**一级订单-项目处理*/
    public static void projectHandleOne(RefundRecordItem refundRecordItem,RefundRecord refundRecord,CommonService commonService){
        //找到子单
        OrderItem orderItem=commonService.selectOneByKey(OrderItemMapper.class,refundRecordItem.getOrderItemId());
        if (orderItem==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到子订单信息");
        }
        //计算子单是否还有剩余的可扣疗程数
        if(refundRecordItem.getRefundNum() > orderItem.getHasReNum()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,orderItem.getGoodsName()+"["+orderItem.getGoodsNo()+"]"+"退款次数大于可退次数[54]!");
        }
 
        //找到用户项目
        UserProjectItem userProjectItem = PartialRefundUtil.getUserProject(orderItem.getId(),commonService);
        if (userProjectItem == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,orderItem.getGoodsName()+"["+orderItem.getGoodsNo()+"]"+"未找到用户子项项目信息");
        }
        if(userProjectItem.getCancelNum() < refundRecordItem.getRefundNum()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,orderItem.getGoodsName()+"["+orderItem.getGoodsNo()+"]"+"作废退款次数大于用户项目已退次数!");
        }
 
        //用户项目操作
        UserProjectTool.userProjectDeduction(userProjectItem, UserProjectUsedCon.USED_METHOD_ORDER_REFUND,UserProjectUsedCon.USED_TYPE_RETURN,refundRecordItem.getDeductionTotalUser()
                ,refundRecordItem.getId(),refundRecordItem.getRealRefundNum(),refundRecord.getInvalidAppId(),refundRecord.getInvalidAppName(),refundRecord.getRefundShopId(),refundRecord.getRefundShopName(),"员工备注:"+refundRecord.getInvalidRemarks(),commonService);
 
        int refundStatus;
        if(refundRecordItem.getRefundNum().equals(orderItem.getHasReNum())){
            refundStatus=OrderTotalConstants.STATUS_REFUND_NONE;
        }else{
            refundStatus=OrderTotalConstants.STATUS_REFUND_PART;
        }
 
        RefundCarryVo refundCarryVo = new RefundCarryVo();
        refundCarryVo.setRefundTotal(refundRecordItem.getRealRefundTotal().negate());
        refundCarryVo.setIntegralTotal(refundRecordItem.getRealRefundIntegral().negate());
        refundCarryVo.setDeductionTotal(refundRecordItem.getDeductionTotal().negate());
        refundCarryVo.setCashTotal(refundRecordItem.getCashTotal().negate());
        refundCarryVo.setCashPurenessTotal(refundRecordItem.getCashPurenessTotal().negate());
        refundCarryVo.setRechargeTotal(refundRecordItem.getRechargeTotal().negate());
        refundCarryVo.setIncrementTotal(refundRecordItem.getIncrementTotal().negate());
 
        //更新子订单信息
        PartialRefundUtil.updateOrderItemOne(orderItem,refundStatus,refundCarryVo,-refundRecordItem.getRealRefundNum(),commonService);
    }
 
    /**一级子单-处理促销*/
    private static void handRefundPromotion(RefundRecordItem refundRecordItem, RefundRecord refundRecord, CommonService commonService) {
 
        //查看订单信息
        OrderItem orderItem = commonService.selectOneByKey(OrderItemMapper.class,refundRecordItem.getOrderItemId());
        if(orderItem == null ){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"未找到子订单信息[84]!");
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> map = new HashMap<>();
 
        //获取退款二级单
        map.put("refundRecordItemId",refundRecordItem.getId());
        sqlSentence.sqlSentence("select * from refund_record_item_source where isDel = 0 AND refundRecordItemId = #{m.refundRecordItemId}",map);
        List<RefundRecordItemSource> sons = commonService.selectList(RefundRecordItemSourceMapper.class, sqlSentence);
 
        for (RefundRecordItemSource son : sons) {
            switch (GroupTypeEnum.getCode(son.getType())){
                case PROJECT:
                    projectHandleTwo(refundRecord,refundRecordItem, son,orderItem.getUserCardId(),commonService);
                    break;
                case RETAIL:
                    rerailHandleTwo(refundRecord,refundRecordItem,son,orderItem.getUserCardId(),commonService);
                    break;
                case INCREMENT:
                    //增值金
                    //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                    if(son.getRealRefundTotal().negate().compareTo(BigDecimal.ZERO)!=0){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"作废退款:促销赠送增值金扣减",refundRecord.getInvalidId(),refundRecord.getOrderId(),refundRecord.getInvalidAppCode(),refundRecord.getId(),son.getRealRefundTotal(), UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND, OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                    }
                    break;
                case STORED:
                    //储值金额
                    //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                    if(son.getRealRefundTotal().negate().compareTo(BigDecimal.ZERO)!=0){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"作废退款:促销赠送储值金额扣减",refundRecord.getInvalidId(),refundRecord.getOrderId(),refundRecord.getInvalidAppCode(),refundRecord.getId(),son.getRealRefundTotal(), UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND, OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.NO);
                    }
                    break;
                case INTEGRAL:
                    //积分
                    //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                    if(son.getRealRefundTotal().negate().compareTo(BigDecimal.ZERO)!=0){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"作废退款:促销赠送积分扣减",refundRecord.getInvalidId(),refundRecord.getOrderId(),refundRecord.getInvalidAppCode(),refundRecord.getId(),son.getRealRefundTotal(), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                    }
                    break;
            }
 
        }
 
        //获取其子项
        map.put("orderItemId",orderItem.getId());
        sqlSentence.sqlSentence("select refundStatus from order_item_source WHERE orderItemId=#{m.orderItemId} and isDel=0",map);
        List<OrderItemSon> orderItemSonList=commonService.selectList(OrderItemSonMapper.class,sqlSentence);
        int refundStatus;
        Integer refundNum = 0;
        List<Integer> collect = orderItemSonList.stream().map(OrderItemSon::getRefundStatus).collect(Collectors.toList());
 
        if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
            refundStatus = OrderTotalConstants.STATUS_REFUND_PART;
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
            if(collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
                refundStatus = OrderTotalConstants.STATUS_REFUND_PART;
            }else{
                refundStatus = OrderTotalConstants.STATUS_REFUND_NONE;
            }
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
            refundStatus = OrderTotalConstants.STATUS_REFUND_FINSH;
            refundNum = orderItem.getBuyNum();
        }else {
            refundStatus = OrderTotalConstants.STATUS_REFUND_NONE;
        }
 
        RefundCarryVo refundCarryVo = new RefundCarryVo();
        refundCarryVo.setRefundTotal(refundRecordItem.getRealRefundTotal().negate());
        refundCarryVo.setIntegralTotal(refundRecordItem.getRealRefundIntegral().negate());
        refundCarryVo.setDeductionTotal(refundRecordItem.getDeductionTotal().negate());
        refundCarryVo.setCashTotal(refundRecordItem.getCashTotal().negate());
        refundCarryVo.setCashPurenessTotal(refundRecordItem.getCashPurenessTotal().negate());
        refundCarryVo.setRechargeTotal(refundRecordItem.getRechargeTotal().negate());
        refundCarryVo.setIncrementTotal(refundRecordItem.getIncrementTotal().negate());
 
        //更新子订单信息
        PartialRefundUtil.updateOrderItemOne(orderItem,refundStatus,refundCarryVo,-refundNum,commonService);
 
    }
 
    /**二级子订单-项目类型
     * @param refundRecord 退款总记录
     * @param refundRecordItem 退款一级子单
     * @param refundRecordItemSource  退款二级子单
     * @param userCardId 用户卡包标识
     * @param commonService 映射
     */
    private static void projectHandleTwo(RefundRecord refundRecord,RefundRecordItem refundRecordItem, RefundRecordItemSource refundRecordItemSource
            ,String userCardId,CommonService commonService) {
 
        //判断操作完了去修改子订单状态
        OrderItemSon orderItemSon = commonService.selectOneByKey(OrderItemSonMapper.class,refundRecordItemSource.getOrderItemSonId());
        if (orderItemSon==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到二级子订单信息[02]");
        }
        //计算子单是否还有剩余的可扣疗程数
        if(refundRecordItemSource.getRefundNum() > orderItemSon.getHasReNum()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,orderItemSon.getGoodsName()+"["+orderItemSon.getGoodsNo()+"]"+"作废退款次数大于已退次数[56]!");
        }
 
        UserProjectItem userProjectItem = PartialRefundUtil.getUserProject(orderItemSon.getId(),commonService);
        if(userProjectItem == null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"用户项目获取失败[06]!");
        }
        //比较作废退款数量
        if(refundRecordItemSource.getRefundNum() > userProjectItem.getCancelNum()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,orderItemSon.getGoodsName()+"["+orderItemSon.getGoodsNo()+"]"+"作废退款次数大于用户项目已退次数[56]!");
        }
 
        //处理用户项目,减去用户项目数量
        UserProjectTool.userProjectDeduction(userProjectItem,UserProjectUsedCon.USED_METHOD_ORDER_REFUND,UserProjectUsedCon.USED_TYPE_RETURN,refundRecordItemSource.getDeductionTotalUser()
                ,refundRecordItemSource.getId(),refundRecordItemSource.getRealRefundNum(),refundRecord.getInvalidAppId(),refundRecord.getInvalidAppName(),refundRecord.getRefundShopId(),refundRecord.getRefundShopName(),"员工备注:"+refundRecord.getInvalidRemarks(),commonService);
 
        int refundStatus;
        if(orderItemSon.getHasReNum().equals(refundRecordItemSource.getRefundNum())){
            refundStatus=OrderTotalConstants.STATUS_REFUND_NONE;
        }else{
            refundStatus=OrderTotalConstants.STATUS_REFUND_PART;
        }
 
        RefundCarryVo refundCarryVo = new RefundCarryVo();
        refundCarryVo.setRefundTotal(refundRecordItemSource.getRealRefundTotal().negate());
        refundCarryVo.setIntegralTotal(refundRecordItemSource.getRealRefundIntegral().negate());
        refundCarryVo.setDeductionTotal(refundRecordItemSource.getDeductionTotal().negate());
        refundCarryVo.setCashTotal(refundRecordItemSource.getCashTotal().negate());
        refundCarryVo.setCashPurenessTotal(refundRecordItemSource.getCashPurenessTotal().negate());
        refundCarryVo.setRechargeTotal(refundRecordItemSource.getRechargeTotal().negate());
        refundCarryVo.setIncrementTotal(refundRecordItemSource.getIncrementTotal().negate());
 
        //更新子单信息
        PartialRefundUtil.updateOrderItemTwo(orderItemSon,refundStatus,refundCarryVo,-refundRecordItemSource.getRealRefundNum(),commonService);
 
        if(refundRecordItem.getType().equals(OrderItemConstants.CARD_BAG)){
            //是卡包的,找回卡包使用记录
            userCardUsedHandle(userCardId,orderItemSon.getCardItemInfoId(),orderItemSon.getId(),orderItemSon.getOrderId(),refundRecordItemSource.getRefundNum(),commonService);
        }
 
    }
 
    /**二级订单-商品/药品
     * @param refundRecord 退款总记录
     * @param refundRecordItem 退款一级子单
     * @param refundRecordItemSource  退款二级子单
     * @param commonService 映射
     * @return 全局携带参数结构
     */
    private static void rerailHandleTwo(RefundRecord refundRecord,RefundRecordItem refundRecordItem, RefundRecordItemSource refundRecordItemSource
            ,String userCardId,CommonService commonService) {
 
        //判断操作完了去修改子订单状态
        OrderItemSon orderItemSon=commonService.selectOneByKey(OrderItemSonMapper.class,refundRecordItemSource.getOrderItemSonId());
        if (orderItemSon==null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"未找到二级子订单信息");
        }
 
        //计算子单是否还有剩余的可扣疗程数
        if(refundRecordItemSource.getRefundNum() > orderItemSon.getHasReNum()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"作废退款次数大于已退次数[84]!");
        }
 
        int refundStatus;
        if(orderItemSon.getHasReNum().equals(refundRecordItemSource.getRefundNum())){
            refundStatus=OrderTotalConstants.STATUS_REFUND_NONE;
        }else{
            refundStatus=OrderTotalConstants.STATUS_REFUND_PART;
        }
 
        RefundCarryVo refundCarryVo = new RefundCarryVo();
        refundCarryVo.setRefundTotal(refundRecordItemSource.getRealRefundTotal().negate());
        refundCarryVo.setIntegralTotal(refundRecordItemSource.getRealRefundIntegral().negate());
        refundCarryVo.setDeductionTotal(refundRecordItemSource.getDeductionTotal().negate());
        refundCarryVo.setCashTotal(refundRecordItemSource.getCashTotal().negate());
        refundCarryVo.setCashPurenessTotal(refundRecordItemSource.getCashPurenessTotal().negate());
        refundCarryVo.setRechargeTotal(refundRecordItemSource.getRechargeTotal().negate());
        refundCarryVo.setIncrementTotal(refundRecordItemSource.getIncrementTotal().negate());
 
        PartialRefundUtil.updateOrderItemTwo(orderItemSon,refundStatus,refundCarryVo,-refundRecordItemSource.getRealRefundNum(),commonService);
 
        if(refundRecordItem.getType().equals(OrderItemConstants.CARD_BAG)){
            //是卡包的,刪除卡包使用
            userCardUsedHandle(userCardId,orderItemSon.getCardItemInfoId(),orderItemSon.getId(),orderItemSon.getOrderId(),refundRecordItemSource.getRefundNum(),commonService);
        }
 
    }
 
    /**卡包使用记录-状态变化
     * @param userCardId 用户卡包
     * @param cardItemInfoId 卡包的卡项子项
     * @param sourceId 卡包使用记录来源标识
     * @param orderId 卡包使用记录来源总表标识
     * @param refundNum 退款数量
     * @param commonService 映射
     */
    public static void userCardUsedHandle(String userCardId,String cardItemInfoId,String sourceId,String orderId,Integer refundNum
            ,CommonService commonService){
 
        //查出用户,commonId:卡项的组合项标识
        CardItemInfo cardItemInfo = commonService.selectOneByKey(CardItemInfoMapper.class,cardItemInfoId);
        if(cardItemInfo == null){
            logger.error("未找到该卡包的组合项-卡包作废退款失败,userCardId:{},cardItemInfoId:{},sourceId:{},orderId:{},refundNum:{}",userCardId,cardItemInfoId,sourceId,orderId,refundNum);
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该卡包的组合项");
        }
 
        UserCard userCard = commonService.selectOneByKey(UserCardMapper.class,userCardId);
        if(userCard == null){
            logger.error("未找到该卡包-卡包作废退款失败,userCardId:{},cardItemInfoId:{},sourceId:{},orderId:{},refundNum:{}",userCardId,cardItemInfoId,sourceId,orderId,refundNum);
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该卡包信息");
        }
 
        //获取权益类型
        CardEquity cardEquity = commonService.selectOneByKey(CardEquityMapper.class,cardItemInfo.getCardEquityId());
        if(cardEquity == null){
            logger.error("未找到该卡包的组合项权益类型-卡包作废退款失败,userCardId:{},cardItemInfoId:{},sourceId:{},orderId:{},refundNum:{}",userCardId,cardItemInfoId,sourceId,orderId,refundNum);
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该卡包的组合项权益类型");
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map = new HashMap<>();
 
        //获取作废使用记录
        map.put("cardItemInfoId",cardItemInfoId);
        map.put("sourceId",sourceId);
        map.put("userCardId",userCardId);
        sqlSentence.sqlSentence(" SELECT * FROM user_card_used WHERE isDel = 1 AND userCardId = #{m.userCardId}" +
                " AND cardItemInfoId = #{m.cardItemInfoId} AND sourceId = #{m.sourceId}",map);
        List<UserCardUsed> userCardUsedList = commonService.selectList(UserCardUsedMapper.class,sqlSentence);
 
        //因为之前的使用记录有些没有关联到订单,所以找不到
        if(userCardUsedList == null || userCardUsedList.size() == 0){
            map.clear();
            map.put("cardItemInfoId",cardItemInfoId);
            map.put("userCardId",userCardId);
            map.put("orderId",orderId);
            sqlSentence.sqlSentence(" SELECT * FROM user_card_used WHERE isDel = 1 AND userCardId = #{m.userCardId}" +
                    " AND cardItemInfoId = #{m.cardItemInfoId} AND orderId = #{m.orderId} AND sourceId IS NULL",map);
            userCardUsedList = commonService.selectList(UserCardUsedMapper.class,sqlSentence);
            if(userCardUsedList.size() == 0){
                sqlSentence.sqlSentence(" SELECT * FROM user_card_used WHERE isDel = 1 AND userCardId = #{m.userCardId}" +
                        " AND cardItemInfoId = #{m.cardItemInfoId} AND sourceId IS NULL",map);
                userCardUsedList = commonService.selectList(UserCardUsedMapper.class,sqlSentence);
            }
        }
 
        //计算当前数量要扣的卡次
        int returnNum = UserCardTool.countUsedNumber(refundNum,cardItemInfo,cardEquity);
        //获取可扣卡次
        UserCardItemInfoVo userCardItemInfoVo = UserCardTool.getSurplusNumber(userCard,cardItemInfo,cardEquity,commonService);
        if(!userCardItemInfoVo.isNumByNum()){
            throw new TipsException("作废退款-卡包扣减失败,不符合N选M规则!");
        }
        if(returnNum > userCardItemInfoVo.getSurplusNum()){
            throw new TipsException("作废退款-卡包扣减失败,抵扣次数不足!");
        }
 
        if(returnNum > userCardUsedList.size()){
            logger.error("卡包可退数量错误-卡包作废退款失败,查询语句:{},传入参数:{}",sqlSentence.getSqlSentence(), JSON.toJSONString(sqlSentence.getM()));
            logger.error("卡包可退数量错误-卡包作废退款失败,userCardId:{},cardItemInfoId:{},sourceId:{},orderId:{},refundNum:{},returnNum:{}",userCardId,cardItemInfoId,sourceId,orderId,refundNum,returnNum);
            throw new TipsException("卡包作废退款次数量大于可退次数!");
        }
 
        //已经操作数量
        int opNum = returnNum;
        StringBuilder sql;
        for(UserCardUsed userCardUsed:userCardUsedList){
            //判断是否够了,跳出循环
            if(opNum <= 0){
                break;
            }
            if(userCardUsed.getCancelNum() <= 0){
                continue;
            }
            sql = new StringBuilder();
            map.clear();
            map.put("id",userCardUsed.getId());
            map.put("cancelNumOld",userCardUsed.getCancelNum());
            if(opNum >= userCardUsed.getCancelNum()){
                map.put("isDel",UserCardUsed.NO);
                map.put("countNum",userCardUsed.getCancelNum());
                opNum = opNum - userCardUsed.getCancelNum();
            }else{
                map.put("isDel",UserCardUsed.YES);
                map.put("countNum",opNum);
                opNum = 0;
            }
            sql.append("isDel = #{m.isDel}");
            sql.append(",usedNum =  usedNum + #{m.countNum}");
            sql.append(",cancelNum =  cancelNum - #{m.countNum}");
            if(StringUtils.isEmpty(userCardUsed.getOrderId())){
                sql.append(",orderId = #{m.orderId}");
                map.put("orderId",orderId);
            }
            if(StringUtils.isEmpty(userCardUsed.getSourceId())){
                sql.append(",sourceId = #{m.sourceId}");
                map.put("sourceId",sourceId);
            }
            sql.append(" WHERE id = #{m.id} AND cancelNum = #{m.cancelNumOld}");
            sqlSentence.sqlUpdate(sql.toString(),map);
            if(commonService.updateWhere(UserCardUsedMapper.class,sqlSentence) != 1){
                throw new TipsException("卡包使用记录已发生变化,请重试!");
            }
        }
        if(opNum != 0){
            logger.error("卡包回退数量错误-卡包作废退款失败,userCardId:{},cardItemInfoId:{},sourceId:{},orderId:{},refundNum:{},returnNum:{},opNum:{}",userCardId,cardItemInfoId,sourceId,orderId,refundNum,returnNum,opNum);
            throw new TipsException("卡包作废回退数量错误!");
        }
 
    }
 
    /**一级子单-处理卡项
     * @param refundRecord 退款总记录
     * @param refundRecordItem 退款一级记录
     * @param commonService 映射
     * @return 全局携带参数结构
     */
    public static void cardHandleOne(RefundRecord refundRecord, RefundRecordItem refundRecordItem,CommonService commonService) {
 
        //判断操作完了去修改子订单状态
        OrderItem orderItem=commonService.selectOneByKey(OrderItemMapper.class,refundRecordItem.getOrderItemId());
        if (orderItem==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到子订单信息");
        }
 
        if(refundRecordItem.getRefundNum() > orderItem.getHasReNum()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"作废退款-卡包提示:作废卡包退款数量大于已退款数量[020]");
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
 
        //找到已退款卡包
        values.put("status",RefundRecordCard.YES);
        values.put("refundRecordItemId",refundRecordItem.getId());
        sqlSentence.sqlSentence("SELECT * FROM refund_record_card WHERE isDel = 0 AND status = #{m.status} AND refundRecordItemId = #{m.refundRecordItemId}",values);
        List<RefundRecordCard> refundRecordCardList = commonService.selectList(RefundRecordCardMapper.class,sqlSentence);
        if(refundRecordItem.getRefundNum() > refundRecordCardList.size()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"作废退款-卡包提示:作废卡包退款数量大于已退款数量[021]");
        }
 
        //变更卡项状态
        RefundRecordCard refundRecordCard;
        for (int i = 0; i < refundRecordItem.getRefundNum(); i++) {
            refundRecordCard= refundRecordCardList.get(i);
            values.clear();
            values.put("id",refundRecordCard.getUserCardId());
            values.put("statusOld", UserCard.TYPE_NO_USED);
            values.put("effectiveStatus", UserProjectConstants.EFF_STATUS_YES);
            values.put("oldEffectiveStatus", UserProjectConstants.EFF_STATUS_CANCEL);
            sqlSentence.sqlSentence(" effectiveStatus=#{m.effectiveStatus} WHERE id = #{m.id} AND effectiveStatus = #{m.oldEffectiveStatus} AND status = #{m.statusOld}",values);
            if(commonService.updateWhere(UserCardMapper.class,sqlSentence) != 1){
                throw new TipsException("用户卡包状态已发生变化,请重试!");
            }
 
            values.clear();
            values.put("id",refundRecordCard.getId());
            values.put("status",RefundRecordCard.NO);
            values.put("statusOld",RefundRecordCard.YES);
            sqlSentence.sqlSentence("status = #{m.status} WHERE id = #{m.id} AND status = #{m.statusOld}",values);
            if(commonService.updateWhere(RefundRecordCardMapper.class,sqlSentence) != 1){
                throw new TipsException("退款卡包状态已发生变化,请重试!");
            }
        }
 
        int refundStatus;
        //根据数量比较
        if (orderItem.getHasReNum().equals(refundRecordItem.getRefundNum())){
            refundStatus =  OrderTotalConstants.STATUS_REFUND_NONE;
        }else {
            refundStatus =  OrderTotalConstants.STATUS_REFUND_PART;
        }
        //根据金额比较
        if(refundStatus == OrderTotalConstants.STATUS_REFUND_NONE){
            if(orderItem.getReTotal().compareTo(refundRecordItem.getRealRefundTotal())>0){
                refundStatus =  OrderTotalConstants.STATUS_REFUND_PART;
            }
        }
 
        //查看是否用户卡包退款
        if(RefundSoruceConstants.TYPE_SOURCE_USER_CARD.equals(refundRecord.getSourceAssistantType())){
            CardRefundTool.cardItemCancel(refundRecord,refundRecordItem,commonService);
        }
 
        RefundCarryVo refundCarryVo = new RefundCarryVo();
        refundCarryVo.setRefundTotal(refundRecordItem.getRealRefundTotal().negate());
        refundCarryVo.setIntegralTotal(refundRecordItem.getRealRefundIntegral().negate());
        refundCarryVo.setDeductionTotal(refundRecordItem.getDeductionTotal().negate());
        refundCarryVo.setCashTotal(refundRecordItem.getCashTotal().negate());
        refundCarryVo.setCashPurenessTotal(refundRecordItem.getCashPurenessTotal().negate());
        refundCarryVo.setRechargeTotal(refundRecordItem.getRechargeTotal().negate());
        refundCarryVo.setIncrementTotal(refundRecordItem.getIncrementTotal().negate());
 
        //更新子订单信息
        PartialRefundUtil.updateOrderItemOne(orderItem,refundStatus,refundCarryVo,-refundRecordItem.getRealRefundNum(),commonService);
    }
 
}