chenjiahe
2023-04-03 e9e32c597f1b95ca18c632cafc551952aa797b81
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
package com.hx.phip.tool.refund;
 
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.UserMoney;
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.consume.ConsumePay;
import com.hx.phiappt.model.consume.ConsumePayItem;
import com.hx.phiappt.model.consume.ConsumePayItemSon;
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.tool.user.UserProjectTool;
import com.hx.phip.util.api.UserMoneyUtil;
import com.hx.phip.vo.order.refund.RefundCarryVo;
import com.hx.phip.vo.user.UserProjectDeductionVo;
import com.hx.util.StringUtils;
import com.platform.exception.PlatTipsException;
import com.platform.resultTool.PlatformCode;
import org.springframework.beans.BeanUtils;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @Author
 */
public class PartialRefundUtil {
 
    /**有子项退款的类型*/
    public static Set<String> CONTAIN_SON_TYPE_SET;
 
    /**领建优惠券标识*/
    public static final String HIS_COUPON_CODE = "his_coupon_code";
 
    static {
        CONTAIN_SON_TYPE_SET = new HashSet<>();
        CONTAIN_SON_TYPE_SET.add(OrderItemConstants.TYPE_PROMOTION);
        CONTAIN_SON_TYPE_SET.add(OrderItemConstants.CARD_BAG);
    }
 
    /**
     * 退款总流程工具
     * @param commonService 映射
     * @param operationId 操作人标识
     * @param operationNme 操作人名称
     * @param refundId 退款总单标识
     */
    public static OrdersTotal refundProcess(CommonService commonService, String operationId, String operationNme, String refundId) {
 
        RefundRecord refundRecord = commonService.selectOneByKeyBlob(RefundRecordMapper.class,refundId);
        if(refundRecord ==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"找不到该退款信息!");
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        //退款总订单状态变更
        values.put("refundStatus", RefundStatus.STATUS_SUCC_REFUND);
        values.put("oldRefundStatus", RefundStatus.STATUS_APPLY_REFUND);
        values.put("refundTotal", refundRecord.getRefundTotal());
        values.put("isDel", BaseEntity.NO);
        values.put("id",refundRecord.getId());
        sqlSentence.sqlSentence(" refundTotal = #{m.refundTotal},refundStatus=#{m.refundStatus} WHERE id = #{m.id} AND isDel=#{m.isDel} AND refundStatus = #{m.oldRefundStatus}",values);
        if(commonService.updateWhere(RefundRecordMapper.class,sqlSentence) != 1){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,退款单状态已改变!");
        }
 
        //获取订单信息
        OrdersTotal ordersTotal = commonService.selectOneByKeyBlob(OrdersTotalMapper.class,refundRecord.getOrderId());
        if(ordersTotal == null ){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到订单信息!");
        }
 
        //查询用户是否有账户信息,退款需要处理资金
        values.clear();
        values.put("userId",refundRecord.getUserId());
        sqlSentence.sqlSentence("SELECT * FROM user_money WHERE  userId=#{m.userId} AND isDel=0",values);
        UserMoney userMoney=commonService.selectOne(UserMoneyMapper.class,sqlSentence);
        if(userMoney==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该用户的资金信息");
        }
 
        //获取总退款方式
        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);
 
        //全程使用携带参数对象
        RefundCarryVo refundCarryVo = new RefundCarryVo();
        refundCarryVo.setRefundRecordMethodList(refundRecordMethodList);
 
