chenjiahe
2023-12-04 228d3547d428c1eb79e95107014e6411006b9fda
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
package com.hx.phip.util.api;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.tool.CouponTool;
import com.hx.phiappt.constants.tool.PickUpGoodTool;
import com.hx.phiappt.dao.mapper.CouponNumberMapper;
import com.hx.phiappt.dao.mapper.CouponOrderDiscountLogMapper;
import com.hx.phiappt.dao.mapper.LimitTotalMapper;
import com.hx.phiappt.model.*;
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.RecordConsume;
import com.hx.phiappt.model.coupon.Coupon;
import com.hx.phiappt.model.coupon.CouponAppoint;
import com.hx.phiappt.model.coupon.CouponNumber;
import com.hx.phiappt.model.coupon.CouponOrderDiscountLog;
import com.hx.phiappt.model.limit.LimitTotal;
import com.hx.phiappt.model.order.OrderItem;
import com.hx.phiappt.model.order.OrderItemSon;
import com.hx.phiappt.model.order.OrdersTotal;
import com.hx.phiappt.model.user.UserCard;
import com.hx.phiappt.model.user.UserCardUsed;
import com.hx.phiappt.model.user.UserProject;
import com.hx.phiappt.model.user.UserProjectItem;
import com.hx.phiappt.model.userMoney.UserMoneyUnclaimed;
import com.hx.phiappt.model.user.*;
import com.hx.phiappt.model.warehouse.PickUpGood;
import com.hx.phiappt.model.warehouse.PickUpGoodItem;
import com.hx.phip.config.CustomParameter;
import com.hx.phip.dao.mapper.*;
import com.hx.resultTool.Result;
import com.hx.util.StringUtils;
import com.hz.crm.dto.coupon.CouponAppointDto;
import com.hz.crm.dto.coupon.CouponCheckDto;
import com.hz.crm.dto.coupon.CouponGoodsDto;
import com.hz.crm.dto.coupon.CouponInfoDto;
import com.hz.crm.feign.FGoodsSkuService;
import com.platform.constants.PlatformPattern;
import com.platform.exception.PlatTipsException;
import com.platform.resultTool.PlatformCode;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
 
import static com.hx.phip.util.api.OrderAddUtil.checkMemberLevel;
 
/**
 * 结账-结账工具类
 */
public class OrderPayUtil {
    private static final Logger logger = LoggerFactory.getLogger(OrderPayUtil.class);
 