        if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
            //充值订单需要把充值的储值金 拿回来   因为储值金需要开单来处理,所以不需要增加日志
            //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
            if(ordersTotal.getActualTotal().compareTo(BigDecimal.ZERO)!=0){
                //交给审批前操作
             /*   UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"审核通过退款:支付方式储值金额退回",operationId,refundRecord.getOrderId(),appIdCode,refundRecord.getId(),new BigDecimal(String.valueOf(ordersTotal.getTotal())).negate(), UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND, OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.NO);
                OrderLog orderLog = RefundToolUtil.setOrderLog(refundRecord, operationId, operationNme, "储值金客户退回金额:"+ordersTotal.getTotal(), 0, OrderLogConstants.LOG_TYPE_REFUND);
                commonService.insert(OrderLogMapper.class,orderLog);*/
                //活动规则退款处理
                // handActivityRule(commonService, operationId, operationNme, sqlSentence, map, refundRecord,ordersTotal,orderInfo);
            }
            //处理支付方式和退款方式关联
            refundCarryVo = rechargeRefundMothedHandle(refundCarryVo,refundRecord,commonService);
        }else{
            //子单退款项处理
            refundCarryVo = numberOfRefunds(refundCarryVo,operationId, refundRecord,ordersTotal,commonService);
        }
        //处理优惠券
        handCoupon(refundRecord,commonService);
        //处理总退款方式数据
        refundCarryVo = refundRecordMotnedHandle(refundCarryVo,operationId,operationNme,refundRecord,ordersTotal,commonService);
 
        //更改总订单退款状态
        values.clear();
        values.put("orderId",ordersTotal.getId());
        sqlSentence.sqlSentence("select * from order_item WHERE  orderId=#{m.orderId} and isDel=0",values);
        List<OrderItem> orderItemList=commonService.selectList(OrderItemMapper.class,sqlSentence);
 
        List<Integer> collect = orderItemList.stream().map(OrderItem::getRefundStatus).collect(Collectors.toList());
        if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
            ordersTotal.setReTotal(orderItemList.stream().map(OrderItem::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE) && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
            ordersTotal.setReTotal(orderItemList.stream().map(OrderItem::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
            ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
            ordersTotal.setStatus(OrderTotalConstants.STATUS_CANCEL);
            ordersTotal.setReTotal(orderItemList.stream().map(OrderItem::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
        }else {
            if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
                if(ordersTotal.getActualTotal().compareTo(refundRecord.getRefundTotal()) <= 0){
                    ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
                }else{
                    ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
                }
            }else{
                ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
            }
        }
        ordersTotal.setIsSyncOrder(BaseEntity.NO);
        ordersTotal.setEditTime(new Date());
        commonService.updateAll(OrdersTotalMapper.class,ordersTotal);
        return ordersTotal;
    }
 
    /**处理总退款方式数据*/
    public static RefundCarryVo refundRecordMotnedHandle(RefundCarryVo refundCarryVo,String operationId,String operationNme
            ,RefundRecord refundRecord,OrdersTotal ordersTotal,CommonService commonService){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map = new HashMap<>();
 
        //获取总退款方式
        List<RefundRecordMethod> refundRecordMethodList = refundCarryVo.getRefundRecordMethodList();
        //退款的支付方式记录数据
        List<RefundRecordConsumePay> refundConsumePayList = refundCarryVo.getRefundConsumePayList();
        //通过支付编号,装载分组好支付方式记录,key值:支付方式编号,value:支付方式记录集合
        Map<String,List<RefundRecordConsumePay>> refundConsumePayMap= new HashMap<>();
        List<RefundRecordConsumePay> refundRecordConsumePays;
        for(RefundRecordConsumePay refundRecordConsumePay:refundConsumePayList){
            refundRecordConsumePays = refundConsumePayMap.computeIfAbsent(refundRecordConsumePay.getNumberNo(),k->new ArrayList<>());
            refundRecordConsumePays.add(refundRecordConsumePay);
        }
 
        List<RefundRecordConsumePay> refundRecordConsumePayList = new ArrayList<>();
        RefundRecordConsumePay refundRecordConsumePay1;
 
        for(RefundRecordMethod refundRecordMethod:refundRecordMethodList){
            //判断是否已经被分配完
            if(refundRecordMethod.getpTotal().compareTo(BigDecimal.ZERO) > 0){
                throw new TipsException("退款错误[20]!");
            }
            refundRecordConsumePays = refundConsumePayMap.get(refundRecordMethod.getNumberNo());
            if(refundRecordConsumePays == null){
                throw new TipsException("退款错误[21]!");
            }
            for(RefundRecordConsumePay refundRecordConsumePay:refundRecordConsumePays){
                //更新支付记录退款信息
                map.clear();
                map.put("refundTotal",refundRecordConsumePay.getRefundTotal());
                map.put("id",refundRecordConsumePay.getConsumePayId());
                sqlSentence.sqlUpdate("refundTotal = refundTotal + #{m.refundTotal} WHERE id = #{m.id} AND actualTotal >= refundTotal + #{m.refundTotal}",map);
                if(commonService.updateWhere(ConsumePayMapper.class,sqlSentence) != 1){
                    throw new TipsException("退款金额错误[33]!");
                }
 
                //生成关联记录
                refundRecordConsumePay1 = insertRefundRecordConsumePay(refundRecordConsumePay.getRefundTotal(),null,null,refundRecord.getOrderId(),refundRecordConsumePay.getNumberNo()
                        ,refundRecordConsumePay.getName(),refundRecordConsumePay.getIsMoneyPay(),refundRecordConsumePay.getIsExecute(),refundRecordConsumePay.getConsumePayId(),refundRecordMethod.getId(),null,refundRecord.getId(),commonService);
                refundRecordConsumePayList.add(refundRecordConsumePay1);
            }
            //修改实际退款金额
            map.put("realRefundTotal",refundRecordMethod.getActualTotal());
            map.put("id",refundRecordMethod.getId());
            sqlSentence.sqlUpdate(" realRefundTotal = realRefundTotal + #{m.realRefundTotal} where id = #{m.id}",map);
            if(commonService.updateWhere(RefundRecordMethodMapper.class,sqlSentence) != 1){
                throw new TipsException("更新退款方式信息错误[001]");
            }
 
        }
        refundCarryVo.setRefundConsumePayList(refundRecordConsumePayList);
 
        //处理回退到账
        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.getRemarks(),"审核通过退款:支付方式储值金额退回",operationId,refundRecord.getOrderId(),refundRecord.getOperatorAppCode(),refundRecord.getId(),refundRecordMethod.getActualTotal(), UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND, OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.NO);
                    OrderLog orderLog = RefundToolUtil.setOrderLog(refundRecord, operationId, operationNme, refundRecordMethod.getName()+"退款金额:"+refundRecordMethod.getActualTotal(), 0, OrderLogConstants.LOG_TYPE_REFUND);
                    commonService.insert(OrderLogMapper.class,orderLog);
                }
            }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(),"审核通过退款:支付方式增值金退回",operationId,refundRecord.getOrderId(),refundRecord.getOperatorAppCode(),refundRecord.getId(),refundRecordMethod.getActualTotal(), UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND, OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                    OrderLog orderLog = RefundToolUtil.setOrderLog(refundRecord,operationId,operationNme,refundRecordMethod.getName(),0, OrderLogConstants.LOG_TYPE_REFUND);
                    commonService.insert(OrderLogMapper.class,orderLog);
                }
            }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(),"审核通过退款:支付方式积分退回",operationId,refundRecord.getOrderId(),refundRecord.getOperatorAppCode(),refundRecord.getId(),refundRecordMethod.getActualTotal(), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                    OrderLog orderLog = RefundToolUtil.setOrderLog(refundRecord,operationId,operationNme,refundRecordMethod.getName()+"退款金额:"+refundRecordMethod.getActualTotal(),0, OrderLogConstants.LOG_TYPE_REFUND);
                    commonService.insert(OrderLogMapper.class,orderLog);
                }
            }else {
                //现金支付
                if(refundRecordMethod.getActualTotal().compareTo(BigDecimal.ZERO)<1){
                    continue;
                }
                OrderLog orderLog = RefundToolUtil.setOrderLog(refundRecord,operationId,operationNme,refundRecordMethod.getName()+"退款金额:"+refundRecordMethod.getActualTotal(),0, OrderLogConstants.LOG_TYPE_REFUND);
                orderLog.setOrderId(ordersTotal.getId());
                commonService.insert(OrderLogMapper.class,orderLog);
 
                //现金支付需要创建创建退款单进行退款
                RefundNote refundNote = new RefundNote(refundRecordMethod.getActualTotal(), refundRecordMethod.getNumberNo(),refundRecordMethod.getName(),ordersTotal.getId(),refundRecord.getUserId());
                refundNote.setRefundRecordId(refundRecord.getId());
                commonService.insert(RefundNoteMapper.class,refundNote);
            }
        }
        return refundCarryVo;
    }
 
    /**充值订单退款方式的支付方式记录处理*/
    public static RefundCarryVo rechargeRefundMothedHandle(RefundCarryVo refundCarryVo,RefundRecord refundRecord,CommonService commonService){
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map = new HashMap<>();
 
        List<RefundRecordMethod> refundRecordMethodList = refundCarryVo.getRefundRecordMethodList();
 
        //装载分配好的支付方式记录的金额数据
        List<RefundRecordConsumePay> refundConsumePayList = new ArrayList<>();
        RefundRecordConsumePay refundRecordConsumePay;
 
        ///////获取订单支付方式记录
        map.put("orderId",refundRecord.getOrderId());
        sqlSentence.sqlSentence("SELECT *,ROUND(actualTotal-refundTotal,2) AS pTotal FROM consume_pay WHERE isDel = 0 AND orderId = #{m.orderId} ORDER BY pTotal ASC",map);
        List<ConsumePay> consumePayList = commonService.selectList(ConsumePayMapper.class,sqlSentence);
        //根据支付编号进行区分,key值:支付编号
        Map<String,List<ConsumePay>> consumePayMap = new HashMap<>();
        List<ConsumePay> consumePays;
        for(ConsumePay consumePay:consumePayList){
            consumePays = consumePayMap.computeIfAbsent(consumePay.getNumberNo(),k->new ArrayList<>());
            consumePays.add(consumePay);
        }
 
        ////引用对象
        //退款方式的金额
        BigDecimal mothedTotal;
        //分配支付方式金额
        BigDecimal mothedCutTotal;
        for(RefundRecordMethod refundRecordMethod:refundRecordMethodList){
            if(refundRecordMethod.getActualTotal().compareTo(BigDecimal.ZERO) < 1){
                continue;
            }
            mothedTotal = refundRecordMethod.getActualTotal();
            consumePays = consumePayMap.get(refundRecordMethod.getNumberNo());
            if(consumePays == null){
                throw new TipsException("没有找到该支付记录:"+refundRecordMethod.getName()+"["+refundRecordMethod.getNumberNo()+"]");
            }
            for(ConsumePay consumePay:consumePays){
                if(consumePay.getpTotal().compareTo(BigDecimal.ZERO) < 1){
                    continue;
                }
                //计算扣减金额
                if(consumePay.getpTotal().compareTo(mothedTotal) > 0){
                    mothedCutTotal = mothedTotal;
                }else{
                    mothedCutTotal = consumePay.getpTotal();
                }
                //减去已经分配的金额
                mothedTotal = mothedTotal.subtract(mothedCutTotal).setScale(2, RoundingMode.HALF_UP);
 
                refundRecordConsumePay = new RefundRecordConsumePay();
                refundRecordConsumePay.setNumberNo(consumePay.getNumberNo());
                refundRecordConsumePay.setName(consumePay.getName());
                refundRecordConsumePay.setRefundTotal(mothedCutTotal);
                refundRecordConsumePay.setConsumePayId(consumePay.getId());
                refundConsumePayList.add(refundRecordConsumePay);
 
                //已经分配完成,跳出循环
                if(mothedTotal.compareTo(BigDecimal.ZERO) < 1){
                    //跳出循环
                    break;
                }
            }
            //判断退款金额是否已经全部分配
            if(mothedTotal.compareTo(BigDecimal.ZERO) > 0){
                throw new TipsException("退款金额错误[426]!");
            }
            refundRecordMethod.setpTotal(BigDecimal.ZERO);
        }
        refundCarryVo.setRefundConsumePayList(refundConsumePayList);
        return refundCarryVo;
    }
 
    /**处理一级子退款方式数据
     * @param deductionTotalUser 用户项目被扣减的划扣金额,可空
     * @param refundRecord 退款记录总表
     * @param refundRecordItem 退款记录子表
     * @param refundCarryVo 总携带参数结构
     * @param commonService 映射
     * @return 总携带参数结构
     */
    public static RefundCarryVo refundRecordMotnedItemHandle(BigDecimal deductionTotalUser,RefundRecord refundRecord,RefundRecordItem refundRecordItem
            ,RefundCarryVo refundCarryVo,CommonService commonService){
 
        //没有退款方式,跳过当前处理,因为这里是处理退款方式金额的,如果没有退款金额,那么可以跳过该环节
        if(refundCarryVo.getRefundRecordMethodList().size() == 0){
            return refundCarryVo;
        }
        //支付方式占比
        BigDecimal payMothedPercentage;
        //计算退款方式的占比
        if(refundRecord.getRefundTotal().compareTo(BigDecimal.ZERO) > 0){
            payMothedPercentage = refundRecordItem.getRefundMoney().divide(refundRecord.getRefundTotal(),15,RoundingMode.HALF_UP);
        }else{
            payMothedPercentage = BigDecimal.ZERO;
        }
 
        //处理退款方式
        refundCarryVo = insertRefundItemMothed(refundRecordItem.getId(),refundRecordItem.getRefundMoney(),payMothedPercentage,OrderSourceConstans.TYPE_PROJECT
                ,refundRecordItem.getOrderItemId(),refundCarryVo,refundRecord,commonService);
 
        //更新退款子单
        updateRefundItem(refundCarryVo.getDeductionTotal(),refundCarryVo.getCashTotal(),deductionTotalUser
                ,refundRecordItem.getId(),commonService);
 
        return refundCarryVo;
    }
 
    /**更新退款一级子单的信息
     * @param deductionTotal 退款方式的划扣金额
     * @param cashTotal 退款方式的现金金额
     * @param deductionTotalUser 用户项目的划扣金额
     * @param refundItemId 退款记录一级子单标识
     * @param commonService 映射
     */
    public static void updateRefundItem(BigDecimal deductionTotal,BigDecimal cashTotal,BigDecimal deductionTotalUser
            ,String refundItemId,CommonService commonService){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        //更新退款子单的信息,更新现金和划扣金额保存
        values.put("deductionTotal",deductionTotal);
        values.put("deductionTotalUser",deductionTotalUser==null?BigDecimal.ZERO:deductionTotalUser);
        values.put("cashTotal",cashTotal);
        values.put("id",refundItemId);
        sqlSentence.sqlUpdate("deductionTotal = #{m.deductionTotal},deductionTotalUser = #{m.deductionTotalUser},cashTotal = #{m.cashTotal} WHERE id = #{m.id}",values);
        if(commonService.updateWhere(RefundRecordItemMapper.class,sqlSentence) != 1){
            throw new TipsException("更新退款子项信息失败!");
        }
    }
 
    /**处理二级子退款方式数据
     * @param deductionTotalUser 用户项目被扣减的划扣金额
     * @param refundRecord  退款记录总表
     * @param refundRecordItemSource 退款记录子表
     * @param refundCarryVo 总携带参数结构
     * @param commonService 映射
     * @return 总携带参数结构
     */
    public static RefundCarryVo refundRecordMotnedItemTwoHandle(BigDecimal deductionTotalUser,RefundRecord refundRecord,RefundRecordItemSource refundRecordItemSource
            ,RefundCarryVo refundCarryVo,CommonService commonService){
 
        //装载支付方式退款信息
        refundCarryVo.setRefundConsumePayList(new ArrayList<>());
        //没有退款方式,跳过当前处理
        if(refundCarryVo.getRefundRecordMethodList().size() == 0){
            return refundCarryVo;
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        //支付方式占比
        BigDecimal payMothedPercentage;
        //计算退款方式的占比
        if(refundRecord.getRefundTotal().compareTo(BigDecimal.ZERO) > 0){
            payMothedPercentage = refundRecordItemSource.getRefundMoney().divide(refundRecord.getRefundTotal(),15,RoundingMode.HALF_UP);
        }else{
            payMothedPercentage = BigDecimal.ZERO;
        }
 
        //处理退款方式
        refundCarryVo = insertRefundItemMothed(refundRecordItemSource.getId(),refundRecordItemSource.getRefundMoney(),payMothedPercentage,OrderSourceConstans.TYPE_RETAIL
                ,refundRecordItemSource.getOrderItemSonId(),refundCarryVo,refundRecord,commonService);
 
        values.put("deductionTotal",refundCarryVo.getDeductionTotal());
        values.put("deductionTotalUser",deductionTotalUser==null?BigDecimal.ZERO:deductionTotalUser);
        values.put("cashTotal",refundCarryVo.getCashTotal());
        values.put("id",refundRecordItemSource.getId());
        sqlSentence.sqlUpdate("deductionTotal = #{m.deductionTotal},deductionTotalUser = #{m.deductionTotalUser},cashTotal = #{m.cashTotal} WHERE id = #{m.id}",values);
        if(commonService.updateWhere(RefundRecordItemSourceMapper.class,sqlSentence) != 1){
            throw new TipsException("更新退款子项信息失败[94]!");
        }
 
        return refundCarryVo;
    }
 
    /**退款子单退款方式处理保存
     * @param refundItemId 退款子单标识
     * @param refundItemTotal 退款子单实际需要退款总金额
     * @param payMothedPercentage 支付方式占比
     * @param orderItemType 订单子单级别
     * @param orderItemId 订单子单标识
     * @param refundCarryVo 总结构对象
     * @param refundRecord 退款总记录
     * @param commonService 映射
     * @return 总结构对象
     */
    public static RefundCarryVo insertRefundItemMothed(String refundItemId,BigDecimal refundItemTotal,BigDecimal payMothedPercentage,String orderItemType
            ,String orderItemId,RefundCarryVo refundCarryVo,RefundRecord refundRecord,CommonService commonService){
 
        //总退款方式金额数据
        List<RefundRecordMethod> refundRecordMethodList = refundCarryVo.getRefundRecordMethodList();
        //进行升序排序,避免后面不够分配
        refundRecordMethodList = refundRecordMethodList.stream().sorted(Comparator.comparing(RefundRecordMethod::getpTotal)).collect(Collectors.toList());
 
        //获取子单的支付方式记录,计算可退款金额
        List<ConsumePayItem> consumePayItemList;
        if(OrderSourceConstans.TYPE_PROJECT.equals(orderItemType)){
            //一级订单
            consumePayItemList = getOrderItemOneConsumePay(orderItemId,commonService);
        }else{
            //二级订单
            consumePayItemList = getOrderItemTwoConsumePay(orderItemId,commonService);
        }
 
        ////存储支付方式编号的可退款金额,根据支付编号求和,后面的业务判断会用到,key值:支付编号,value:可退金额
        Map<String,BigDecimal> noMap = new HashMap<>();
        BigDecimal surplusTotal;
        ////存储支付方式编号的支付方式记录,根据支付编号整合,后面的业务会用到,key值:支付编号,value:支付记录集合
        Map<String,List<ConsumePayItem>> noPayItemMap = new HashMap<>();
        List<ConsumePayItem> noPayItemList;
 
        ////////填充支付方式记录的退款金额,计算剩余可退金额,支付方式记录的退款金额需要去查询计算获取
        //获取订单子单已经退款的退款方式金额,根据支付方式记录的标识求和返回
        List<RefundRecordConsumePay> refundRecordConsumePayList = getRefundRecordConsumePay(orderItemId,null,false,true,commonService);
        //转化成map,可以根据支付方式记录的标识直接获取到数据
        Map<String, RefundRecordConsumePay> refundRecordConsumePayMap = refundRecordConsumePayList.stream().collect(
                Collectors.toMap(RefundRecordConsumePay::getConsumePayId,(a) -> a));
        RefundRecordConsumePay refundRecordConsumePay;
        for(ConsumePayItem consumePayItem:consumePayItemList){
            refundRecordConsumePay = refundRecordConsumePayMap.get(consumePayItem.getConsumePayId());
            if(refundRecordConsumePay != null){
                //已退款金额
                consumePayItem.setRefundTotal(refundRecordConsumePay.getRefundTotal());
                //可退款金额
                consumePayItem.setpTotal(consumePayItem.getpTotal().subtract(refundRecordConsumePay.getRefundTotal()).setScale(2,RoundingMode.HALF_UP));
            }
            //计算每个支付编码可退款金额
            surplusTotal = noMap.computeIfAbsent(consumePayItem.getNumberNo(),k->BigDecimal.ZERO);
            surplusTotal = surplusTotal.add(consumePayItem.getpTotal()).setScale(2,RoundingMode.HALF_UP);
            noMap.put(consumePayItem.getNumberNo(),surplusTotal);
 
            //支付编码集合整合
            noPayItemList = noPayItemMap.computeIfAbsent(consumePayItem.getNumberNo(),k->new ArrayList<>());
            noPayItemList.add(consumePayItem);
        }
 
        List<RefundRecordConsumePay> refundConsumePayList = new ArrayList<>();
 
        ////引用对象
        RefundRecordItemMethod refundRecordItemMethod;
        RefundRecordMethod refundRecordMethod;
        //需要退的退款编号金额
        BigDecimal mothedTotal;
        //支付编号分配的退款金额
        BigDecimal mothedCutTotal;
        //分配的划扣金额总和
        BigDecimal deductionTotal = BigDecimal.ZERO;
        //分配的现金金额总和
        BigDecimal cashTotal = BigDecimal.ZERO;
 
        ////退款方式金额分配
        for(int i = 0;i <refundRecordMethodList.size();i++){
            refundRecordMethod = refundRecordMethodList.get(i);
 
            ////子项退款方式填充
            refundRecordItemMethod = new RefundRecordItemMethod();
            refundRecordItemMethod.setNumberNo(refundRecordMethod.getNumberNo());
            refundRecordItemMethod.setName(refundRecordMethod.getName());
            //支付方式
            refundRecordItemMethod.setPaymentMethodId(refundRecordMethod.getPaymentMethodId());
            refundRecordItemMethod.setIsMoneyPay(refundRecordMethod.getIsMoneyPay());
            refundRecordItemMethod.setIsExecute(refundRecordMethod.getIsExecute());
            refundRecordItemMethod.setIsPay(refundRecordMethod.getIsPay());
            //退款方式
            refundRecordItemMethod.setRefundNumberNo(refundRecordMethod.getRefundNumberNo());
            refundRecordItemMethod.setRefundName(refundRecordMethod.getRefundName());
            refundRecordItemMethod.setRefundMethodId(refundRecordMethod.getRefundMethodId());
 
            //计算退款方式的金额
            if(i == refundRecordMethodList.size()-1){
                ////最后一个
                refundRecordItemMethod.setActualTotal(refundItemTotal);
            }else {
                ////不是最后一个
                refundRecordItemMethod.setActualTotal(refundRecordMethod.getActualTotal().multiply(payMothedPercentage).setScale(2,RoundingMode.UP));
            }
            //判断与剩余的未分配退款方式金额
            if (refundRecordItemMethod.getActualTotal().compareTo(refundRecordMethod.getpTotal()) > 0){
                refundRecordItemMethod.setActualTotal(refundRecordMethod.getpTotal());
            }
            //判断与剩下的未分配金额校验
            if(refundRecordItemMethod.getActualTotal().compareTo(refundItemTotal) > 0){
                refundRecordItemMethod.setActualTotal(refundItemTotal);
            }
            //可支付方式可退款金额
            surplusTotal = noMap.computeIfAbsent(refundRecordItemMethod.getNumberNo(),k-> BigDecimal.ZERO);
            if(refundRecordItemMethod.getActualTotal().compareTo(surplusTotal) > 0){
                refundRecordItemMethod.setActualTotal(surplusTotal);
            }
 
            refundRecordItemMethod.setRealRefundTotal(refundRecordItemMethod.getActualTotal());
            refundRecordItemMethod.setCommonType(orderItemType);
            refundRecordItemMethod.setCommonId(orderItemId);
            refundRecordItemMethod.setOrderId(refundRecordMethod.getOrderId());
            refundRecordItemMethod.setRefundRecordItemId(refundItemId);
            refundRecordItemMethod.setRefundRecordId(refundRecord.getId());
            commonService.insert(RefundRecordItemMethodMapper.class,refundRecordItemMethod);
 
            //减去已经分配的退款方式金额
            refundRecordMethod.setpTotal(refundRecordMethod.getpTotal().subtract(refundRecordItemMethod.getActualTotal()).setScale(2,RoundingMode.HALF_UP));
            //减去已经分配的退款金额
            refundItemTotal = refundItemTotal.subtract(refundRecordItemMethod.getActualTotal()).setScale(2,RoundingMode.HALF_UP);
            //减去已经分配的可退款金额
            surplusTotal = surplusTotal.subtract(refundRecordItemMethod.getActualTotal()).setScale(2,RoundingMode.HALF_UP);
            noMap.put(refundRecordItemMethod.getNumberNo(),surplusTotal);
 
            ///////生成关联支付方式记录和退款方式关联
            //根据支付编号获取支付方式记录
            noPayItemList = noPayItemMap.computeIfAbsent(refundRecordItemMethod.getNumberNo(),k->new ArrayList<>());
            //进行升序排序,避免后面不够分配
            noPayItemList = noPayItemList.stream().sorted(Comparator.comparing(ConsumePayItem::getpTotal)).collect(Collectors.toList());
            mothedTotal = refundRecordItemMethod.getActualTotal();
            for(ConsumePayItem consumePayItem:noPayItemList){
                if(consumePayItem.getpTotal().compareTo(BigDecimal.ZERO) < 1){
                    continue;
                }
                //计算扣减金额
                if(consumePayItem.getpTotal().compareTo(mothedTotal) > 0){
                    mothedCutTotal = mothedTotal;
                }else{
                    mothedCutTotal = consumePayItem.getpTotal();
                }
 
                //划扣金额
                if(consumePayItem.getIsMoneyPay().equals(ConsumePayItem.YES)){
                    cashTotal = cashTotal.add(mothedCutTotal).setScale(2,RoundingMode.HALF_UP);
                }
                //现金金额
                if(consumePayItem.getIsExecute().equals(ConsumePayItem.YES)){
                    deductionTotal = deductionTotal.add(mothedCutTotal).setScale(2,RoundingMode.HALF_UP);
                }
 
                //生成关联记录
                refundRecordConsumePay = insertRefundRecordConsumePay(mothedCutTotal,refundRecordItemMethod.getCommonType(),refundRecordItemMethod.getCommonId(),refundRecord.getOrderId(),consumePayItem.getNumberNo()
                        ,consumePayItem.getName(),consumePayItem.getIsMoneyPay(),consumePayItem.getIsExecute(),consumePayItem.getConsumePayId(),refundRecordItemMethod.getId(),refundItemId,refundRecord.getId(),commonService);
                refundConsumePayList.add(refundRecordConsumePay);
 
                //支付方式记录减掉已经分配退款方式金额
                consumePayItem.setpTotal(consumePayItem.getpTotal().subtract(mothedCutTotal).setScale(2,RoundingMode.HALF_UP));
                //减掉已经分配退款方式金额
                mothedTotal = mothedTotal.subtract(mothedCutTotal).setScale(2, RoundingMode.HALF_UP);
                //分配完成,跳出循环
                if(mothedTotal.compareTo(BigDecimal.ZERO) < 1){
                    //跳出循环
                    break;
                }
            }
        }
        //判断是否已经分配完
        if(refundItemTotal.compareTo(BigDecimal.ZERO) > 0){
            throw new TipsException("分配退款金额错误["+orderItemType+"]");
        }
 
        refundCarryVo.setDeductionTotal(deductionTotal);
        refundCarryVo.setCashTotal(cashTotal);
        refundCarryVo.setRefundConsumePayList(refundConsumePayList);
 
        return refundCarryVo;
    }
 
 
    /**
     * 退款-处理优惠券
     * @param refundRecord 退款总数据
     * @param commonService 映射
     */
    public static void handCoupon(RefundRecord refundRecord,CommonService commonService) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> map = new HashMap<>();
 
        //回去回退优惠券
        map.put("refundRecordId",refundRecord.getId());
        sqlSentence.sqlSentence("select * from refund_record_coupon where refundRecordId=#{m.refundRecordId} and isDel=0 ",map);
        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,"订单优惠卷标识不正确");
            }
 
            //变更订单优惠券记录状态
            map.clear();
            map.put("status", BaseEntity.YES);
            map.put("id", couponOrderDiscountLog.getId());
            sqlSentence.sqlSentence("status = #{m.status} WHERE id = #{m.id}",map);
            if(commonService.updateWhere(CouponOrderDiscountLogMapper.class,sqlSentence) != 1){
                throw new TipsException("优惠券回退失败!");
            }
 
            //领建优惠券跳过回退
            if(HIS_COUPON_CODE.equals(couponOrderDiscountLog.getCouponNumberId())){
                continue;
            }
 
            //优惠券状态变化
            map.put("isUse", BaseEntity.NO);
            map.put("useTime", null);
            map.put("useType", CouponNumber.USE_TYPE_UNKNOW);
            map.put("id", couponOrderDiscountLog.getCouponNumberId());
            sqlSentence.sqlSentence("  isUse=#{m.isUse},useTime=#{m.useTime},useType=#{m.useType},isUse=#{m.isUse} WHERE id = #{m.id}  ",map);
            if(commonService.updateWhere(CouponNumberMapper.class,sqlSentence) != 1){
                throw new TipsException("优惠券回退失败[67]!");
            }
        }
    }
 
    /**
     * 退款-处理活动规则增值金和积分
     */
    private static void handActivityRule(CommonService commonService, String operationId, String operationNme, SqlSentence sqlSentence,
                                         Map<String, Object> map, RefundRecord refundRecord, OrdersTotal ordersTotal, OrderInfo orderInfo) {
        if(orderInfo!=null && StringUtils.noNull(orderInfo.getActivityId())){
            ActivityRule activityRule=commonService.selectOneByKeyBlob(ActivityRuleMapper.class,orderInfo.getActivityId());
            if(activityRule!=null){
                map.put("activityRuleId",activityRule.getId());
                map.put("type", ActivityAction.TYPE_INTEGRAL);
                map.put("type1",ActivityAction.TYPE_VALUEADDEDFUND);
                map.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",map);
                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()).negate().compareTo(BigDecimal.ZERO)!=0){
                                UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"退款扣减活动规则赠送积分",operationId,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(ActivityAction.TYPE_VALUEADDEDFUND.equals(activityAction.getType())){
                            //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                            if(new BigDecimal(activityAction.getWorth()).negate().compareTo(BigDecimal.ZERO)!=0){
                                UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"退款扣减活动规则赠送增值金",operationId,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(ActivityAction.TYPE_COUPON.equals(activityAction.getType())){
                            map.put("oldValidState",BaseEntity.YES);
                            map.put("newValidState",BaseEntity.NO);
                            map.put("couponId",activityAction.getCrmCouponId());
                            map.put("commonId",ordersTotal.getId());
                            sqlSentence.sqlSentence(" validState=#{m.newValidState} where couponId=#{m.couponId} and commonId=#{m.commonId} and validState=#{m.oldValidState} ",map);
                            commonService.updateWhere(CouponNumberMapper.class,sqlSentence);
                        }
                    }
                }
            }
        }
 
    }
 
    /**退款-处理普通订单信息(比如:项目、促销、卡项)
     * @param refundCarryVo 全局携带参数结构
     * @param operationId 操作人标识
     * @param refundRecord 退款总标识
     * @param ordersTotal 订单
     * @param commonService 映射
     * @return 全局携带参数结构
     */
    public static RefundCarryVo numberOfRefunds(RefundCarryVo refundCarryVo,String operationId, RefundRecord refundRecord,OrdersTotal ordersTotal,CommonService commonService) {
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> map = new HashMap<>();
 
        //获取退款子单
        map.put("refundRecordId",refundRecord.getId());
        sqlSentence.sqlSentence("SELECT * FROM refund_record_item WHERE isDel = 0 AND refundRecordId = #{m.refundRecordId}",map);
        List<RefundRecordItem> refundRecordItems =commonService.selectList(RefundRecordItemMapper.class,sqlSentence);
        if(refundRecordItems == null || refundRecordItems.size() == 0){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到退款子订单信息");
        }
 
        //根据支付记录总表的标识来整合已退的金额,key值:支付记录总表标识,value:金额数据
        Map<String,RefundRecordConsumePay> refundRecordConsumePayMap = new HashMap<>();
        RefundRecordConsumePay refundRecordConsumePay;
 
        for (RefundRecordItem refundRecordItem: refundRecordItems) {
            //初始化总结构携带参数
            refundCarryVo.setRefundConsumePayList(new ArrayList<>());
            refundCarryVo.setDeductionTotal(BigDecimal.ZERO);
            refundCarryVo.setCashTotal(BigDecimal.ZERO);
            refundCarryVo.setDeductionTotalUser(BigDecimal.ZERO);
            //商品类型判断
            switch (refundRecordItem.getType()){
                case OrderItemConstants.TYPE_RETAIL:
                    refundCarryVo = handRefundRerail(refundRecord,refundRecordItem,refundCarryVo,commonService);
                    break;
                case OrderItemConstants.TYPE_DRUG:
                    refundCarryVo = handRefundRerail(refundRecord,refundRecordItem,refundCarryVo,commonService);
                    break;
                case OrderItemConstants.TYPE_PROJECT:
                    refundCarryVo = handRefundNoExecution(refundRecord,refundRecordItem,refundCarryVo,commonService);
                    break;
                case OrderItemConstants.TYPE_PROMOTION:
                    refundCarryVo = handRefundPromotion(operationId, refundRecord, ordersTotal,refundRecordItem,refundCarryVo,commonService);
                    break;
                case OrderItemConstants.TYPE_CARD:
                    refundCarryVo = handRefundCard(refundRecord,refundRecordItem,refundCarryVo,commonService);
                    break;
                case OrderItemConstants.CARD_BAG:
                    refundCarryVo = handRefundPromotion(operationId, refundRecord, ordersTotal,refundRecordItem,refundCarryVo,commonService);
                    break;
                default:break;
            }
 
            //遍历叠加支付方式记录的退款金额
            for(RefundRecordConsumePay re:refundCarryVo.getRefundConsumePayList()){
                refundRecordConsumePay = refundRecordConsumePayMap.computeIfAbsent(re.getConsumePayId(),k->new RefundRecordConsumePay(BigDecimal.ZERO,re.getNumberNo(),re.getName(),re.getIsMoneyPay(),re.getIsExecute(),re.getConsumePayId()));
                refundRecordConsumePay.setRefundTotal(refundRecordConsumePay.getRefundTotal().add(re.getRefundTotal()));
            }
        }
 
        //转载返回支付方式记录的退款金额
        List<RefundRecordConsumePay> refundRecordConsumePayList = new ArrayList<>();
        for (Map.Entry<String, RefundRecordConsumePay> entry : refundRecordConsumePayMap.entrySet()) {
            refundRecordConsumePayList.add(entry.getValue());
        }
 
        //校验金额是不是已经分配完
        for(RefundRecordMethod refundRecordMethod:refundCarryVo.getRefundRecordMethodList()){
            if(refundRecordMethod.getpTotal().compareTo(BigDecimal.ZERO) > 0){
                throw new TipsException("退款金额分配错误!");
            }
        }
 
        refundCarryVo.setRefundConsumePayList(refundRecordConsumePayList);
        return refundCarryVo;
    }
 
    /**
     * 退款一级是商品
     * @param refundRecord 退款总信息
     * @param refundRecordItem 退款子单
     * @param commonService 映射
     */
    private static RefundCarryVo handRefundRerail(RefundRecord refundRecord, RefundRecordItem refundRecordItem
            , RefundCarryVo refundCarryVo, CommonService commonService) {
 
        //判断操作完了去修改子订单状态
        OrderItem orderItem=commonService.selectOneByKey(OrderItemMapper.class,refundRecordItem.getOrderItemId());
        if (orderItem==null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"未找到子订单信息");
        }
        //剩余可退款数量
        Integer surplusNum = orderItem.getBuyNum()-orderItem.getHasReNum();
        if(refundRecordItem.getRefundNum() > surplusNum){
            throw new TipsException("退款数量不能大于可退款数量!");
        }
 
        //变更退款子项信息
        int refundStatus;
        if (surplusNum.equals(refundRecordItem.getRefundNum())){
            refundStatus = OrderTotalConstants.STATUS_REFUND_FINSH;
        }else{
            refundStatus = OrderTotalConstants.STATUS_REFUND_PART;
        }
 
        //更新子订单信息
        updateOrderItemOne(orderItem,refundStatus,refundRecordItem.getRefundMoney(),refundRecordItem.getRefundNum(),commonService);
 
        //退款方式处理
        return refundRecordMotnedItemHandle(null,refundRecord,refundRecordItem,refundCarryVo,commonService);
    }
 
    /**
     * 退款-处理未执行划扣   项目类型
     * @param refundRecord 退款总记录
     * @param refundRecordItem 退款一级子记录
     */
    private static RefundCarryVo handRefundNoExecution(RefundRecord refundRecord, RefundRecordItem refundRecordItem
            ,RefundCarryVo refundCarryVo,CommonService commonService) {
 
        //找到子单
        OrderItem orderItem=commonService.selectOneByKey(OrderItemMapper.class,refundRecordItem.getOrderItemId());
        if (orderItem==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到子订单信息");
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> map = new HashMap<>();
 
        //找到用户项目
        map.put("commonId",refundRecordItem.getOrderItemId());
        sqlSentence.sqlSentence("select * from user_project_item where isDel = 0 and commonId = #{m.commonId} and isTransfer = 0",map);
        UserProjectItem userProjectItem =commonService.selectOne(UserProjectItemMapper.class,sqlSentence);
        if (userProjectItem == null) {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到用户子项项目信息");
        }
 
        if(userProjectItem.getNotUsedNum() < refundRecordItem.getRefundNum()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款次数大于可退次数!");
        }
 
        //用户项目操作
        UserProjectDeductionVo  userProjectDeductionVo = UserProjectTool.userProjectDeduction(userProjectItem,UserProjectUsedCon.USED_METHOD_ORDER_REFUND,UserProjectUsedCon.USED_TYPE_DEDUCTION,null
                ,refundRecordItem.getId(),refundRecordItem.getRefundNum(),refundRecord.getOperatorAppId(),refundRecord.getOperatorAppName(),refundRecord.getRefundShopId(),refundRecord.getRefundShopName(),"员工备注:"+refundRecord.getRemarks()+"|用户备注:"+refundRecord.getRefundReason(),commonService);
 
        refundCarryVo.setDeductionTotalUser(userProjectDeductionVo.getDeductionTotal());
 
        //计算子单是否还有剩余的可扣疗程数
        int surplusNum = orderItem.getUsedTotal()-orderItem.getHasReNum();
        if(refundRecordItem.getRefundNum() > surplusNum){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款次数大于子单可退次数[54]!");
        }
 
        int refundStatus;
        if(refundRecordItem.getRefundNum() == surplusNum){
            refundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
        }else{
            refundStatus=OrderTotalConstants.STATUS_REFUND_PART;
        }
 
        //更新子订单信息
        updateOrderItemOne(orderItem,refundStatus,refundRecordItem.getRefundMoney(),refundRecordItem.getRefundNum(),commonService);
 
        //退款方式处理
        return refundRecordMotnedItemHandle(userProjectDeductionVo.getDeductionTotal(),refundRecord,refundRecordItem,refundCarryVo,commonService);
    }
 
    /**退款-处理卡项
     * @param refundRecord 退款总记录
     * @param refundRecordItem 退款一级记录
     * @param refundCarryVo 全局携带参数结构
     * @param commonService 映射
     * @return 全局携带参数结构
     */
    public static RefundCarryVo handRefundCard(RefundRecord refundRecord, RefundRecordItem refundRecordItem,RefundCarryVo refundCarryVo,CommonService commonService) {
 
        //判断操作完了去修改子订单状态
        OrderItem orderItem=commonService.selectOneByKey(OrderItemMapper.class,refundRecordItem.getOrderItemId());
        if (orderItem==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到子订单信息");
        }
        Integer surplusNum = orderItem.getBuyNum() - orderItem.getHasReNum();
        if(refundRecordItem.getRefundNum() > surplusNum){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款作废卡包提示:没有找到对应的卡包可退[020]");
        }
 
        //找到可退款卡包
        List<UserCard> userCardList = PartialRefundUtil.getRefundCard(orderItem.getId(),commonService);
        if(refundRecordItem.getRefundNum() > userCardList.size()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款作废卡包提示:没有找到对应的卡包可退[021]");
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> map = new HashMap<>();
 
        //变更卡项状态
        UserCard userCard;
        RefundRecordCard refundRecordCard;
        for (int i = 0; i < refundRecordItem.getRefundNum(); i++) {
            userCard= userCardList.get(i);
            map.put("id",userCard.getId());
            map.put("effectiveStatus", UserProjectConstants.EFF_STATUS_CANCEL);
            sqlSentence.sqlSentence(" effectiveStatus=#{m.effectiveStatus} WHERE id = #{m.id}",map);
            commonService.updateWhere(UserCardMapper.class,sqlSentence);
 
            //生成退款关联
            refundRecordCard = new RefundRecordCard();
            refundRecordCard.setUserCardId(userCard.getId());
            refundRecordCard.setRefundRecordId(refundRecord.getId());
            refundRecordCard.setRefundRecordItemId(refundRecordItem.getId());
            commonService.insert(RefundRecordCardMapper.class,refundRecordCard);
        }
 
        int refundStatus;
        if (surplusNum.equals(refundRecordItem.getRefundNum())){
            refundStatus =  OrderTotalConstants.STATUS_REFUND_FINSH;
        }else {
            refundStatus =  OrderTotalConstants.STATUS_REFUND_PART;
 
        }
        //更新子订单信息
        updateOrderItemOne(orderItem,refundStatus,refundRecordItem.getRefundMoney(),refundRecordItem.getRefundNum(),commonService);
 
        //退款方式处理
        refundCarryVo = refundRecordMotnedItemHandle(null,refundRecord,refundRecordItem,refundCarryVo,commonService);
        return refundCarryVo;
    }
 
    /**退款-处理卡包
     */
    public static void handCardBag(String operationId,RefundRecord refundRecord, OrdersTotal ordersTotal
            ,RefundRecordItem refundRecordItem,RefundCarryVo refundCarryVo,CommonService commonService) {
 
        //查看订单信息
        OrderItem orderItem=commonService.selectOneByKey(OrderItemMapper.class,refundRecordItem.getOrderItemId());
        if(orderItem == null ){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到子订单信息!");
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> map = new HashMap<>();
 
        map.put("refundRecordItemId",refundRecordItem.getId());
        sqlSentence.sqlSentence("select * from refund_record_item_source where refundRecordItemId =#{m.refundRecordItemId}",map);
        List<RefundRecordItemSource> sons = commonService.selectList(RefundRecordItemSourceMapper.class, sqlSentence);
        if(sons.size() == 0 ){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到子订单信息[015]!");
        }
 
        for (RefundRecordItemSource son : sons) {
            refundCarryVo.setRefundConsumePayList(new ArrayList<>());
            refundCarryVo.setDeductionTotal(BigDecimal.ZERO);
            refundCarryVo.setCashTotal(BigDecimal.ZERO);
            switch (GroupTypeEnum.getCode(son.getType())){
                case PROJECT:
                    //handRefundNoSonExecution(refundRecord,son,refundCarryVo,commonService);
                    break;
                case RETAIL:
                    //handRefundSonRerail(refundRecord,son,refundCarryVo,commonService );
                    //deleteUserCardUsed(sqlSentence,map,ordersTotal,commonService,son,orderItem);
                    break;
                case INCREMENT:
                    //增值金
                    //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                    if(son.getRealRefundTotal().negate().compareTo(BigDecimal.ZERO)!=0){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"审核通过退款:促销赠送增值金扣减",operationId,refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),son.getRealRefundTotal().negate(), 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(),"审核通过退款:促销赠送储值金额扣减",operationId,refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),son.getRealRefundTotal().negate(), 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(),"审核通过退款:促销赠送积分扣减",operationId,refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),son.getRealRefundTotal().negate(), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                    }
                    break;
            }
        }
 
        //更改二级子订单退款状态
        map.put("orderItemId",orderItem.getId());
        sqlSentence.setSqlSentence("select * from order_item_source WHERE  orderItemId=#{m.orderItemId} and isDel=0");
        List<OrderItemSon> orderItemSonList=commonService.selectList(OrderItemSonMapper.class,sqlSentence);
 
        List<Integer> collect = orderItemSonList.stream().map(OrderItemSon::getRefundStatus).collect(Collectors.toList());
        if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
            orderItem.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
            orderItem.setReTotal(orderItemSonList.stream().map(OrderItemSon::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE) && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
            orderItem.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
            orderItem.setReTotal(orderItemSonList.stream().map(OrderItemSon::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
        }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
            orderItem.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
        }else  if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
            orderItem.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
            orderItem.setReTotal(orderItemSonList.stream().map(OrderItemSon::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
            orderItem.setHasReNum(orderItem.getBuyNum());
        }else {
            orderItem.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
        }
 
        commonService.updateAll(OrderItemMapper.class,orderItem);
    }
 
    /**退款需要删除用户卡包使用记录
     * @param cardItemInfoId 卡包的卡项子项
     * @param sourceId 卡包使用记录来源标识
     * @param orderId 卡包使用记录来源总表标识
     * @param refundNum 退款数量
     * @param commonService 映射
     */
    public static void deleteUserCardUsed(String cardItemInfoId,String sourceId,String orderId,Integer refundNum
            ,CommonService commonService){
 
        //查出用户,commonId:卡项的组合项标识
        CardItemInfo cardItemInfo=commonService.selectOneByKey(CardItemInfoMapper.class,cardItemInfoId);
        if(cardItemInfo ==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该卡包的组合项");
        }
 
        //获取权益类型
        CardEquity cardEquity = commonService.selectOneByKey(CardEquityMapper.class,cardItemInfo.getCardEquityId());
        if(cardEquity == null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该卡包的组合项权益类型");
        }
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map = new HashMap<>();
 
        //获取使用记录
        map.put("cardItemInfoId",cardItemInfoId);
        map.put("sourceId",sourceId);
        sqlSentence.sqlSentence(" SELECT * FROM user_card_used WHERE isDel = 0" +
                " 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);
            sqlSentence.sqlSentence(" SELECT * FROM user_card_used WHERE isDel = 0" +
                    " AND cardItemInfoId = #{m.cardItemInfoId} AND sourceId IS NULL",map);
            userCardUsedList = commonService.selectList(UserCardUsedMapper.class,sqlSentence);
        }
 
        //计算退回的卡次
        int returnNum;
        //因为有些是算次数抵扣的,所以要算
        if(CardEquity.EQUITY_TYPE_TIME_CARD.equals(cardEquity.getEquityType())){
            //次卡:总次数=开单的总次数*每次划扣的次数
            returnNum= refundNum * cardItemInfo.getEveryDrawNum();
        }else if(CardEquity.EQUITY_TYPE_N_M.equals(cardEquity.getEquityType())){
            returnNum = refundNum;
        }else{
            returnNum = refundNum;
        }
 
        if(returnNum > userCardUsedList.size()){
            throw new TipsException("卡包可退数量错误!");
        }
 
        //已经操作数量
        int opNum = 0;
        StringBuilder sql;
        for(UserCardUsed userCardUsed:userCardUsedList){
            sql = new StringBuilder();
            sql.append("isDel = 1");
            map.clear();
            map.put("id",userCardUsed.getId());
            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 isDel = 0");
            sqlSentence.sqlUpdate(sql.toString(),map);
            opNum = opNum+commonService.updateWhere(UserCardUsedMapper.class,sqlSentence);
        }
        if(opNum != returnNum){
            throw new TipsException("卡包回退数量错误!");
        }
 
    }
 
    /**退款-处理促销
     * @param operationId 操作人标识
     * @param refundRecord 退款总记录
     * @param ordersTotal 订单
     * @param refundRecordItem 退款一级记录
     * @param refundCarryVo 全局携带参数结构
     * @param commonService 映射
     * @return 全局携带参数结构
     */
    private static RefundCarryVo handRefundPromotion(String operationId, RefundRecord refundRecord, OrdersTotal ordersTotal
            , RefundRecordItem refundRecordItem,RefundCarryVo refundCarryVo,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);
 
        //根据支付记录总表的标识来整合已退的金额,key值:支付记录总表标识,value:金额数据
        Map<String,RefundRecordConsumePay> refundRecordConsumePayMap = new HashMap<>();
        RefundRecordConsumePay refundRecordConsumePay;
        //计算本次退款方式的划扣金额
        BigDecimal deductionTotal = BigDecimal.ZERO;
        //计算本次退款方式的现金金额
        BigDecimal cashTotal = BigDecimal.ZERO;
        //分配的用户项目划扣金额
        BigDecimal deductionTotalUser = BigDecimal.ZERO;
 
        for (RefundRecordItemSource son : sons) {
            //初始化总结构携带参数
            refundCarryVo.setRefundConsumePayList(new ArrayList<>());
            refundCarryVo.setDeductionTotal(BigDecimal.ZERO);
            refundCarryVo.setCashTotal(BigDecimal.ZERO);
            refundCarryVo.setDeductionTotalUser(BigDecimal.ZERO);
            switch (GroupTypeEnum.getCode(son.getType())){
                case PROJECT:
                    refundCarryVo = handRefundNoSonExecution(refundRecord,refundRecordItem,son,refundCarryVo,commonService);
                    break;
                case RETAIL:
                    refundCarryVo = handRefundSonRerail(refundRecord,refundRecordItem,son,refundCarryVo,commonService);
                    break;
                case INCREMENT:
                    //增值金
                    //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
                    if(son.getRealRefundTotal().negate().compareTo(BigDecimal.ZERO)!=0){
                        UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),"审核通过退款:促销赠送增值金扣减",operationId,refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),son.getRealRefundTotal().negate(), 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(),"审核通过退款:促销赠送储值金额扣减",operationId,refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),son.getRealRefundTotal().negate(), 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(),"审核通过退款:促销赠送积分扣减",operationId,refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),son.getRealRefundTotal().negate(), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
                    }
                    break;
            }
            deductionTotal = deductionTotal.add(refundCarryVo.getDeductionTotal());
            cashTotal = cashTotal.add(refundCarryVo.getCashTotal());
            deductionTotalUser = deductionTotalUser.add(refundCarryVo.getDeductionTotalUser());
            //遍历叠加支付方式记录的退款金额
            for(RefundRecordConsumePay re:refundCarryVo.getRefundConsumePayList()){
                refundRecordConsumePay = refundRecordConsumePayMap.computeIfAbsent(re.getConsumePayId(),k->new RefundRecordConsumePay(BigDecimal.ZERO,re.getNumberNo(),re.getName(),re.getIsMoneyPay(),re.getIsExecute(),re.getConsumePayId()));
                refundRecordConsumePay.setRefundTotal(refundRecordConsumePay.getRefundTotal().add(re.getRefundTotal()));
            }
        }
 
        //转载返回支付方式记录的退款金额
        List<RefundRecordConsumePay> refundRecordConsumePayList = new ArrayList<>();
        for (Map.Entry<String, RefundRecordConsumePay> entry : refundRecordConsumePayMap.entrySet()) {
            refundRecordConsumePayList.add(entry.getValue());
        }
        refundCarryVo.setCashTotal(cashTotal);
        refundCarryVo.setDeductionTotal(deductionTotal);
        refundCarryVo.setDeductionTotalUser(deductionTotalUser);
        refundCarryVo.setRefundConsumePayList(refundRecordConsumePayList);
 
        //更新退款子单
        updateRefundItem(refundCarryVo.getDeductionTotal(),refundCarryVo.getCashTotal(),refundCarryVo.getDeductionTotalUser()
                ,refundRecordItem.getId(),commonService);
 
        //获取其子项
        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;
        }
 
        //更新子订单信息
        updateOrderItemOne(orderItem,refundStatus,refundRecordItem.getRefundMoney(),refundNum,commonService);
 
        return refundCarryVo;
    }
 
    /**退款-处理二级子订单未执行划扣   项目类型
     * @param refundRecord 退款总记录
     * @param refundRecordItem 退款一级子单
     * @param refundRecordItemSource  退款二级子单
     * @param refundCarryVo 全局携带参数接口
     * @param commonService 映射
     */
    private static RefundCarryVo handRefundNoSonExecution(RefundRecord refundRecord,RefundRecordItem refundRecordItem, RefundRecordItemSource refundRecordItemSource
            ,RefundCarryVo refundCarryVo,CommonService commonService) {
 
        //判断操作完了去修改子订单状态
        OrderItemSon orderItemSon = commonService.selectOneByKey(OrderItemSonMapper.class,refundRecordItemSource.getOrderItemSonId());
        if (orderItemSon==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到二级子订单信息[02]");
        }
 
        UserProjectItem userProjectItem = getUserProject(orderItemSon.getId(),commonService);
        if(userProjectItem == null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"用户项目获取失败[06]!");
        }
        if(userProjectItem.getNotUsedNum()<refundRecordItemSource.getRefundNum()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款次数大于可退次数[83]!");
        }
 
        //计算子单是否还有剩余的可扣疗程数
        int surplusNum = orderItemSon.getUsedTotal() - orderItemSon.getHasReNum();
        if(refundRecordItemSource.getRefundNum() > surplusNum){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款次数大于可退次数[56]!");
        }
 
        //处理用户项目,减去用户项目数量
        UserProjectDeductionVo userProjectDeductionVo= UserProjectTool.userProjectDeduction(userProjectItem,UserProjectUsedCon.USED_METHOD_ORDER_REFUND,UserProjectUsedCon.USED_TYPE_DEDUCTION,null
                ,refundRecordItemSource.getId(),refundRecordItemSource.getRefundNum(),refundRecord.getOperatorAppId(),refundRecord.getOperatorAppName(),refundRecord.getRefundShopId(),refundRecord.getRefundShopName(),"员工备注:"+refundRecord.getRemarks()+"|用户备注:"+refundRecord.getRefundReason(),commonService);
 
        refundCarryVo.setDeductionTotalUser(userProjectDeductionVo.getDeductionTotal());
 
        int refundStatus;
        if(surplusNum == refundRecordItemSource.getRefundNum()){
            refundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
        }else{
            refundStatus=OrderTotalConstants.STATUS_REFUND_PART;
        }
 
        //更新子单信息
        updateOrderItemTwo(orderItemSon,refundStatus,refundRecordItemSource.getRefundMoney(),refundRecordItemSource.getRefundNum(),commonService);
 
        //处理退款支付方式
        refundCarryVo = refundRecordMotnedItemTwoHandle(userProjectDeductionVo.getDeductionTotal(),refundRecord,refundRecordItemSource,refundCarryVo,commonService);
 
        if(refundRecordItem.getType().equals(OrderItemConstants.CARD_BAG)){
            //是卡包的,刪除卡包使用
            deleteUserCardUsed(orderItemSon.getCardItemInfoId(),orderItemSon.getId(),orderItemSon.getOrderId(),refundRecordItemSource.getRefundNum(),commonService);
        }
 
        return refundCarryVo;
    }
 
    /**退款二级是商品
     * @param refundRecord 退款总记录
     * @param refundRecordItem 退款一级子单
     * @param refundRecordItemSource  退款二级子单
     * @param refundCarryVo 全局携带参数结构
     * @param commonService 映射
     * @return 全局携带参数结构
     */
    private static RefundCarryVo handRefundSonRerail(RefundRecord refundRecord,RefundRecordItem refundRecordItem, RefundRecordItemSource refundRecordItemSource
            ,RefundCarryVo refundCarryVo,CommonService commonService) {
 
        //判断操作完了去修改子订单状态
        OrderItemSon orderItemSon=commonService.selectOneByKey(OrderItemSonMapper.class,refundRecordItemSource.getOrderItemSonId());
        if (orderItemSon==null){
            throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"未找到二级子订单信息");
        }
 
        //计算子单是否还有剩余的可扣疗程数
        int surplusNum = orderItemSon.getBuyNum() - orderItemSon.getHasReNum();
        if(refundRecordItemSource.getRefundNum() > surplusNum){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款次数大于可退次数[84]!");
        }
 
        int refundStatus;
        if(surplusNum == refundRecordItemSource.getRefundNum()){
            refundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
        }else{
            refundStatus=OrderTotalConstants.STATUS_REFUND_PART;
        }
 
        updateOrderItemTwo(orderItemSon,refundStatus,refundRecordItemSource.getRefundMoney(),refundRecordItemSource.getRefundNum(),commonService);
 
        //处理退款支付方式
        refundCarryVo = refundRecordMotnedItemTwoHandle(null,refundRecord,refundRecordItemSource,refundCarryVo,commonService);
 
        if(refundRecordItem.getType().equals(OrderItemConstants.CARD_BAG)){
            //是卡包的,刪除卡包使用
            deleteUserCardUsed(orderItemSon.getCardItemInfoId(),orderItemSon.getId(),orderItemSon.getOrderId(),refundRecordItemSource.getRefundNum(),commonService);
        }
 
        return refundCarryVo;
    }
 
    /**更新订单一级子单的信息
     * @param orderItem 订单子单
     * @param refundStatus 退款状态
     * @param refundTotal 退款金额
     * @param refundNum 退款数量
     * @param commonService 映射
     */
    public static void updateOrderItemOne(OrderItem orderItem,Integer refundStatus,BigDecimal refundTotal,Integer refundNum
            ,CommonService commonService){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        values.put("id", orderItem.getId());
        values.put("refundStatus", refundStatus);
        values.put("refundTotal",refundTotal);
        values.put("refundNum",refundNum);
        values.put("oldHasReNum",orderItem.getHasReNum());
        sqlSentence.sqlUpdate(" refundStatus=#{m.refundStatus},reTotal=reTotal+#{m.refundTotal},hasReNum=hasReNum+#{m.refundNum}" +
                " WHERE isDel = 0 AND id = #{m.id} AND hasReNum = #{m.oldHasReNum}",values);
        if(commonService.updateWhere(OrderItemMapper.class,sqlSentence) != 1){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"当前订单信息已发生变化,请重试[012]!");
        }
    }
 
    /**更新订单二级子单的信息
     * @param orderItemSon 订单子单
     * @param refundStatus 退款状态
     * @param refundTotal 退款金额
     * @param refundNum 退款数量
     * @param commonService 映射
     */
    public static void updateOrderItemTwo(OrderItemSon orderItemSon,Integer refundStatus,BigDecimal refundTotal,Integer refundNum
            ,CommonService commonService){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        values.put("id", orderItemSon.getId());
        values.put("refundStatus", refundStatus);
        values.put("refundTotal",refundTotal);
        values.put("refundNum",refundNum);
        values.put("oldHasReNum",orderItemSon.getHasReNum());
        sqlSentence.sqlUpdate(" refundStatus = #{m.refundStatus},reTotal=reTotal+#{m.refundTotal},hasReNum=hasReNum+#{m.refundNum}" +
                " where isDel=0 AND id = #{m.id} AND hasReNum = #{m.oldHasReNum}",values);
        if(commonService.updateWhere(OrderItemSonMapper.class,sqlSentence) != 1){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"当前订单信息已发生变化,请重试[012]!");
        }
    }
 
    /**获取订单一级子单的支付方式记录
     * @param orderItemId 订单一级子单标识
     * @param commonService 映射
     * @return 订单一级子单的支付方式记录
     */
    public static List<ConsumePayItem> getOrderItemOneConsumePay(String orderItemId,CommonService commonService){
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        //获取子单的支付方式,一级子单支付记录,计算可退款金额
        values.put("typeId",orderItemId);
        sqlSentence.sqlSentence("SELECT * FROM consume_pay_item WHERE isDel = 0 AND typeId = #{m.typeId}",values);
        return commonService.selectList(ConsumePayItemMapper.class,sqlSentence);
    }
 
    /**获取订单二级子单的支付方式记录
     * @param orderItemId 订单一级子单标识
     * @param commonService 映射
     * @return 订单二级子单的支付方式记录
     */
    public static List<ConsumePayItem> getOrderItemTwoConsumePay(String orderItemId,CommonService commonService){
 
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
 
        //获取子单的支付方式,一级子单支付记录,计算可退款金额
        values.put("typeId",orderItemId);
        sqlSentence.sqlSentence("SELECT * FROM consume_pay_item_son WHERE isDel = 0 AND typeId = #{m.typeId}",values);
        List<ConsumePayItemSon> consumePayItemSonList = commonService.selectList(ConsumePayItemSonMapper.class,sqlSentence);
        List<ConsumePayItem> consumePayItemList = new ArrayList<>();
        ConsumePayItem consumePayItem;
        for(ConsumePayItemSon consumePayItemSon:consumePayItemSonList){
            consumePayItem = new ConsumePayItem();
            BeanUtils.copyProperties(consumePayItemSon,consumePayItem);
            consumePayItemList.add(consumePayItem);
        }
        return consumePayItemList;
    }
 
    /**获取已退款方式金额,根据支付方式编号求和返回
     * 注意:groupByONumberNo和groupByConsumePayId不能同时使用
     * @param itemId 订单子单标识
     * @param refundRecordItemId 退款子单标识
     * @param groupByONumberNo 根据支付方式编号求和
     * @param groupByConsumePayId 根据支付方式记录标识求和
     * @param commonService 映射
     * @return 返回已退款方式金额集合
     */
    public static List<RefundRecordConsumePay> getRefundRecordConsumePay(String itemId,String refundRecordItemId,boolean groupByONumberNo
            ,boolean groupByConsumePayId,CommonService commonService){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> values = new HashMap<>();
        StringBuilder sql = new StringBuilder();
 
        sql.append("SELECT");
        if(groupByONumberNo){
            sql.append(" a.numberNo,");
        }
        if(groupByConsumePayId){
            sql.append(" a.consumePayId,");
        }
        sql.append("SUM(a.refundTotal) AS refundTotal FROM refund_record_consume_pay a");
        sql.append(" JOIN refund_record rr ON rr.id = a.refundRecordId AND rr.isDel = 0 AND rr.refundStatus = #{m.refundStatus}");
        sql.append("  WHERE a.isDel = 0");
        if(StringUtils.noNull(itemId)){
            sql.append("  AND a.commonId = #{m.commonId}");
        }
        if(StringUtils.noNull(refundRecordItemId)){
            sql.append("  AND a.refundRecordItemId = #{m.refundRecordItemId}");
        }
        if(groupByONumberNo){
            sql.append(" GROUP BY a.numberNo");
        }
        if(groupByConsumePayId){
            sql.append(" GROUP BY a.consumePayId");
        }
        //获取已退款的支付方式
        values.put("commonId",itemId);
        values.put("refundStatus", RefundStatus.STATUS_SUCC_REFUND);
        sqlSentence.sqlSentence(sql.toString(),values);
        return commonService.selectList(RefundRecordConsumePayMapper.class,sqlSentence);
    }
 
    /**保存退款方式和支付方式关联
     * @param refundTotal 退款金额
     * @param commonType 子单级别,可空
     * @param commonId 子单标识,可空
     * @param orderId  总单标识
     * @param numberNo 支付方式编号
     * @param name 支付方式名称
     * @param consumePayId 支付方式记录标识
     * @param refundMethodId 退款方式标识
     * @param refundRecordItemId 退款子记录标识,可空
     * @param refundRecordId 退款总记录标识
     * @param commonService 映射
     * @return 返回关联记录
     */
    public static RefundRecordConsumePay insertRefundRecordConsumePay(BigDecimal refundTotal, String commonType, String commonId, String orderId
            , String numberNo,String name,Integer isMoneyPay,Integer isExecute, String consumePayId, String refundMethodId,String refundRecordItemId,String refundRecordId,CommonService commonService){
        //生成关联记录
        RefundRecordConsumePay refundRecordConsumePay = new RefundRecordConsumePay();
        refundRecordConsumePay.setRefundTotal(refundTotal);
        refundRecordConsumePay.setCommonType(commonType);
        refundRecordConsumePay.setCommonId(commonId);
        refundRecordConsumePay.setOrderId(orderId);
        refundRecordConsumePay.setName(name);
        refundRecordConsumePay.setNumberNo(numberNo);
        refundRecordConsumePay.setIsMoneyPay(isMoneyPay);
        refundRecordConsumePay.setIsExecute(isExecute);
        refundRecordConsumePay.setConsumePayId(consumePayId);
        refundRecordConsumePay.setRefundMethodId(refundMethodId);
        refundRecordConsumePay.setRefundRecordItemId(refundRecordItemId);
        refundRecordConsumePay.setRefundRecordId(refundRecordId);
        commonService.insert(RefundRecordConsumePayMapper.class,refundRecordConsumePay);
        return refundRecordConsumePay;
    }
 
    /**获取可退款的用户卡项
     * @param sourceId 订单子单标识
     * @return 可退款的用户卡项
     */
    public static List<UserCard> getRefundCard(String sourceId,CommonService commonService){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> sqlMap = new HashMap<>();
        //获取用户卡项
        sqlMap.put("sourceId",sourceId);
        sqlMap.put("status",UserCard.TYPE_NO_USED);
        sqlMap.put("effectiveStatus",UserProjectConstants.EFF_STATUS_YES);
        sqlSentence.sqlSentence("SELECT * FROM user_card WHERE isDel = 0 AND sourceId = #{m.sourceId} AND status = #{m.status}" +
                " AND effectiveStatus = #{m.effectiveStatus} AND turnAddId IS NULL",sqlMap);
        return commonService.selectList(UserCardMapper.class,sqlSentence);
 
    }
 
    /**获取用户项目*/
    public static UserProjectItem getUserProject(String commonId,CommonService commonService){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> map = new HashMap<>();
 
        map.put("commonId",commonId);
        sqlSentence.sqlSentence("select * from user_project_item where isDel=0 and commonId=#{m.commonId} and isTransfer = 0",map);
        return commonService.selectOne(UserProjectItemMapper.class,sqlSentence);
    }
 
}