    /**
     * 支付-处理用户具体支付
     * @param orderTypeList             订单类型集合:充值、支付
     * @param amountList                用户具体使用支付方式JSON集合
     * @param operator                  操作人Map
     * @param ordersTotal               总订单
     * @param userMoney                 用户资金对象
     * @param commonService
     * @param customParameter
     * @return
     */
    public static Map<String,Object> handPayMethod(List<String> orderTypeList, JSONArray amountList, Map<String, String> operator, OrdersTotal ordersTotal,
                                                   UserMoney userMoney, CommonService commonService, CustomParameter customParameter) {
        //新增消费记录
        RecordConsume recordConsume=setRecordConsume(ordersTotal);
        commonService.insert(RecordConsumeMapper.class,recordConsume);
 
        JSONObject hisPay;
        BigDecimal money;
        ConsumePay consumePay;
        Map<String,Object> objectMap=new HashMap<>();//sql参数Map,方法返回map
        Integer isAccount=0;//等于0没有任何变化,1:代表增值金变动,2:代表储值金额有变动
        BigDecimal payTotal=BigDecimal.ZERO;//订单的已支付现金金额(微信/支付宝支付/其他)
        BigDecimal payRecharge=BigDecimal.ZERO;//订单的已支付储值金金额
        BigDecimal payIncrement=BigDecimal.ZERO;//订单的已支付增值金金额
        BigDecimal snapPayTotal=BigDecimal.ZERO;//划扣现金总金额
        Map<String,String> itemMap=new HashMap<>();//一级子订单用户实际支付金额,该Map用于统计用户按照项目部分付款
        JSONArray hisPayList=new JSONArray();////用户支付方式集合,用于同步到his系统
        List<String> cardIds=new ArrayList<>();//存储卡项id,用户判断用户是否使用的是卡包进行结算
        SqlSentence sqlSentence=new SqlSentence();;
        sqlSentence.setM(objectMap);
        //查询二级子订单
        objectMap.put("orderId",ordersTotal.getId());
        objectMap.put("isDel",BaseEntity.NO);
        sqlSentence.setSqlSentence("select COUNT(*) from order_item_source where isDel= #{m.isDel} and orderId=#{m.orderId} and isCardBag=1");
        //判断该订单是卡包还是其他订单,如果是卡包该cardNum肯定>0代表该订单是卡包订单需要使用卡项进行支付,不能使用其他支付方式进行支付
        int cardNum = commonService.selectCountSql(OrderItemSonMapper.class,sqlSentence);
        for(int i=0;i<amountList.size();i++) {
 
            hisPay=new JSONObject();
            JSONObject jsonObject = amountList.getJSONObject(i);
            String amount = jsonObject.getString("amount");//用户实际支付金额
            String method = jsonObject.getString("method");//用户支付编码
            String commonId = jsonObject.getString("commonId");//用户支付的商品/项目/组合套餐/组合卡项的标识
            String cardEquityId = jsonObject.getString("cardEquityId");//卡项的权益类型标识
            String userCardId = jsonObject.getString("userCardId");//用户卡包标识
            itemMap.put(commonId, amount);
            money = new BigDecimal(amount);
 
            if(cardNum>0 && !PayMethodTypeConstants.PAY_CARD.equals(method)){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "该订单为卡包订单,应当使用卡项支付方式进行结账");
            }
 
            objectMap.put("method",method);
            objectMap.put("isDel",BaseEntity.NO);
            objectMap.put("isUp",BaseEntity.YES);
            sqlSentence.setSqlSentence("select * from payment_method where numberNo=#{m.method} and isDel=#{m.isDel} and isUp=#{m.isUp}");
            //记录订单支付的方式
            PaymentMethod paymentMethod=commonService.selectOne(PaymentMethodMapper.class,sqlSentence);
            if (paymentMethod == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "未找到支付方式");
            }
            //统计现金支付总额,为了计算未执行划扣金额,设置现金支付的支付方式才计算到未执行划扣金额
            if(BaseEntity.YES==paymentMethod.getIsExecute()){
                snapPayTotal=snapPayTotal.add(money);
            }
            consumePay = new ConsumePay(method, paymentMethod.getName(), money, ConsumePayConstants.STATUS_ORDER, ordersTotal.getId(),recordConsume.getId(),
                    paymentMethod.getIsMoneyPay(),paymentMethod.getIsExecute(),paymentMethod.getId());
            commonService.insert(ConsumePayMapper.class,consumePay);
            if(orderTypeList.contains(ordersTotal.getType())){
                //订单充值
                isAccount=1;
                if(!(PayMethodTypeConstants.PAY_STORED.equals(paymentMethod.getNumberNo()) || PayMethodTypeConstants.PAY_ADD_FUND.equals(paymentMethod.getNumberNo()))){
//                    userMoney=UserMoneyUtil.dealStoreValueFund(operator,ordersTotal.getUserId(),userMoney,money,customParameter,commonService,1);
                    UserMoneyUtil.setUserMoneyUnclaimed(ordersTotal,ordersTotal.getId(),ordersTotal.getShouldTotal(), UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND,OperationReasonConstants.OP_REASON_RECHARGE_GIFT,commonService,UserMoneyUnclaimed.NO);
 
//                    if(GivingAmountType.TYPE_ADD_AMONUT.equals(ordersTotal.getGivingType())){
//                        //增加增值金,调用航爷的方法,增值金需要过期
//                        UserMoneyUtil.setUserMoneyUnclaimed(ordersTotal,null,ordersTotal.getGivingAmount(), UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND,OperationReasonConstants.OP_REASON_RECHARGE_GIFT,commonService,UserMoneyUnclaimed.YES);
//                        objectMap.put("userId",ordersTotal.getUserId());
//                        sqlSentence.setSqlSentence("select * from user_money where userId=#{m.userId}");
//                        userMoney=commonService.selectOne(UserMoneyMapper.class,sqlSentence);
//                    }
                    payRecharge=payRecharge.add(money);
                }else{
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"用户不可以用储值金进行充值");
                }
            }else{
                //订单支付
                switch (paymentMethod.getNumberNo()){
                    //增值金支付
                    case PayMethodTypeConstants.PAY_ADD_FUND:
                        isAccount=2;
                        //增加增值金,调用航爷的方法,增值金需要过期
                        UserMoneyUtil.setUserMoneyUnclaimed(ordersTotal,ordersTotal.getId(),money.negate(), UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND,OperationReasonConstants.OP_REASON_RECHARGE_BUY,commonService,UserMoneyUnclaimed.NO);
                        objectMap.put("userId",ordersTotal.getUserId());
                        sqlSentence.setSqlSentence("select * from user_money where userId=#{m.userId}");
                        userMoney=commonService.selectOne(UserMoneyMapper.class,sqlSentence);
                        payIncrement=payIncrement.add(money);//累加增值金
                        break;
                    //储值金支付
                    case PayMethodTypeConstants.PAY_STORED:
                        isAccount=3;
                        UserMoneyUtil.setUserMoneyUnclaimed(ordersTotal,ordersTotal.getId(),money.negate(), UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND,OperationReasonConstants.OP_REASON_RECHARGE_BUY,commonService,UserMoneyUnclaimed.NO);
                        payRecharge=payRecharge.add(money);//累加储值金
                        break;
                    //卡项支付
                    case PayMethodTypeConstants.PAY_CARD:
                        isAccount=5;
                        //记录用户卡包使用记录
                        cardIds.add(payCard(ordersTotal, commonId, cardEquityId, userCardId,customParameter,commonService));
                        payTotal=payTotal.add(money);
                        break;
                    case PayMethodTypeConstants.PAY_INTEGRAL:
                        isAccount=6;
                        //积分
                        UserMoneyUtil.setUserMoneyUnclaimed(ordersTotal,ordersTotal.getId(),money.negate(), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_RECHARGE_BUY,commonService,UserMoneyUnclaimed.YES);
                        payTotal=payTotal.add(money);
                        break;
                    default:
                        isAccount=4;//除了增值金、储值金以外的支付
                        payTotal=payTotal.add(money);
                        break;
                }
            }
            //添加用户支付方式金额、以及方法,用于同步到his系统
            hisPay.put("amount",amount);
            hisPay.put("methodCode",paymentMethod.getNumberNo());
            hisPayList.add(hisPay);
        }
        if(isAccount==0){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请传支付方式编码");
        }
        objectMap.clear();
        objectMap.put("consumeTotal",ordersTotal.getTotal());
        objectMap.put("consumeMoney",payTotal.add(payRecharge).add(payIncrement));
        objectMap.put("thirdPartyFund",ordersTotal.getPayTotal());
        objectMap.put("storedFund",ordersTotal.getPayRecharge());
        objectMap.put("incrementFund",ordersTotal.getPayIncrement());
        objectMap.put("payMoney",payTotal.add(payRecharge).add(payIncrement));
        objectMap.put("id",recordConsume.getId());
        sqlSentence.setSqlSentence(" consumeTotal=#{m.consumeTotal},consumeMoney=#{m.consumeMoney},thirdPartyFund=#{m.thirdPartyFund},storedFund=#{m.storedFund}," +
                                    "incrementFund=#{m.incrementFund},payMoney=#{m.payMoney} where isDel=0 and id=#{m.id}");
        commonService.updateWhere(RecordConsumeMapper.class,sqlSentence);
        objectMap.clear();
        objectMap.put("ordersTotal",ordersTotal);
        objectMap.put("itemMap",itemMap);
        objectMap.put("payTotal",payTotal);
        objectMap.put("payRecharge",payRecharge);
        objectMap.put("payIncrement",payIncrement);
        objectMap.put("hisPayList",hisPayList);
        objectMap.put("cardIds",cardIds);
        objectMap.put("snapPayTotal",snapPayTotal);
        return objectMap;
    }
 
    /**
     *  总订单-处理总订单
     * @param operator                  操作人Map
     * @param ordersTotal               总订单
     * @param payTotal                  订单的已支付现金金额(微信/支付宝支付/其他)
     * @param payRecharge               订单的已支付储值金金额
     * @param payIncrement              订单的已支付增值金金额
     * @param couponAfterAmount         使用优惠券的折扣后总金额
     */
    public static void payHandleOrderTotal(Map<String, String> operator, OrdersTotal ordersTotal, BigDecimal payTotal
            , BigDecimal payRecharge, BigDecimal couponAfterAmount, BigDecimal payIncrement
            , BigDecimal actualTotalPoint ,CommonService commonService) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        map.put("id",ordersTotal.getId());
 
        //设置用户实际支付的储值金
        ordersTotal.setPayRecharge(payRecharge);
        //设置用户实际支付的增值金
        ordersTotal.setPayIncrement(payIncrement);
        //设置用户实际支付的现金金额(微信/支付宝支付/其他)
        ordersTotal.setPayTotal(payTotal);
        //设置用户实际支付积分
        ordersTotal.setActualTotalPoints(actualTotalPoint);
        //计算用户实际支付总金额
        BigDecimal actualTotal=payRecharge.add(payIncrement).add(payTotal).setScale(2,RoundingMode.HALF_UP);
        //设置用户实际支付的总金额
        ordersTotal.setActualTotal(actualTotal);
 
        //统计加上优惠券用户实际支付金额=用户实际支付总金额+优惠券金额
        BigDecimal couponTotal=BigDecimal.ZERO;
        couponTotal=couponTotal.add(actualTotal).add(couponAfterAmount).setScale(2,RoundingMode.HALF_UP);
 
        //系统剩余支付金额=应付总金额-优惠券金额
        BigDecimal laveAmount = ordersTotal.getShouldTotal().subtract(couponAfterAmount).setScale(2, RoundingMode.HALF_UP);
        if(laveAmount.compareTo(BigDecimal.ZERO) ==-1){
            //系统剩余支付金额为负数:默认为0,标识优惠总金额足够付应付总订单
            laveAmount=BigDecimal.ZERO;
        }
        /**
         * 判断剩余支付金额是否还需要支付,
         *          如果系统剩余支付金额-用户实际支付金额等于0那么订单直接完成,代表优惠券直接满足该订单的金额
         *          如果系统计算剩余支付金额-用户实际支付金额大于0或者小于0那么表示用户支付金额不符合,代表用户支付金额不正确
         */
        BigDecimal subtract = laveAmount.subtract(actualTotal);
        logger.info("subtract:{},couponTotal:{},couponAfterAmount:{}",subtract,couponTotal,couponAfterAmount);
        if(OrderTotalConstants.TYPE_CARD_BAG.equals(ordersTotal.getType())) {
            ordersTotal.setPayStatus(OrderTotalConstants.PAY_STATUS_SUC);//已支付
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);//已支付
        }else if(couponTotal.compareTo(ordersTotal.getShouldTotal()) ==0){
            ordersTotal.setPayStatus(OrderTotalConstants.PAY_STATUS_SUC);//已支付
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);//已支付
        }else if(subtract.compareTo(BigDecimal.ZERO)==0){
            ordersTotal.setPayStatus(OrderTotalConstants.PAY_STATUS_SUC);//已支付
            ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);//已支付
        }else if(couponTotal.compareTo(ordersTotal.getShouldTotal()) ==-1){
            ordersTotal.setPayStatus(OrderTotalConstants.PAY_STATUS_PART);//部分支付
            ordersTotal.setStatus(OrderTotalConstants.STATUS_ARREARS);//欠费
        }else {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"用户实际支付金额超出应付总金额,请重新填写");
        }
 
        //设置支付时间
        ordersTotal.setPayTime(new Date());
 
        map.put("actualTotal",ordersTotal.getActualTotal());
        map.put("payTotal",ordersTotal.getPayTotal());
        //优惠券金额比订单金额大
        if(couponAfterAmount.compareTo(ordersTotal.getShouldTotal()) > 0){
            map.put("couponAfterAmount",ordersTotal.getShouldTotal());
        }else{
            map.put("couponAfterAmount",couponAfterAmount);
        }
        map.put("payRecharge",ordersTotal.getPayRecharge());
        map.put("payIncrement",ordersTotal.getPayIncrement());
        map.put("actualTotalPoints",ordersTotal.getActualTotalPoints());
        map.put("status",ordersTotal.getStatus());
        map.put("payStatus",ordersTotal.getPayStatus());
        map.put("payTime",ordersTotal.getPayTime());
        map.put("cashierId",ordersTotal.getCashierId());
        map.put("cashierName",ordersTotal.getCashierName());
        map.put("cashierShopId",ordersTotal.getCashierShopId());
        map.put("cashierShopName",ordersTotal.getCashierShopName());
        map.put("couponTotal",couponAfterAmount);
        //支付人信息
        map.put("payUserId",ordersTotal.getPayUserId());
        map.put("payUserNo",ordersTotal.getPayUserNo());
        map.put("payUserName",ordersTotal.getPayUserName());
        map.put("payUserCIQ",ordersTotal.getPayUserCIQ());
        map.put("payUserMemberId",ordersTotal.getPayUserMemberId());
        map.put("payUserMemberNo",ordersTotal.getPayUserMemberNo());
        map.put("payUserLevel",ordersTotal.getPayUserLevel());
        map.put("payUserAdviserId",ordersTotal.getPayUserAdviserId());
        map.put("payUserAdviserNo",ordersTotal.getPayUserAdviserNo());
        map.put("payUserAdviserName",ordersTotal.getPayUserAdviserName());
        map.put("payUserShopId",ordersTotal.getPayUserShopId());
        map.put("payUserShopNo",ordersTotal.getPayUserShopNo());
        map.put("payUserShopName",ordersTotal.getPayUserShopName());
        // 大众点评兑换码
        map.put("conversionCode", ordersTotal.getConversionCode());
        // 销售平台订单号
        map.put("sourceOrderNo", ordersTotal.getSourceOrderNo());
        // 订单推荐人处理
        map.put("inviteeType", ordersTotal.getInviteeType());
        map.put("inviteeId", ordersTotal.getInviteeId());
        map.put("inviteeName", ordersTotal.getInviteeName());
        map.put("userBelongingType", ordersTotal.getUserBelongingType());
 
        sqlSentence.setSqlSentence(" actualTotal=actualTotal+#{m.actualTotal},shouldTotal = shouldTotal - #{m.couponAfterAmount},payTotal=payTotal+#{m.payTotal},payRecharge=payRecharge+#{m.payRecharge}" +
                ",payIncrement=payIncrement+#{m.payIncrement},actualTotalPoints=actualTotalPoints+#{m.actualTotalPoints},status=#{m.status},sourceOrderNo=#{m.sourceOrderNo}"+
                ",payStatus=#{m.payStatus},payTime=#{m.payTime},couponTotal=#{m.couponTotal},cashierId=#{m.cashierId},cashierName=#{m.cashierName},cashierShopId=#{m.cashierShopId},cashierShopName=#{m.cashierShopName}" +
                ",payUserId = #{m.payUserId},payUserNo = #{m.payUserNo},payUserName = #{m.payUserName},payUserCIQ = #{m.payUserCIQ},payUserMemberId = #{m.payUserMemberId},conversionCode = #{m.conversionCode}" +
                ",payUserMemberNo = #{m.payUserMemberNo},payUserLevel = #{m.payUserLevel},payUserAdviserId = #{m.payUserAdviserId},payUserAdviserNo = #{m.payUserAdviserNo}" +
                ",payUserAdviserName = #{m.payUserAdviserName},payUserShopId = #{m.payUserShopId},payUserShopNo = #{m.payUserShopNo},payUserShopName = #{m.payUserShopName}" +
                ",inviteeType = #{m.inviteeType},inviteeId = #{m.inviteeId},inviteeName = #{m.inviteeName},userBelongingType = #{m.userBelongingType}" +
                " where id =#{m.id} and status in (0,1,5)");
        //更新总订单
        if(commonService.updateWhere(OrdersTotalMapper.class,sqlSentence)!=1){
            throw new TipsException("请勿重复结账!");
        }
        //记录结账订单日志
        commonService.insert(OrderLogMapper.class,ApiOrderUtil.setOrderLog(ordersTotal,null,operator.get("operatorId"),operator.get("operatorName"),"",3, OrderLogConstants.LOG_TYPE_PAY));
        //更新现金总金额
        map.put("orderId",ordersTotal.getId());
        map.put("snapPayTotal",ordersTotal.getOrderInfo().getSnapPayTotal());
        map.put("snapExecuteTotal",ordersTotal.getOrderInfo().getSnapExecuteTotal());
        // 大众点评信息
        map.put("orderOCRImageUrl",ordersTotal.getOrderInfo().getOrderOCRImageUrl());
        map.put("otherOrderNo",ordersTotal.getOrderInfo().getOtherOrderNo());
        map.put("redemptionCode",ordersTotal.getOrderInfo().getRedemptionCode());
        sqlSentence.setSqlSentence(" snapPayTotal=#{m.snapPayTotal},snapExecuteTotal=#{m.snapExecuteTotal},orderOCRImageUrl=#{m.orderOCRImageUrl},otherOrderNo=#{m.otherOrderNo},redemptionCode=#{m.redemptionCode} " +
                "where snapPayTotal=0 and orderId=#{m.orderId}");
        commonService.updateWhere(OrderInfoMapper.class,sqlSentence);
    }
 
    /**
     * 子订单-处理子订单
     * @param ordersTotal               总订单
     * @param itemMap                   一级子订单用户实际支付金额,该Map用于统计用户按照项目部分付款
     * @param operator                  操作人Map
     * @param userMoney                 用户资金对象
     * @param cardIds                   存储卡项id,用户判断用户是否使用的是卡包进行结算
     * @param commonService
     * @param customParameter
     */
    public static void payHandOrderItem(List<OrderItem> orderItemList,OrdersTotal ordersTotal, Map<String, String> itemMap, Map<String, String> operator, UserMoney userMoney, List<String> cardIds,
                                        BigDecimal payTotal,CommonService commonService, CustomParameter customParameter) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        UserProjectItem userProjectItem = null;
        Date date = new Date();
        User user=commonService.selectOneByKey(UserMapper.class,ordersTotal.getUserId());
        List<PickUpGoodItem> items = null;
        PickUpGoodItem pickUpGoodItem;
 
        //根据一级子订单处理二级子订单项目、商品、促销、卡项操作
        for(OrderItem vo:orderItemList){
            userProjectItem = new UserProjectItem();
 
            map.clear();
            map.put("orderItemId",vo.getId());
            map.put("isDel",BaseEntity.NO);
            map.put("snapPayTotal",ordersTotal.getOrderInfo().getSnapPayTotal());
            sqlSentence.setSqlSentence("select * from order_item_source where isDel= #{m.isDel} and orderItemId=#{m.orderItemId}");
            List<OrderItemSon> orderItemSonList=commonService.selectList(OrderItemSonMapper.class,sqlSentence);
 
            //小荔枝说已有卡项结账不需要限制
            if(!OrderItemConstants.CARD_BAG.equals(vo.getType()) || BaseEntity.NO != vo.getIsLimitBug()){
                //限制总表,查询该项目、商品、卡项、促销是否限制,有限制查看是否符合支付条件并对其限制
                JSONObject param = new JSONObject();
                param.put("commonId",vo.getCommonId());
                param.put("commonName",vo.getGoodsName());
                param.put("userId",ordersTotal.getUserId());
                param.put("shopId",ordersTotal.getDeveloperShopId());
                LimitPlatformUtil.limitMethod(commonService,param.toJSONString());
                //限制会员等级支付
                map.put("foreignKey",vo.getCommonId());
                checkMemberLevel(sqlSentence, user, vo.getType(),commonService);
            }
 
            if(OrderItemConstants.TYPE_PROJECT.equals(vo.getType())){
                BigDecimal snapMoney = noSnapMoney(ordersTotal, vo, null, map, commonService);
                logger.info("项目执行划扣金额:{},订单标识:{}",snapMoney,ordersTotal.getId());
                //未执行划扣金额
                userProjectItem.setNoDeductionAmount(snapMoney);
                userProjectItem.setDeductionTotalAmount(snapMoney);
                //暂时不处理,全部由同步中心处理
//                handleUserProject(ordersTotal, userProjectItem, date, vo,null,OrderItemConstants.TYPE_PROJECT,commonService);
            }else if(OrderItemConstants.TYPE_RETAIL.equals(vo.getType())){
                //处理商品信息,生成提货单
                items=new ArrayList<>();
                pickUpGoodItem=new PickUpGoodItem();
                pickUpGoodItem.setConsumablesId(vo.getCommonId());
                pickUpGoodItem.setNum(vo.getBuyNum());
                pickUpGoodItem.setSalePrice(vo.getCurPrice());
                pickUpGoodItem.setSalePrice(vo.getCurPrice());
                items.add(pickUpGoodItem);
            }else if(OrderItemConstants.TYPE_CARD.equals(vo.getType())){
                //cardIds不为空表示使用卡项支付
                if(cardIds !=null && cardIds.size()>0 && cardIds.contains(vo.getCommonId())){
                    for(OrderItemSon orderItemSon:orderItemSonList){
//                        if(OrderItemConstants.TYPE_PROJECT.equals(orderItemSon.getType())){
//                            BigDecimal snapMoney = noSnapMoney(ordersTotal, vo, orderItemSon, map, commonService);
//                            logger.info("卡项执行划扣金额:{},订单标识:{}",snapMoney,ordersTotal.getId());
//                            //未执行划扣金额
//                            userProjectItem.setNoDeductionAmount(snapMoney);
//                        }
                        items = handCardPromotion(ordersTotal, operator, userMoney, userProjectItem, items, vo, orderItemSon,commonService,customParameter);
                    }
                }else{
//                    //卡包,生成用户卡包中的具体卡项记录
//                    map.put("cardId",vo.getCommonId());
//                    sqlSentence.setSqlSentence("select * from limit_total where isDel= #{m.isDel} and foreignKey=#{m.cardId} order by createTime desc limit 1");
//                    LimitTotal limitTotal=commonService.selectOne(LimitTotalMapper.class,sqlSentence);
//                    UserCard userCard = createUserCardItem(ordersTotal, vo, limitTotal);
//                    //购买卡项不生成卡包信息,由同步中心生成卡包信息,卡包支付还是以领建为主
//                    commonService.insert(UserCardMapper.class,userCard);
                }
            }else if(OrderItemConstants.CARD_BAG.equals(vo.getType())){
                map.put("userCardId",vo.getUserCardId());
                if(cardIds !=null && cardIds.size()>0 && cardIds.contains(vo.getCommonId())) {
                    for (OrderItemSon orderItemSon : orderItemSonList) {
                        if (OrderItemConstants.TYPE_PROJECT.equals(orderItemSon.getType())) {
                            BigDecimal snapMoney = noSnapMoney(ordersTotal, vo, orderItemSon, map, commonService);
                            logger.info("卡项执行划扣金额:{},订单标识:{}", snapMoney, ordersTotal.getId());
                            //未执行划扣金额
                            userProjectItem.setNoDeductionAmount(snapMoney);
                            userProjectItem.setDeductionTotalAmount(snapMoney);
                        }
                        items = handCardPromotion(ordersTotal, operator, userMoney, userProjectItem, items, vo, orderItemSon, commonService, customParameter);
                    }
                }
            } else if(OrderItemConstants.TYPE_PROMOTION.equals(vo.getType())){
                //处理促销,将促销的项目生成未划扣记录,商品生成提货单,增值金、储值金、积分给用户添加上
                if(orderItemSonList==null || orderItemSonList.size()==0){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账:购买促销时未找到该订单的二级子项");
                }
                for(OrderItemSon orderItemSon:orderItemSonList){
                    if(OrderItemConstants.TYPE_PROJECT.equals(orderItemSon.getType())){
                        BigDecimal snapMoney = noSnapMoney(ordersTotal, vo, orderItemSon, map, commonService);
                        logger.info("促销中的项目执行划扣金额:{},订单标识:{}",snapMoney,ordersTotal.getId());
                        //未执行划扣金额
                        userProjectItem.setNoDeductionAmount(snapMoney);
                        userProjectItem.setDeductionTotalAmount(snapMoney);
                    }
                    items = handCardPromotion(ordersTotal, operator, userMoney, userProjectItem, items, vo, orderItemSon,commonService,customParameter);
                }
            }
 
            String itemMoney = itemMap.get(vo.getCommonId());
            if(StringUtils.noNull(itemMoney)){
                BigDecimal userPaid=vo.getUserPaidTotal()==null?new BigDecimal(itemMoney):vo.getUserPaidTotal().add(new BigDecimal(itemMoney));
                vo.setUserPaidTotal(userPaid);
            }
            //更新子订单
            map.clear();
            map.put("payStatus",vo.getPayStatus());
            map.put("userPaidTotal",vo.getUserPaidTotal());
            map.put("id",vo.getId());
//            vo.setPayStatus(ordersTotal.getPayStatus());//支付状态,先暂定总订单支付状态
            sqlSentence.setSqlSentence(" payStatus=#{m.payStatus},userPaidTotal=#{m.userPaidTotal} WHERE id=#{m.id} and isDel=0");
            commonService.updateWhere(OrderItemMapper.class,sqlSentence);
//            orderItemService.updatePayStatus(vo);//更改子订单的支付状态
        }
        //生成商品提货单
        if(items!=null && items.size()>0){
            payRetail(ordersTotal, user, items,commonService);
        }
 
    }
 
    /**
     * 子订单-处理子订单
     * @param ordersTotal               总订单
     * @param itemMap                   一级子订单用户实际支付金额,该Map用于统计用户按照项目部分付款
     * @param operator                  操作人Map
     * @param userMoney                 用户资金对象
     * @param cardIds                   存储卡项id,用户判断用户是否使用的是卡包进行结算
     * @param commonService
     * @param customParameter
     */
    public static void payHandOrderItemNew(List<OrderItem> orderItemList,OrdersTotal ordersTotal, Map<String, String> itemMap, Map<String, String> operator, UserMoney userMoney, List<String> cardIds,
                                 CommonService commonService, CustomParameter customParameter) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        UserProjectItem userProjectItem = null;
        Date date = new Date();
        User user=commonService.selectOneByKey(UserMapper.class,ordersTotal.getUserId());
        List<PickUpGoodItem> items = null;
        PickUpGoodItem pickUpGoodItem;
 
        for(OrderItem vo:orderItemList){
            map.clear();
            userProjectItem = new UserProjectItem();
            map.put("orderItemId",vo.getId());
            map.put("isDel",BaseEntity.NO);
            sqlSentence.setSqlSentence("select * from order_item_source where isDel= #{m.isDel} and orderItemId=#{m.orderItemId}");
            List<OrderItemSon> orderItemSonList=commonService.selectList(OrderItemSonMapper.class,sqlSentence);
 
            //限制总表,查询该项目、商品、卡项、促销是否限制,有限制查看是否符合支付条件并对其限制
            JSONObject param = new JSONObject();
            param.put("commonId",vo.getCommonId());
            param.put("commonName",vo.getGoodsName());
            param.put("userId",ordersTotal.getUserId());
            param.put("shopId",ordersTotal.getDeveloperShopId());
            LimitPlatformUtil.limitMethod(commonService,param.toJSONString());
            //限制会员等级支付
            map.put("foreignKey",vo.getCommonId());
            checkMemberLevel(sqlSentence, user, vo.getType(),commonService);
 
            if(OrderItemConstants.TYPE_PROJECT.equals(vo.getType())){
                handleUserProject(ordersTotal, userProjectItem, date, vo,null,OrderItemConstants.TYPE_PROJECT,commonService);
            }else if(OrderItemConstants.TYPE_RETAIL.equals(vo.getType())){
                //处理商品信息,生成提货单
                // 此处商品不生成提货单
//                items=new ArrayList<>();
//                pickUpGoodItem=new PickUpGoodItem();
//                pickUpGoodItem.setConsumablesId(vo.getCommonId());
//                pickUpGoodItem.setNum(vo.getBuyNum());
//                pickUpGoodItem.setSalePrice(vo.getCurPrice());
//                pickUpGoodItem.setSalePrice(vo.getCurPrice());
//                items.add(pickUpGoodItem);
            }else if(OrderItemConstants.TYPE_CARD.equals(vo.getType())){
                //cardIds不为空表示使用卡项支付
                if(cardIds !=null && cardIds.size()>0 && cardIds.contains(vo.getCommonId())){
                    for(OrderItemSon orderItemSon:orderItemSonList){
                        items = handCardPromotion(ordersTotal, operator, userMoney, userProjectItem, items, vo, orderItemSon,commonService,customParameter);
                    }
                }else{
                    //卡包,生成用户卡包中的具体卡项记录
                    map.put("cardId",vo.getCommonId());
                    sqlSentence.setSqlSentence("select * from limit_total where isDel= #{m.isDel} and foreignKey=#{m.cardId} order by createTime desc limit 1");
                    LimitTotal limitTotal=commonService.selectOne(LimitTotalMapper.class,sqlSentence);
                    UserCard userCard = createUserCardItem(ordersTotal, vo, limitTotal);
                    commonService.insert(UserCardMapper.class,userCard);
                }
            }else if(OrderItemConstants.TYPE_PROMOTION.equals(vo.getType())){
                //处理促销,将促销的项目生成未划扣记录,商品生成提货单,增值金、储值金、积分给用户添加上
                if(orderItemSonList==null || orderItemSonList.size()==0){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账:购买促销时未找到该订单的二级子项");
                }
                for(OrderItemSon orderItemSon:orderItemSonList){
                    items = handCardPromotion(ordersTotal, operator, userMoney, userProjectItem, items, vo, orderItemSon,commonService,customParameter);
                }
            }
 
            String itemMoney = itemMap.get(vo.getCommonId());
            if(StringUtils.noNull(itemMoney)){
                BigDecimal userPaid=vo.getUserPaidTotal()==null?new BigDecimal(itemMoney):vo.getUserPaidTotal().add(new BigDecimal(itemMoney));
                vo.setUserPaidTotal(userPaid);
            }
            //更新子订单
            map.clear();
            map.put("payStatus",vo.getPayStatus());
            map.put("userPaidTotal",vo.getUserPaidTotal());
            map.put("id",vo.getId());
//            vo.setPayStatus(ordersTotal.getPayStatus());//支付状态,先暂定总订单支付状态
            sqlSentence.setSqlSentence(" payStatus=#{m.payStatus},userPaidTotal=#{m.userPaidTotal} WHERE id=#{m.id} and isDel=0");
            commonService.updateWhere(OrderItemMapper.class,sqlSentence);
//            orderItemService.updatePayStatus(vo);//更改子订单的支付状态
        }
        //生成商品提货单
        if(items!=null && items.size()>0){
            payRetail(ordersTotal, user, items,commonService);
        }
 
    }
 
    /**
     *  卡项/促销-处理卡项和促销结账完成后项目、商品、增值金、储值金、积分的具体操作
     * @param ordersTotal
     * @param operator
     * @param userMoney
     * @param userProjectItem
     * @param items
     * @param vo
     * @param orderItemSon
     * @param commonService
     * @param customParameter
     * @return
     */
    public static List<PickUpGoodItem> handCardPromotion(OrdersTotal ordersTotal, Map<String, String> operator, UserMoney userMoney, UserProjectItem userProjectItem,
                                                         List<PickUpGoodItem> items, OrderItem vo, OrderItemSon orderItemSon,CommonService commonService,CustomParameter customParameter) {
        Date date=new Date();
        PickUpGoodItem pickUpGoodItem;
        switch (orderItemSon.getType()){
            case OrderItemConstants.TYPE_PROJECT:
                //暂时不处理,全部由同步中心处理
//                handleUserProject(ordersTotal, userProjectItem, date, vo,orderItemSon,OrderItemConstants.TYPE_PROMOTION,commonService);
                break;
            case OrderItemConstants.TYPE_RETAIL:
                items=new ArrayList<>();
                pickUpGoodItem=new PickUpGoodItem();
                pickUpGoodItem.setConsumablesId(orderItemSon.getGoodsId());
                pickUpGoodItem.setNum(orderItemSon.getBuyNum());
                pickUpGoodItem.setSalePrice(orderItemSon.getCurPrice());
                pickUpGoodItem.setSalePrice(orderItemSon.getCurPrice());
                items.add(pickUpGoodItem);
                break;
            case PayMethodTypeConstants.PAY_ADD_FUND://增加增值金
                UserMoneyUtil.setUserMoneyUnclaimed(ordersTotal,orderItemSon.getOrderId(),orderItemSon.getCurPrice(), UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND,OperationReasonConstants.OP_REASON_CARD_PROMOTION,commonService,UserMoneyUnclaimed.YES);
                break;
            case PayMethodTypeConstants.PAY_STORED://增加储值金
                UserMoneyUtil.setUserMoneyUnclaimed(ordersTotal,ordersTotal.getId(),orderItemSon.getCurPrice(), UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND,OperationReasonConstants.OP_REASON_CARD_PROMOTION,commonService,UserMoneyUnclaimed.NO);
                break;
            case PayMethodTypeConstants.PAY_INTEGRAL://积分
                UserMoneyUtil.setUserMoneyUnclaimed(ordersTotal,ordersTotal.getId(),orderItemSon.getCurPrice(), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_CARD_PROMOTION,commonService,UserMoneyUnclaimed.NO);
                break;
        }
        return items;
    }
 
    /**
     * 卡包-记录用户卡包使用具
     * @param ordersTotal     体组合项记录   总订单
     * @param commonId          卡项组合项标识
     * @param cardEquityId      权益id
     * @param userCardId        用户卡包标识
     * @return
     */
    public static String  payCard(OrdersTotal ordersTotal, String commonId, String cardEquityId, String userCardId,CustomParameter customParameter,CommonService commonService) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        UserCardUsed userCardUsed;
        sqlSentence.setM(map);
        map.put("isDel", BaseEntity.NO);
        map.put("commonId",commonId);
        map.put("cardEquityId",cardEquityId);
        map.put("cardId",userCardId);
        map.put("orderId",ordersTotal.getId());
        UserCard userCard=commonService.selectOneByKey(UserCardMapper.class,userCardId);
        if(userCard==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:未找到该用户卡包信息");
        }
        //查出用户,commonId:卡项的组合项标识
        CardItemInfo cardItemInfo=commonService.selectOneByKey(CardItemInfoMapper.class,commonId);
        if(cardItemInfo ==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:未找到该卡项的组合项");
        }
 
        CardEquity cardEquity=commonService.selectOneByKey(CardEquityMapper.class,cardItemInfo.getCardEquityId());
        //查询一级子订单
        sqlSentence.setSqlSentence("SELECT * FROM order_item WHERE userCardId=#{m.cardId} and orderId=#{m.orderId} and isDel=#{m.isDel}");
        OrderItem orderItem=commonService.selectOne(OrderItemMapper.class,sqlSentence);
        map.put("orderItemId",orderItem.getId());
        //查询该订单选中的二级子订获取订单购买数量
        sqlSentence.setSqlSentence("SELECT * FROM order_item_source WHERE cardEquityId=#{m.cardEquityId} and cardItemInfoId=#{m.commonId} and orderItemId=#{m.orderItemId} and isDel=#{m.isDel}");
        OrderItemSon orderItemSon=commonService.selectOne(OrderItemSonMapper.class,sqlSentence);
        if(orderItemSon==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:未找到用户选定的项目");
        }
        Integer sumNum=orderItemSon.getBuyNum()==null?0:orderItemSon.getBuyNum();
        if(CardEquity.EQUITY_TYPE_TIME_CARD.equals(cardEquity.getEquityType())){
            //权益类型是次卡,获取使用的总次数
            sqlSentence.setSqlSentence("select * FROM user_card_used WHERE  cardEquityId=#{m.cardEquityId} and userCardId=#{m.cardId} and isDel=#{m.isDel}");
            //根据cardItemIfo标识查询用户使用记录
            List<UserCardUsed> userCardUseds = commonService.selectList(UserCardUsedMapper.class, sqlSentence);
            //使用次数
            Integer usedNum = userCardUseds.stream().collect(Collectors.summingInt(o -> o.getEveryDrawNum()));
            //次卡的剩余次数=总次数-权益总次数
            Integer laveNum=cardEquity.getValue()-usedNum;
            //次卡:总次数=开单的总次数*每次划扣的次数
            sumNum=sumNum*cardItemInfo.getEveryDrawNum();
            if(sumNum>laveNum){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:卡项的次卡使用次数不够");
            }else if(sumNum<=0){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:用户选择的订单次数为"+sumNum);
            }
//            sqlSentence.setSqlSentence("select usedNum,commonId,id,hisId FROM user_card_item WHERE  cardEquityId=#{m.cardEquityId} and userCardId=#{m.cardId} and isDel=#{m.isDel}");
//            List<UserCardItem> userCardItems=commonService.selectList(UserCardItemMapper.class,sqlSentence);
//            if(userCardItems!=null && userCardItems.size()>0){
//                //领建已经使用次数
//                Integer collarBuild = userCardItems.stream().collect(Collectors.summingInt(o -> o.getUsedNum()));
//                //次卡:总次数=开单的总次数*每次划扣的次数,领建剩余次数
//                Integer collarBuildLaveNum=cardEquity.getValue()-collarBuild;
//                if(sumNum>collarBuildLaveNum){
//                    logger.info("卡项结账提示:用户选择该卡包次卡次数不足,请排查!,购买次数:{},剩余次数:{},卡项划扣次数:{},订单标识:{}",sumNum,collarBuildLaveNum,collarBuildLaveNum,ordersTotal.getId());
////                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:用户选择该卡包次卡次数不足,请排查!");
//                }
//                List<UserCardItem> userCardItemList = userCardItems.stream().filter(o -> o.getCommonId().equals(orderItemSon.getGoodsId())).collect(Collectors.toList());
//                if(userCardItemList!=null && userCardItemList.size()==1){
//                    SynOrderUtil.updateUserCard(userCardItemList.get(0).getHisId(),sumNum,customParameter);
//                }else{
//                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:找到多条或者未找到领建使用记录,请排查!");
//                }
//            }else{
//                logger.info("未找到用户领建次卡卡包记录信息,sql:{},M:{}",sqlSentence.getSqlSentence(),sqlSentence.getM());
//                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:未找到用户领建卡包记录信息,请排查!");
//            }
 
            for(int i=0;i<sumNum;i++){
                userCardUsed  = getUserCardUsed(ordersTotal.getId(),UserCardUsed.SOURCE_TYPE_ORDER_ITEM_TWO
                        ,orderItemSon.getId(), userCard, cardItemInfo, cardEquity);
                commonService.insert(UserCardUsedMapper.class,userCardUsed);
            }
        }else{
            if(CardEquity.EQUITY_TYPE_N_M.equals(cardEquity.getEquityType())){
                //根据卡包id查询使用记录
                sqlSentence.setSqlSentence("select * FROM user_card_used WHERE userCardId=#{m.cardId} and cardEquityId=#{m.cardEquityId} and isDel=#{m.isDel}");
                logger.info("sql:{},M:{},value:{}",sqlSentence.getSqlSentence(),sqlSentence.getM(),cardEquity.getValue());
                List<UserCardUsed> cardUseds=commonService.selectList(UserCardUsedMapper.class, sqlSentence);
                if(cardUseds!=null && cardUseds.size()>0 ){
                    List<String> commonIds = cardUseds.stream().map(o -> o.getCommonId()).distinct().collect(Collectors.toList());
                    if(commonIds.size() > cardEquity.getValue() && !commonIds.contains(commonId)){
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:不符合N选M规则,请重试");
                    }
                }
 
                if(sumNum > cardItemInfo.getMaxNum()){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:数量不足,订单总次数:"+sumNum+"卡项最大次数:"+cardItemInfo.getMaxNum());
                }else if(sumNum<=0){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:用户选择的订单次数为"+sumNum);
                }
            }
            //权益类型不是次卡,获取使用的总次数
            sqlSentence.setSqlSentence("select COUNT(*) FROM user_card_used WHERE cardItemInfoId =#{m.commonId}  and cardEquityId=#{m.cardEquityId} and userCardId=#{m.cardId} and isDel=#{m.isDel}");
            //根据cardItemIfo标识查询用户使用记录
            int usedNum=commonService.selectCountSql(UserCardUsedMapper.class, sqlSentence);
            //剩余次数
            int laveNum = cardItemInfo.getMaxNum() - usedNum;
            if(sumNum>laveNum){
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:卡项的该组合项使用次数不够,已使用次数:"+usedNum+",剩余次数:"+laveNum+",卡项最大次数:"+cardItemInfo.getMaxNum());
            }
 
//            sqlSentence.setSqlSentence("select usedNum,commonId,id,hisId FROM user_card_item WHERE  cardEquityId=#{m.cardEquityId} and userCardId=#{m.cardId} and cardItemInfoId=#{m.commonId} and isDel=#{m.isDel}");
//            List<UserCardItem> userCardItems=commonService.selectList(UserCardItemMapper.class,sqlSentence);
//            if(userCardItems!=null && userCardItems.size()>0){
//                //领建已经使用次数
//                Integer collarBuild = userCardItems.stream().collect(Collectors.summingInt(o -> o.getUsedNum()));
//                //剩余可划扣次数=卡项最大次数-领建已经使用次数
//                Integer collarBuildLaveNum=cardItemInfo.getMaxNum()-collarBuild;
//                if(sumNum>collarBuildLaveNum){
//                    logger.info("卡项结账提示:用户选择该卡包N/M或者固定次数不足,请排查!,购买次数:{},剩余次数:{},卡项划扣次数:{},订单标识:{}",sumNum,collarBuildLaveNum,collarBuildLaveNum,ordersTotal.getId());
////                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:用户选择该N/M或者固定次卡次数不足,请排查!");
//                }
//                List<UserCardItem> userCardItemList = userCardItems.stream().filter(o -> o.getCommonId().equals(orderItemSon.getGoodsId())).collect(Collectors.toList());
//                if(userCardItemList!=null && userCardItemList.size()==1){
//                    SynOrderUtil.updateUserCard(userCardItemList.get(0).getHisId(),sumNum,customParameter);
//                }else{
//                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:找到多条或者未找到领建使用记录,请排查!");
//                }
//            }else{
//                logger.info("未找到用户领建卡包记录信息,sql:{},M:{}",sqlSentence.getSqlSentence(),sqlSentence.getM());
//                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"卡项结账提示:未找到用户领建卡包记录信息,请排查!");
//            }
            for(int i=0;i<sumNum;i++){
                userCardUsed  = getUserCardUsed(ordersTotal.getId(),UserCardUsed.SOURCE_TYPE_ORDER_ITEM_TWO
                        ,orderItemSon.getId(), userCard, cardItemInfo, cardEquity);
                commonService.insert(UserCardUsedMapper.class,userCardUsed);
            }
        }
        return userCard.getCardItemId();
    }
 
    /**
     * 卡包-创建卡包记录对象
     * @param ordersTotal           总订单
     * @param vo                    一级子订单
     * @param limitTotal            总限制表
     * @return
     */
    public static UserCard createUserCardItem(OrdersTotal ordersTotal, OrderItem vo, LimitTotal limitTotal) {
        UserCard userCard = new UserCard();
        userCard.setCode(vo.getGoodsNo());
        userCard.setCardItemId(vo.getCommonId());
        userCard.setUserId(ordersTotal.getUserId());
        userCard.setEffectiveStatus(BaseEntity.YES);
        userCard.setEffectiveStartTime(limitTotal==null ?new Date():limitTotal.getStartTime());
        userCard.setEffectiveEndTime(limitTotal==null ?new Date():limitTotal.getEndTime());
        userCard.setHisOrderId(ordersTotal.getHisOrderId());
        return userCard;
    }
 
    /**
     * 卡包- 创建用户卡包使用记录对象(该废弃)
     * @param orderId               订单id
     * @param userCard              用户卡包
     * @param cardItemInfo          卡项组合项
     * @param cardEquity            权益类型对象
     * @return
     */
    public static UserCardUsed getUserCardUsed(String orderId,Integer sourceType,String sourceId, UserCard userCard
            , CardItemInfo cardItemInfo, CardEquity cardEquity) {
        UserCardUsed userCardUsed=new UserCardUsed();
        userCardUsed.setEquityType(cardEquity.getEquityType());
        userCardUsed.setGroupName(cardEquity.getGroupName());
        userCardUsed.setCommonId(cardItemInfo.getCommonId());
        userCardUsed.setCommonName(cardItemInfo.getCommonName());
        userCardUsed.setCommonType(cardItemInfo.getCommonType());
        userCardUsed.setPrice(cardItemInfo.getPrice());
        userCardUsed.setUsedNum(cardItemInfo.getMaxNum()==null?cardItemInfo.getEveryDrawNum():1);
        userCardUsed.setEmResultsNum(cardItemInfo.getEmResultsNum());
        userCardUsed.setShareMoney(cardItemInfo.getShareMoney());
        userCardUsed.setEveryDrawNum(cardItemInfo.getEveryDrawNum());
        userCardUsed.setEveryShareMoney(cardItemInfo.getEveryShareMoney());
        userCardUsed.setUserCardCode(userCard.getCode());
        userCardUsed.setUserCardId(userCard.getId());
        userCardUsed.setSourceType(sourceType);
        userCardUsed.setSourceId(sourceId);
        userCardUsed.setOrderId(orderId);
        userCardUsed.setCardEquityId(cardEquity.getId());
        userCardUsed.setCardItemInfoId(cardItemInfo.getId());
        return userCardUsed;
    }
 
 
    /**
     * 用户划扣项目-处理用户项目方法(生成userProject表)
     * @param ordersTotal       订单总表
     * @param userProjectItem   用户子项目表
     * @param date              当前时间
     * @param vo                一级子订单
     * @param type              卡项/促销,根据判断该类型是根据二级子订单生成用户划扣项目还是一级子订单
     */
    public static void handleUserProject(OrdersTotal ordersTotal, UserProjectItem userProjectItem, Date date, OrderItem vo,OrderItemSon orderItemSon,String type,CommonService commonService) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        map.put("userId",ordersTotal.getUserId());
        sqlSentence.setSqlSentence("select * from user_project where goodsId=#{m.commonId} and userId =#{m.userId} and isDel=0");
        List<String> typeList = Arrays.asList(OrderItemConstants.TYPE_CARD, OrderItemConstants.TYPE_PROMOTION);
 
        if(typeList.contains(type)){
            map.put("commonId",orderItemSon.getGoodsId());
            UserProject userProject=commonService.selectOne(UserProjectMapper.class,sqlSentence);
            if(userProject==null){
                userProject=new UserProject();
                setUserProject(ordersTotal, userProject, vo,orderItemSon,1);
//                commonService.insert(UserProjectMapper.class,userProject);
            }else {
                userProject.setUsedTotal(userProject.getUsedTotal()+orderItemSon.getUsedTotal());
                userProject.setNotUsedNum(userProject.getNotUsedNum()+orderItemSon.getUsedTotal());
//                commonService.updateAll(UserProjectMapper.class,userProject);
            }
            setUserProjectItem(ordersTotal, userProject, userProjectItem, date, vo,orderItemSon,1);
//            commonService.insert(UserProjectItemMapper.class,userProjectItem);//新增用户项目子项记录
        }else{
            map.put("commonId",vo.getCommonId());
            UserProject userProject=commonService.selectOne(UserProjectMapper.class,sqlSentence);
            if(userProject==null){
                userProject=new UserProject();
                setUserProject(ordersTotal, userProject, vo,orderItemSon,0);
//                commonService.insert(UserProjectMapper.class,userProject);
            }else {
                userProject.setUsedTotal(userProject.getUsedTotal()+vo.getUsedTotal());
                userProject.setNotUsedNum(userProject.getNotUsedNum()+vo.getUsedTotal());
//                commonService.updateAll(UserProjectMapper.class,userProject);
            }
            setUserProjectItem(ordersTotal, userProject, userProjectItem, date, vo,orderItemSon,0);
//            commonService.insert(UserProjectItemMapper.class,userProjectItem);//新增用户项目子项记录
        }
    }
 
    /**
     * 用户划扣项目-设值未划扣记录
     * @param ordersTotal       总订单
     * @param userProject       用户划扣总记录
     * @param vo                一级子订单
     * @param son               二级子订单
     * @param type              0:读取一级子订单(项目、商品),1:读取二级子订单:促销/卡项
     */
    public static void setUserProject(OrdersTotal ordersTotal, UserProject userProject, OrderItem vo,OrderItemSon son,Integer type) {
        List<String> typeList= Arrays.asList(OrderItemConstants.TYPE_CARD, OrderItemConstants.TYPE_PROMOTION, OrderItemConstants.CARD_BAG);
        Integer buyNum=typeList.contains(vo.getType())?son.getBuyNum():vo.getBuyNum();
        userProject.setType(type==0?vo.getType():son.getType());
        userProject.setGoodsNo(type==0?vo.getGoodsNo():son.getGoodsNo());
        userProject.setGoodsId(type==0?vo.getCommonId():son.getGoodsId());
        userProject.setEffectiveStatus(UserProjectConstants.EFF_STATUS_YES);
        userProject.setUsedTotal(type==0?buyNum*vo.getUsedTotal():buyNum*son.getUsedTotal());
        userProject.setNotUsedNum(type==0?buyNum*vo.getUsedTotal():buyNum*son.getUsedTotal());
        userProject.setUsedNum(0);
        userProject.setOverdueNum(0);
        userProject.setTransferNum(0);
        userProject.setCancelNum(0);
        userProject.setUserId(ordersTotal.getUserId());
        userProject.setGoodsName(type==0?vo.getGoodsName():son.getGoodsName());
    }
 
    /**
     * 用户划扣项目-设值未划扣记录子项
     * @param ordersTotal           总订单
     * @param userProject           用户总划扣
     * @param userProjectItem       用户子划扣
     * @param date                  当前时间
     * @param vo                    一级子订单
     * @param son                   二级子订单
     * @param type                  0:读取一级子订单(项目、商品),1:读取二级子订单:促销/卡项
     */
    public static void setUserProjectItem(OrdersTotal ordersTotal, UserProject userProject, UserProjectItem userProjectItem, Date date, OrderItem vo,OrderItemSon son,Integer type) {
        List<String> typeList= Arrays.asList(OrderItemConstants.TYPE_CARD, OrderItemConstants.TYPE_PROMOTION, OrderItemConstants.CARD_BAG);
        Integer buyNum=typeList.contains(vo.getType())?son.getBuyNum():vo.getBuyNum();
        userProjectItem.setTotal(type==0?vo.getTotal():son.getTotal());//子项总金额
        userProjectItem.setActualTotal(type==0?vo.getActualTotal():son.getActualTotal());//子项支付总金额
        userProjectItem.setOriPrice(type==0?vo.getOriPrice():son.getOriPrice());//原价
        userProjectItem.setCurPrice(type==0?vo.getCurPrice():son.getCurPrice());//现价
        userProjectItem.setBuyNum(type==0?vo.getBuyNum():son.getBuyNum());//数量
        userProjectItem.setUsedTotal(type==0?buyNum*vo.getUsedTotal():buyNum*son.getUsedTotal());//总次数
        userProjectItem.setNotUsedNum(type==0?buyNum*vo.getUsedTotal():buyNum*son.getUsedTotal());//未使用次数(户口的时候需要相应扣减)
        userProjectItem.setUsedNum(0);//已使用次数
        userProjectItem.setEffectiveStatus(UserProjectConstants.EFF_STATUS_YES);//是否有效,结账默认项目和商品有效,套餐卡项暂定
        userProjectItem.setTimeLimit(0);//是否有效时间限制,目前项目和商品没有时间限制,套餐和卡项暂定
        userProjectItem.setLimitStartTime(date);//有效开始时间,系统当前时间
        userProjectItem.setLimitEndTime(date);//有效结束时间,系统当前时间,项目和商品是没有时间限制的,所以默认系统当前时间,如果是套餐和卡项就填套餐和卡项的有效时间
        userProjectItem.setCommonType(OrderSourceConstans.TYPE_PROJECT);//项目和商品是来源于一级子订单,套餐和卡项即使二级子订单
        userProjectItem.setCommonId(type==0?vo.getId():son.getId());//类型是一级子订单,该字段就是一级子订单标识,二级也是如此
        userProjectItem.setUsedOne(type==0?vo.getSingle():son.getUsedOne());//单次疗程数量
        userProjectItem.setUserProjectId(userProject.getId());//用户项目id
        userProjectItem.setUserId(ordersTotal.getUserId());//用户id
        userProjectItem.setOrderItemId(vo.getId()); // 存OrderItemId
        userProjectItem.setDepartmentCode(ordersTotal.getDepartmentCode());//科室编码
        userProjectItem.setDepartmentName(ordersTotal.getDepartmentName());//科室名称
        userProjectItem.setShopId(ordersTotal.getShopId());//操作人门店id
        userProjectItem.setShopName(ordersTotal.getShopName());//操作人门店名称
        userProjectItem.setBodyPartsId(type==0?vo.getBodyPartsId():son.getBodyPartsId());//身体部位id
        userProjectItem.setBodyPartsName(type==0?vo.getBodyPartsName():son.getBodyPartsName());//身体部位名称
    }
 
    /**
     * 商品-生成商品提货单
     * @param ordersTotal
     * @param user
     * @param items
     */
    public static void payRetail(OrdersTotal ordersTotal, User user, List<PickUpGoodItem> items,CommonService commonService) {
        PickUpGood pickUpGood = new PickUpGood();
        pickUpGood.setUserId(ordersTotal.getUserId());
        pickUpGood.setSex(user.getGender());
        pickUpGood.setShopId(ordersTotal.getShopId());
        pickUpGood.setDoctorId(ordersTotal.getDoctorId());
        pickUpGood.setItems(items);
        //生成商品提货单
        PickUpGoodTool.createPickUpGood(pickUpGood,commonService);
    }
 
    /**
     * 消费记录-创建消费记录对象
     * @param ordersTotal       总订单
     * @return
     */
    public static RecordConsume setRecordConsume(OrdersTotal ordersTotal) {
        Integer status=ordersTotal.getStatus() == OrderTotalConstants.STATUS_ARREARS ? RecordConsumeConstants.STATUS_PAID_ARREDRS:RecordConsumeConstants.STATUS_PAID;
 
        RecordConsume recordConsume=new RecordConsume();
        recordConsume.setStatus(status);//状态
        recordConsume.setConsumeTotal(ordersTotal.getShouldTotal());//应付总金额
        recordConsume.setConsumeMoney(ordersTotal.getActualTotal());//实付金额
        recordConsume.setPayMoney(ordersTotal.getPayTotal().add(ordersTotal.getPayIncrement()).add(ordersTotal.getPayRecharge()));//支付总金额
        recordConsume.setThirdPartyFund(ordersTotal.getPayTotal());//第三方金额
        recordConsume.setStoredFund(ordersTotal.getPayRecharge());//储值金额
        recordConsume.setIncrementFund(ordersTotal.getPayIncrement());//增值金额
        recordConsume.setRefundTotal(BigDecimal.ZERO);//退款金额
        recordConsume.setThirdPartyRefund(BigDecimal.ZERO);//第三方退款金额
        recordConsume.setStoredRefund(BigDecimal.ZERO);//储值金
        recordConsume.setIncrementRefund(BigDecimal.ZERO);//增值金
        recordConsume.setRemarks(ordersTotal.getRemarks());//备注
        recordConsume.setShopId(ordersTotal.getShopId());//门店
        recordConsume.setShopName(ordersTotal.getShopName());
        recordConsume.setOrderNo(ordersTotal.getOrderNo());//订单编号
        recordConsume.setOrderTime(ordersTotal.getCreateTime());//开单日期
        recordConsume.setCommonType(RecordConsumeConstants.COMMON_TYPE_ORDER);
        recordConsume.setCommonId(ordersTotal.getId());//订单id
        recordConsume.setUserId(ordersTotal.getUserId());//用户id
        return recordConsume;
    }
 
    /**
     * 结账-处理优惠券
     * @param userCouponId      用户优惠券标识
     * @param orderItemList     一级子订单
     * @param commonService
     * @return
     */
    public static BigDecimal handCoupon(String userCouponId, List<OrderItem> orderItemList,String orderId,BigDecimal userAmount,User user,CommonService commonService, FGoodsSkuService fGoodsSkuService) {
//        List<String> platfromTypeList = Arrays.asList(PlatformConstants.TYPE_PLATFORM_PHIS, PlatformConstants.TYPE_PLATFORM_HIS, PlatformConstants.TYPE_PLATFORM_GUIDE);
        //注意:优惠券不能让卡项和促销使用,判断该订单是否有促销和卡项
//        List<String> cardPromotions = Arrays.asList(OrderItemConstants.TYPE_CARD, OrderItemConstants.TYPE_PROMOTION);
//        List<String> orderItemTypes = orderItemList.stream().map(o -> o.getType()).distinct().collect(Collectors.toList());
//        //通过工具类求交集能购买的限制标签集合和用户已有的标签集合
//        Collection intersection = CollectionUtils.intersection(cardPromotions, orderItemTypes);
//        if(intersection.size()>0){
//            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账-优惠券:该订单包含卡项/促销商品,该订单不能使用优惠券");
//        }
 
        //查看用户是否有优惠券
        CouponNumber couponNumber = commonService.selectOneByKey(CouponNumberMapper.class, userCouponId);
        if(couponNumber==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠卷:该用户没有优惠券");
        }
        //查看用户是否有优惠券
        Coupon coupon = commonService.selectOneByKey(CouponMapper.class, couponNumber.getCouponId());
        if(coupon==null){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠卷:未找到优惠券信息");
        }
 
        List<String> orderItemIds = new ArrayList<>();
        List<CouponGoodsDto> couponGoodsList= new ArrayList();
        CouponGoodsDto dto;
        for (OrderItem orderItem : orderItemList) {
            dto=new CouponGoodsDto();
            orderItemIds.add(orderItem.getCommonId());
            dto.setHisId(orderItem.getCommonId());
            dto.setType(orderItem.getType());
            couponGoodsList.add(dto);
        }
 
        //优惠券限制项目、商品、卡项、促销调用阿琪接口,在调用此方法之前就需要判断是否能用      2022-10-20
        boolean isCanUse = checkCouponIsUse(commonService, fGoodsSkuService, couponNumber, coupon, couponGoodsList);
        if(!isCanUse){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠卷提醒:该订单不符合优惠券规则,请检查优惠券配置信息!");
        }
 
        //优惠券限制项目、商品、卡项、促销调用阿琪接口判断,以下判断屏蔽
//        boolean isPass= checkUserCoupon(coupon, orderItemList);
//        if(isPass){
//            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠卷提醒:该订单不符合使用优惠券条件,请检查优惠券信息是否有禁用!");
//        }
        //处理优惠卷-将用户实际支付总金额计算出使用优惠券之后具体优惠的金额
        CouponOrderDiscountLog couponOrderDiscountLog = CouponTool.useCoupon(orderItemIds, userAmount, couponNumber, commonService, orderId);
 
        CouponTool.payCoupon(orderItemIds,couponNumber,commonService);
 
        //线下券核销
        if(coupon.getIssueType() !=null && BaseEntity.YES==coupon.getIssueType()){
            CouponTool.getOfflineCoupon(commonService,couponNumber.getId(),user.getId());
        }
 
        //将总订单处理后的优惠券的总金额返回
        return couponOrderDiscountLog.getDiscountTotal();
    }
 
    public static boolean checkCouponIsUse(CommonService commonService, FGoodsSkuService fGoodsSkuService, CouponNumber couponNumber, Coupon coupon, List<CouponGoodsDto> couponGoodsList) {
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> map=new HashMap<>();
        sqlSentence.setM(map);
        map.put("couponId",coupon.getId());
        map.put("isDel", BaseEntity.NO);
        sqlSentence.setSqlSentence("select * from coupon_appoint where couponId=#{m.couponId} and isDel=#{m.isDel} ");
        List<CouponAppoint> couponAppointMappers = commonService.selectList(CouponAppointMapper.class, sqlSentence);
 
        List<CouponAppointDto> couponAppointDtos=new ArrayList<>();
        if(couponAppointMappers!=null && couponAppointMappers.size()>0){
            couponAppointDtos=couponAppointMappers.stream().map(e->{
                CouponAppointDto d=new CouponAppointDto();
                BeanUtils.copyProperties(e,d);
                return d;
            }).collect(Collectors.toList());
        }
 
        CouponCheckDto couponCheckDto = new CouponCheckDto();
        CouponInfoDto couponInfoDto = new CouponInfoDto();
 
        //拷贝优惠券
        BeanUtils.copyProperties(coupon,couponInfoDto);
 
        couponCheckDto.setCoupon(couponInfoDto);
        couponCheckDto.setGoodsList(couponGoodsList);
        couponCheckDto.setCouponAppoint(couponAppointDtos);
        logger.info("请求阿琪校验优惠券接口是否使用优惠券,参数:{}",JSONObject.toJSONString(couponCheckDto));
        Result result = fGoodsSkuService.goodsCheckType(couponCheckDto);
        if (result != null) {
            logger.info("阿琪校验优惠券接口是否使用优惠券,返回:{}",JSONObject.toJSONString(result));
            result.checkTips();
            JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(result.getData()));
            if(object.isEmpty()){
                return false;
            }else {
                boolean isCanUse =(boolean) object.get("isCanUse");
                return isCanUse;
            }
        } else {
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"校验优惠券失败[037]!");
        }
 
    }
 
    /**
     * 结账-计算划扣未执行金额
     * map里参数:
     *      // snapPayTotal      划扣现金总金额
     *      // userCardId        用户卡包标识
     * @return
     */
    public static BigDecimal noSnapMoney(OrdersTotal ordersTotal,OrderItem item,OrderItemSon itemSon,Map<String,Object> map,CommonService commonService) {
        if(map.isEmpty()){
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账提示:计算划扣未执行金额方法参数为空");
        }
        BigDecimal snapPayTotal= (BigDecimal) map.get("snapPayTotal");
        String userCardId= (String) map.get("userCardId");
        SqlSentence sqlSentence = new SqlSentence();
        Map<String,Object> sqlMap=new HashMap<>();
        sqlSentence.setM(sqlMap);
        //划扣比例=现金总金额➗订单总金额
        BigDecimal proportion=BigDecimal.ZERO;
        //未执行划扣金额=实付金额 * 划扣比例
        BigDecimal snapMoney=BigDecimal.ZERO;
        switch (item.getType()){
            case OrderItemConstants.TYPE_PROJECT:
                /*划扣现金比例=支付现金总金额➗订单应付总金额按照这样来搞
                *   普通订单购买项目:
                *           划扣现金比例=支付现金总金额➗订单实收总金额
                *           未执行划扣金额=(项目实付总金额 * 划扣现金比例) * 开单数量
                * */
                proportion=BigDecimal.ZERO.compareTo(ordersTotal.getShouldTotal()) ==0?BigDecimal.ZERO:BigDecimal.ZERO.compareTo(snapPayTotal)==0?BigDecimal.ZERO:snapPayTotal.divide(ordersTotal.getShouldTotal(),2,BigDecimal.ROUND_HALF_UP);
                snapMoney=item.getCurPrice().multiply(proportion).multiply(BigDecimal.valueOf(item.getBuyNum()));
                break;
            case OrderItemConstants.TYPE_PROMOTION:
//                /*三少说促销项目按照普通购买项目计算
//                 *   普通订单购买项目:
//                 *           划扣现金比例=支付现金总金额➗订单实收总金额
//                 *           未执行划扣金额=(项目实付总金额 * 划扣现金比例) * 开单数量
//                 * */
//                proportion=snapPayTotal.divide(ordersTotal.getShouldTotal(),2,BigDecimal.ROUND_HALF_UP);
//                snapMoney=itemSon.getActualTotal().multiply(proportion).multiply(BigDecimal.valueOf(itemSon.getBuyNum()));
                /*
                * 荣爷说促销就按照项目的折后价格
                * */
                snapMoney=itemSon.getActualTotal();
                break;
            case OrderItemConstants.CARD_BAG:
                /*
                * 先找到开卡订单,查看是否有用优惠券、折扣,荣爷说目前先按照已有卡项
                * */
                UserCard userCard=commonService.selectOneByKey(UserCardMapper.class,userCardId);
//                if(userCard ==null){
//                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账提示:计算未执划扣行金额方法未找到用户卡包信息");
//                }
//                if(StringUtils.noNull(userCard.getHisOrderId())){
                    /*
                    * 没有用优惠券:每次卡项分摊金额=卡项分摊金额➗最大次数,
                      如果有用优惠券:
                            卡项分摊金额比例=划扣现金金额 ➗ 卡项金额
                            每次卡项分摊金额=(卡项分摊金额*卡项分摊金额比例)➗ 最大次数或者每次划扣次数
                    * */
//                    sqlMap.put("hisOrderId",userCard.getHisOrderId());
//                    sqlSentence.setSqlSentence("select * from orders_total where hisOrderId=#{m.hisOrderId}");
//                    OrdersTotal order=commonService.selectOne(OrdersTotalMapper.class,sqlSentence);
//                    if(order==null){
//                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账提示:计算未执划扣行金额方法根据用户卡包领建订单标识未找到预约订单信息");
//                    }else{
                        /*
                        * 找到购买卡项订单的应付总金额(该金额已去除优惠券、整单折扣)
                        * 划扣金额比例=现金支付总金额➗订单应付总金额 (保留两位小数)
                        * */
                        proportion=BigDecimal.ZERO.compareTo(ordersTotal.getShouldTotal())==0?BigDecimal.ZERO:BigDecimal.ZERO.compareTo(snapPayTotal)==0?BigDecimal.ZERO:snapPayTotal.divide(ordersTotal.getShouldTotal(),2,BigDecimal.ROUND_HALF_UP);
                        /*
                        * 每次划扣金额=(卡项明细分摊金额 * 划扣金额比例)➗ 最大次数或者每次划扣次数  (保留两位小数)
                        * 未执行金额=每次划扣金额 * 开单数
                        * */
                        //查询卡项明细
                        CardItemInfo cardItemInfo=commonService.selectOneByKey(CardItemInfoMapper.class,itemSon.getCardItemInfoId());
                        if(cardItemInfo==null){
                            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账提示:计算未执划扣行金额方法根据订单信息找不到具体卡项明细");
                        }else {
                            //卡项明细分摊金额
                            BigDecimal shareMoney=cardItemInfo.getShareMoney()==null?cardItemInfo.getEveryShareMoney():cardItemInfo.getShareMoney();
                            //卡项明细最大次数
                            Integer cardNum=cardItemInfo.getMaxNum()==null?cardItemInfo.getEveryDrawNum():cardItemInfo.getMaxNum();
                            //每次划扣金额
                            BigDecimal everySnapMoney=shareMoney.multiply(proportion).divide(BigDecimal.valueOf(cardNum),2,BigDecimal.ROUND_HALF_UP);
                            snapMoney=everySnapMoney.multiply(BigDecimal.valueOf(itemSon.getBuyNum()));
                        }
//                    }
 
//                }else{
//                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账提示:计算未执划扣行金额方法该用户卡包信息没有找到领建订单标识");
//                }
                break;
            default:break;
        }
 
        return snapMoney;
    }
 
    /**
     * 检查优惠券是否能使用
     * @param coupon
     * @param orderItemList
     */
    private static boolean checkUserCoupon(Coupon coupon, List<OrderItem> orderItemList) {
        boolean isPass=false;
        for (OrderItem orderItem : orderItemList) {
            if(OrderItemConstants.TYPE_PROJECT.equals(orderItem.getType()) && coupon.getUseProjectType()==Coupon.TYPE_CANCEL){
                isPass=true;
                return isPass;
            }else if(OrderItemConstants.TYPE_RETAIL.equals(orderItem.getType()) && coupon.getUseGoodsType()==Coupon.TYPE_CANCEL){
                isPass=true;
                return isPass;
            }else if(OrderItemConstants.TYPE_PROMOTION.equals(orderItem.getType()) && coupon.getUsePromotionType()==Coupon.TYPE_CANCEL){
                isPass=true;
                return isPass;
            }else if(OrderItemConstants.TYPE_CARD.equals(orderItem.getType()) && coupon.getUseCardType()==Coupon.TYPE_CANCEL){
                isPass=true;
                return isPass;
            }
        }
        return isPass;
    }
}