ANDRU-PC\Andru
2023-10-08 572fd8325c78965f462cc19847033dac86fc5be6
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
package com.hx.phip.service.order.impl;
 
import com.alibaba.fastjson.JSON;
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.*;
import com.hx.phiappt.constants.tool.model.MessageTemplate;
import com.hx.phiappt.constants.tool.order.OrderUtil;
import com.hx.phiappt.constants.tool.user.UserLabelTool;
import com.hx.phiappt.model.*;
import com.hx.phiappt.model.consume.ConsumePay;
import com.hx.phiappt.model.coupon.Coupon;
import com.hx.phiappt.model.coupon.CouponNumber;
import com.hx.phiappt.model.coupon.CouponOrderDiscountLog;
import com.hx.phiappt.model.memberLevel.MemberLevel;
import com.hx.phiappt.model.order.*;
import com.hx.phiappt.model.user.UserProjectItem;
import com.hx.phiappt.tool.CouponCheckTool;
import com.hx.phip.config.ApproveConfig;
import com.hx.phip.config.CustomParameter;
import com.hx.phip.dao.mapper.*;
import com.hx.phip.model.ApplyParameter;
import com.hx.phip.model.SysParameter;
import com.hx.phip.service.OrdersTotalService;
import com.hx.phip.service.ProjectService;
import com.hx.phip.service.SystemParameterService;
import com.hx.phip.service.deduction.DeductionSingleService;
import com.hx.phip.service.init.OrderInitService;
import com.hx.phip.service.order.OrderRiseService;
import com.hx.phip.service.order.OrderServiceV2;
import com.hx.phip.service.userLevel.UserLevelRuleService;
import com.hx.phip.tool.ApplyParameterTool;
import com.hx.phip.tool.SendSMSTool;
import com.hx.phip.tool.deduction.UserDeductionSingleTool;
import com.hx.phip.util.OrdersSnapshotUtil;
import com.hx.phip.util.api.ApiPlatformUtil;
import com.hx.phip.util.api.*;
import com.hx.resultTool.Result;
import com.hx.util.DateUtil;
import com.hx.util.StringUtils;
import com.hx.warehouse.feign.WOrderService;
import com.hz.crm.dto.GoodsTypeDto;
import com.hz.crm.feign.FGoodsSkuService;
import com.hz.his.dto.coupon.CouponCheckDto;
import com.hz.his.dto.coupon.CouponCheckItemDto;
import com.hz.his.dto.gzh.GzhTemplateVO;
import com.hz.his.dto.order.PayDto;
import com.hz.his.feign.service.dcp.SUserTagInfoService;
import com.hz.his.feign.service.marketing.MOrderService;
import com.hz.his.feign.service.phis.SCouponService;
import com.hz.his.feign.service.phisAdmin.SGzhTemplateService;
import com.hz.his.feign.service.sync.SyncOrderService;
import com.hz.phis.dt.ListDt;
import com.hz.phis.dt.coupon.CouponCheckDt;
import com.platform.constants.PlatformPattern;
import com.platform.entity.ThirtApplication;
import com.platform.exception.PlatTipsException;
import com.platform.resultTool.PlatformCode;
import com.platform.resultTool.SystemCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 开单实现类
 *
 * @Author: zhouxiang
 * @Date: 2022/09/19/15:32
 * @Description:
 */
@Transactional
@Service
public class OrderServiceV2Impl implements OrderServiceV2 {
    //log4j日志
    private static Logger logger = LoggerFactory.getLogger(OrderServiceV2Impl.class.getName());
 
    private static List<String> orderTypeList= Arrays.asList(OrderTotalConstants.TYPE_RECHARGE,OrderTotalConstants.TYPE_TURN_RECHARGE);
 
    @Resource
    private SystemParameterMapper systemParameterMapper;
    @Resource
    private OrdersTotalService ordersTotalService;
    @Resource
    private CustomParameter customParameter;
    @Resource
    private ProjectService projectService;
    @Resource
    private CommonService commonService;
    @Resource
    private SGzhTemplateService sGzhTemplateService;
    @Resource
    private FGoodsSkuService fGoodsSkuService;
    @Resource
    private MOrderService mOrderService;
    @Resource
    private WOrderService wOrderService;
    @Resource
    private ApproveConfig approveConfig;
    @Resource
    private OrderInitService orderInitService;
    @Resource
    private SUserTagInfoService sUserTagInfoService;
    @Resource
    private SCouponService sCouponService;
    @Resource
    private UserLevelRuleService userLevelRuleService;
    @Resource
    private DeductionSingleService deductionSingleService;
    @Resource
    private OrderRiseService orderRiseService;
    @Resource
    private SystemParameterService systemParameterService;
 
    /**
     * @param opShopId 操作人门店
     * */
    @Override
    public Map<String, Object> orderCreate(OrdersTotal ordersTotal, List<OrderItem> items, Integer type, List<OrderDeveloper> orderDeveloperList
            , Map<String, String> operator, Shop shop,String opShopId, UserMoney userMoney, User user, PlatformApplication platformApplication
            , List<OrderRise> orderRiseList, CommonService commonService) {
        //定义总订单金额初始字段
        //总订单订单售价总金额
        BigDecimal totalPrice=BigDecimal.ZERO;
        //总订单订单原价总金额
        BigDecimal oriTotal=BigDecimal.ZERO;
        //总订单应付支付总金额
        BigDecimal shouldOrderTotal=BigDecimal.ZERO;
        //总订单的总积分
        BigDecimal totalPoints = BigDecimal.ZERO;
        //总订单的应付总积分
        BigDecimal shouldTotalPoints = BigDecimal.ZERO;
        //总订单的折扣金额
        BigDecimal discountTotal=BigDecimal.ZERO;
        //非主线任务节点报错标记
        Integer nodeType=0;
 
        //是否老带新
        Integer isOldBringNew =BaseEntity.NO;
        //是否初诊单
        Integer isBothTheOne =BaseEntity.NO;
 
        //返回参数
        Map<String,Object> data=new HashMap<>();
        //开单节点日志
        OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
        StringBuilder orderCreate = new StringBuilder();
 
        SqlSentence sqlSentence=new SqlSentence();
        Map<String, Object> appIdMap = new HashMap<>();
        sqlSentence.setM(appIdMap);
 
        //主线业务
        //业务逻辑判断(商品限制、订单重复等)
        OrderCreateUtil.businessJudge(ordersTotal,items,user,shop,ordersTotalService,commonService);
 
        /**
         * 计算订单金额信息(计算请求参数的一级子订单)
         *      1、充值订单不需要系统计算金额,充多少是多少
         *      2、商品、项目、促销、卡项、卡向内等均系统计算订单金额
         *      3、处理活动规则(主要处理是满减、满折扣情况),对总订单金额进行扣减
         */
        if(orderTypeList.contains(ordersTotal.getType())){
            //订单充值总金额
            totalPrice=ordersTotal.getTotal();
            //订单应付付总金额
            shouldOrderTotal=ordersTotal.getTotal();
        }else {
            Map<String, Object> handOrderItemMap = OrderCreateUtil.handOrderItem(ordersTotal, shop,opShopId, items, totalPrice, shouldOrderTotal,discountTotal,oriTotal, commonService, systemParameterMapper);
            totalPrice = (BigDecimal) handOrderItemMap.get("totalPrice");
            shouldOrderTotal = (BigDecimal) handOrderItemMap.get("shouldOrderTotal");
            discountTotal = (BigDecimal) handOrderItemMap.get("discountTotal");
            oriTotal = (BigDecimal) handOrderItemMap.get("oriTotal");
            totalPoints = (BigDecimal) handOrderItemMap.get("totalPoints");
            shouldTotalPoints = (BigDecimal) handOrderItemMap.get("shouldTotalPoints");
            items = (List<OrderItem>) handOrderItemMap.get("items");
        }
 
        //处理活动规则,活动规则如果是满减、折扣,则订单应付金额需要扣减活动规则金额,(目前只有充值订单才能用到活动规则)
        if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType()) &&  ordersTotal.getActivityIds() !=null && ordersTotal.getActivityIds().size()>0){
            ordersTotal.setShouldTotal(totalPrice);
            BigDecimal price=OrderAddUtil.activityRule(ordersTotal,commonService,operator,userMoney,customParameter,user,0);
            if(!price.equals(BigDecimal.ZERO)){
                ordersTotal.setActivityTotal(shouldOrderTotal.subtract(price));
                shouldOrderTotal=price;
            }
        }
 
 
        //处理订单基本信息(总订单和子订单)
        //处理总订单开发人,默认客户的所属顾问,注意如果是crm开单的传什么就是什么
        OrderCreateUtil.handUserDeveloper(ordersTotal,user,orderTypeList,commonService);
 
        //构架总订单基本信息,金额信息,并保存(orderTotal、orderInfo)
        OrderCreateUtil.setOrderTotal(ordersTotal, shop, totalPrice, shouldOrderTotal, discountTotal,
                operator.get("operatorId"),operator.get("operatorName"),Integer.valueOf(operator.get("operatorType"))
                ,oriTotal, totalPoints, shouldTotalPoints
                ,type,user,systemParameterMapper, platformApplication,commonService);
 
        ordersTotal = OrderCreateUtil.createOrder(ordersTotal, operator, user, userMoney, commonService);
 
        //开单优先校验处理升单关联信息,出错后不再往下走其他逻辑
        OrderCreateUtil.createOrderRiseInfo(commonService, ordersTotal, orderRiseList);
 
 
        //保存活动规则信息(目前只有充值订单才能用到活动规则)
        OrderCreateUtil.insertActivity(ordersTotal.getActivityIds(),ordersTotal,commonService);
 
        //非主线业务
        try {
            //判断是否是初诊单
            nodeType=3;
            orderCreate.append("-开始判断是否是初诊单");
            // 改集中工具类 复制于翔爷代码 统一方便修改代码
            isBothTheOne = OrderUtil.checkIsBothTheOne(ordersTotal, commonService, VisitRecordMapper.class);
            orderCreate.append("-结束判断是否是初诊单");
            nodeType=4;
            //订单如果为复诊单那么就是老带新订单,对应禅道需求编号694
//            if(isBothTheOne !=null && isBothTheOne==OrderInfo.CONSULTATION){
//                isOldBringNew=BaseEntity.YES;
//            }
            //判断是否老带新
            nodeType=1;
            orderCreate.append("-开始判断是否老带新");
            // 改集中工具类 复制于翔爷代码 统一方便修改代码
            ordersTotal.getOrderInfo().setIsBothTheOne(isBothTheOne);
            ordersTotal.getOrderInfo().setIsBothTheOneInitial(isBothTheOne);
            isOldBringNew = OrderUtil.checkOldBringNew(ordersTotal, commonService, VisitRecordMapper.class);
            orderCreate.append("-结束判断是否老带新");
            nodeType=2;
 
        }catch (Exception e){
            String nodeText="";
            if(nodeType>=1 && nodeType<2){
                nodeText="判断是否老带新失败";
                orderCreate.append("-判断是否老带新失败,异常信息:"+e.getMessage());
            }else if(nodeType>=3 && nodeType<4){
                nodeText="判断是否是初诊单失败";
                orderCreate.append("-判断是否是初诊单失败,异常信息:"+e.getMessage());
            }
            //记录非主线日志(处理到具体节点(成功和失败))
            ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_CREATE);
            ordersNodeLog.setContent(orderCreate.toString());
            ordersNodeLog.setOrderId(ordersTotal.getId());
            commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
 
            //异常发送企业微信通知给工作人员
            SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),nodeText,commonService,customParameter);
            logger.info("开单"+nodeText+",异常原因:{}",e.getMessage(),e);
            e.printStackTrace();
        }
 
        //主线业务
        //保存订单其他信息(对象:orderInfo)
        String activityName = OrderCreateUtil.saveOrderInfo(ordersTotal, user,customParameter,isOldBringNew,isBothTheOne, commonService);
 
        //保存一级子订单和处理二级子订单信息(orderItem、orderItemSon)
        if(!orderTypeList.contains(ordersTotal.getType())){
            //创建子订单
            OrderCreateUtil.createOrderItem(ordersTotal, items,projectService,commonService,sqlSentence,appIdMap);
        }
        //生成订单日志
        commonService.insert(OrderLogMapper.class, ApiOrderUtil.setOrderLog(ordersTotal, null, operator.get("operatorId"), operator.get("operatorName"), activityName, 0, OrderLogConstants.LOG_TYPE_CREATE));
 
        //保存绑定的其他开发人集合信息
        OrderAddUtil.creatDeveloperList(ordersTotal, orderDeveloperList,commonService);
 
 
        //如果是开单开了设置的卡项
        if (haveCard(items)){
            //营销助手审批,如果订单有支付
            if(StringUtils.isEmpty(ordersTotal.getKoapOrderId())&& ordersTotal.getOrderInfo()!=null) {
                OrderCreateUtil.approvalPayMarketing(ordersTotal,items,mOrderService,commonService);
            }
        }else {
            //营销助手审批,如果订单有折扣
            if(StringUtils.isEmpty(ordersTotal.getKoapOrderId())&& ordersTotal.getOrderInfo()!=null) {
                OrderCreateUtil.approvalMarketing(ordersTotal,mOrderService,commonService);
            }
        }
 
 
        //返回phis订单号、phis订单id
        data.put("orderNo",ordersTotal.getOrderNo());
        data.put("orderId",ordersTotal.getId());
 
        return data;
    }
 
    /**判断子订单是否包含对应的要审核的卡项*/
    private boolean haveCard(List<OrderItem> items) {
        boolean isHaveCard = false;
        String cardNoString = approveConfig.getCardNoList();
        if (!StringUtils.isEmpty(cardNoString)){
            List<String> collect = Arrays.stream(cardNoString.split(ApproveConfig.SIGN)).collect(Collectors.toList());
            if (collect.size() > 0){
                for (String s : collect) {
                    for (OrderItem item : items) {
                        if (!StringUtils.isEmpty(item.getGoodsNo()) && s.equals(item.getGoodsNo())){
                            isHaveCard = true;
                            break;
                        }
                    }
                }
            }
        }
        return isHaveCard;
    }
 
    /**
     * 处理优惠券发送人和订单推荐人
     * @param couponNumber 优惠券
     * @param coupon 优惠券配置
     * @param ordersTotal 订单
     * @param orderInfo 订单详情
     */
    private void couponSentInfo(CouponNumber couponNumber, Coupon coupon, OrdersTotal ordersTotal, OrderInfo orderInfo) {
        // 都不等于空同时订单信息没用发放人
        if (coupon != null && couponNumber != null && ordersTotal != null && orderInfo != null && StringUtils.isEmpty(ordersTotal.getInviteeId())) {
            // 排除生日券处理同时发送人不为空
            if (BaseEntity.NO.equals(coupon.getIsBirthday()) && !StringUtils.isEmpty(couponNumber.getSendId())) {
                // 员工信息
                Employee employee = commonService.selectOneByKey(EmployeeMapper.class, couponNumber.getSendId());
                if (employee != null) {
                    // 判断是否是crm平台下单
                    if (PlatformConstants.TYPE_PLATFORM_CRM.equals(ordersTotal.getAppIdCode())) {
                        // 没有推荐人
                        if (StringUtils.isEmpty(ordersTotal.getInviteeId())) {
                            ordersTotal.setInviteeType(UserChannelType.CATEGORY_EMPLOYEE);
                            ordersTotal.setInviteeId(employee.getId());
                            ordersTotal.setInviteeName(employee.getCnName());
                        }
                    }
                } else {
                    // 用户信息
                    User user = commonService.selectOneByKey(UserMapper.class, couponNumber.getUserId());
                    if (user != null) {
                        // 判断是否是crm平台下单
                        if (PlatformConstants.TYPE_PLATFORM_CRM.equals(ordersTotal.getAppIdCode())) {
                            // 没有推荐人
                            if (StringUtils.isEmpty(ordersTotal.getInviteeId())) {
                                ordersTotal.setInviteeType(UserChannelType.CATEGORY_MEMBERS);
                                ordersTotal.setInviteeId(user.getId());
                                ordersTotal.setInviteeName(user.getName());
                                ordersTotal.setUserBelongingType(user.getUserBelongingType());
                            }
                        }
                    }
                }
            }
        }
    }
 
    @Override
    public Map<String, Object> orderPayMoney(Integer couponCheckVersion, Integer type, OrdersTotal ordersTotal, User user, User payUser, Shop shop, OrderInfo info, List<OrderItem> orderItemList,
                                             Map<String, String> operator, UserMoney userMoney, String total, JSONArray amountList, JSONArray userCouponIds,
                                             PayDto payDto, ThirtApplication thirtApplication) {
        String message="";
        //订单优惠券金额
        BigDecimal couponAfterAmount =BigDecimal.ZERO;
 
        //用户支付方式集合,用于同步到his系统
        JSONArray hisPayList=new JSONArray();
 
        //接口返回参数map
        Map<String,Object> data=new HashMap<>();
 
        //订单节点日志
        OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
        StringBuilder orderNodeBuilder = new StringBuilder();
 
//        if(userCouponIds!=null && userCouponIds.size()>0){
//            //获取优惠券金额
//            couponAfterAmount = CouponTool.handCouponAmout(ordersTotal.getShouldTotal(), coupon);
//        }
 
        //升单的订单在开始结账时就要处理对应逻辑
        if(OrderTotalConstants.ADD_WAY_RISE.equals(ordersTotal.getAddWay())){
            orderRiseService.beforeCheckoutHandle(ordersTotal, operator.get("operatorId"), operator.get("opRoleId"), amountList, thirtApplication);
        }
 
        orderNodeBuilder.append("开始结账");
        /**
         * 处理优惠券金额,先计算优惠金额因为优惠券金额也需要参加到业务判断金额是否符合
         */
        if(userCouponIds!=null && userCouponIds.size()>0){
            orderNodeBuilder.append("-开始处理优惠券信息");
            CouponNumber couponNumber=null;
            Coupon coupon=null;
            //旧版逻辑
            if (couponCheckVersion == null || couponCheckVersion == 0){
                //判断优惠券是否可以使用,以及保存订单使用优惠券记录,以及线下券核销操作
                for(int i=0;i<userCouponIds.size();i++){
                    String couponId = userCouponIds.getString(i);
                    //查看用户是否有优惠券
                    couponNumber = commonService.selectOneByKey(CouponNumberMapper.class, couponId);
                    //查看用户是否有优惠券
                    coupon = commonService.selectOneByKey(CouponMapper.class, couponNumber.getCouponId());
                    BigDecimal couponTotal = OrderPayMoneyUtil.handCoupon(couponNumber, coupon, orderItemList, ordersTotal.getId(), ordersTotal.getShouldTotal(), user, commonService, fGoodsSkuService);
                    couponAfterAmount=couponAfterAmount.add(couponTotal);
                    // 优惠券发送人处理
                    this.couponSentInfo(couponNumber, coupon, ordersTotal, ordersTotal.getOrderInfo());
                }
            }else {
                List<CouponNumber> couponNumberList = new ArrayList<>();
                //新版逻辑
                CouponCheckDto couponCheckDto = new CouponCheckDto();
 
                //1.封装优惠券码
                List<String> couponNumberIdList = new ArrayList<>();
                for(int i=0;i<userCouponIds.size();i++) {
                    couponNumberIdList.add(userCouponIds.getString(i));
                    CouponNumber userCouponNumber = commonService.selectOneByKey(CouponNumberMapper.class, userCouponIds.getString(i));
                    if (userCouponNumber != null){
                        Coupon userCoupon = commonService.selectOneByKey(CouponMapper.class, userCouponNumber.getCouponId());
                        if (userCoupon != null){
                            userCouponNumber.setType(userCoupon.getType());
                            // 优惠券发送人处理
                            this.couponSentInfo(userCouponNumber, userCoupon, ordersTotal, ordersTotal.getOrderInfo());
                        }
                    }
                    couponNumberList.add(userCouponNumber);
                }
                couponCheckDto.setCouponNumberIdList(couponNumberIdList);
 
                //2.封装商品信息
                List<CouponCheckItemDto> goodsList = new ArrayList<>();
                for (OrderItem orderItem : orderItemList) {
                    CouponCheckItemDto couponCheckItemDto = new CouponCheckItemDto();
                    couponCheckItemDto.setSkuId(orderItem.getPlatformTypeId());
                    couponCheckItemDto.setHisId(orderItem.getCommonId());
                    couponCheckItemDto.setHisType(orderItem.getType());
                    couponCheckItemDto.setPrice(orderItem.getProPrice());
                    couponCheckItemDto.setBuyNum(orderItem.getBuyNum());
 
                    //获取商品所属分类
                    GoodsTypeDto goodsTypeDto = new GoodsTypeDto();
                    if (!StringUtils.isEmpty(orderItem.getPlatformTypeId())){
                        goodsTypeDto.setSkuId(orderItem.getPlatformTypeId());
                    }else if (!StringUtils.isEmpty(orderItem.getCommonId())){
                        goodsTypeDto.setHisId(orderItem.getCommonId());
                    }
                    Result result = fGoodsSkuService.goodsSkuTypeList(goodsTypeDto);
                    if (result == null || !result.checkCode()){
                        logger.error("优惠券校验-获取所属分类信息失败"+JSON.toJSONString(result));
                        throw new TipsException("优惠券校验失败,错误代码01");
                    }
                    ListDt listDt = result.getObject(result.getData(), ListDt.class);
                    if (listDt == null){
                        logger.error("优惠券校验-获取所属分类信息失败,转换信息为空"+JSON.toJSONString(result));
                        throw new TipsException("优惠券校验失败,错误代码02");
                    }
                    couponCheckItemDto.setTypeIdList(listDt.getList().stream().map(a -> (String)a.get("id")).collect(Collectors.toList()));
 
                    goodsList.add(couponCheckItemDto);
                }
                couponCheckDto.setGoodsList(goodsList);
                //3.封装支付方式
                List<String> payMethodList = new ArrayList<>();
                for(int i=0;i<amountList.size();i++) {
                    JSONObject object = amountList.getJSONObject(i);
                    payMethodList.add(object.getString("method"));
                }
                couponCheckDto.setPayMethodList(payMethodList);
 
                logger.info("校验优惠券,参数"+JSON.toJSONString(couponCheckDto));
//                Result result = sCouponService.unifyCheck(couponCheckDto);
//                logger.info("校验优惠券,返回"+JSON.toJSONString(result));
//                if (result == null){
//                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠券校验不通过-错误代码01");
//                }
//                if (!result.checkCode()){
//                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠券校验不通过-错误代码02");
//                }
//                CouponCheckDt couponCheckDt = result.getObject(result.getData(), CouponCheckDt.class);
                CouponCheckDt couponCheckDt = CouponCheckTool.unifyCheck(couponCheckDto, commonService);
                logger.info("校验优惠券,返回"+JSON.toJSONString(couponCheckDt));
                if (couponCheckDt == null){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠券校验不通过-错误代码03");
                }
                if (couponCheckDt.getIsErr()){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠券校验不通过,"+couponCheckDt.getErrMsg());
                }
                if (!couponCheckDt.getIsCanUse()){
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠券校验不通过,"+couponCheckDt.getUnavailableMsg());
                }
                //叠加金额,先算满减的叠加
                List<CouponNumber> moneyList = couponNumberList.stream().filter(a -> a.getType() != null && a.getType().equals(Coupon.TYPE_AMOUNT)).collect(Collectors.toList());
                for (CouponNumber number : moneyList) {
                    BigDecimal couponTotal = OrderPayMoneyUtil.handCouponNew(number, ordersTotal.getId(),
                            user.getId(), ordersTotal.getShouldTotal(),commonService);
                    couponAfterAmount = couponAfterAmount.add(couponTotal);
                }
                //再算剩余的折扣
                List<CouponNumber> disList = couponNumberList.stream().filter(a -> a.getType() != null && a.getType().equals(Coupon.TYPE_DIS)).collect(Collectors.toList());
                for (CouponNumber number : disList) {
                    BigDecimal couponTotal = OrderPayMoneyUtil.handCouponNew(number,ordersTotal.getId(), user.getId(),
                            ordersTotal.getShouldTotal().subtract(couponAfterAmount).setScale(2, RoundingMode.HALF_UP), commonService);
                    couponAfterAmount = couponAfterAmount.add(couponTotal);
                }
            }
            orderNodeBuilder.append("-结束处理优惠券信息");
        }
 
        //判断升单金额逻辑
        if(OrderTotalConstants.ADD_WAY_RISE.equals(ordersTotal.getAddWay())){
            OrderPayMoneyUtil.riseCheckOutAmount(couponAfterAmount, ordersTotal, amountList);
        }
 
        /**
         * 业务判断(判断金额是否符合(需要把优惠券金额加进用户支付金额进行判断),状态是否能结账,项目、商品、促销、卡项等模板限制等)
         */
        OrderPayMoneyUtil.checkOrderAmount(type, ordersTotal, couponAfterAmount, total, amountList,orderItemList,user,commonService);
 
        ///////支付人信息填充
        if(!payUser.getId().equals(ordersTotal.getUserId())){
            //是否代付
            ordersTotal.setIsGenerationPay(BaseEntity.YES);
        }
        ordersTotal.setPayUserId(payUser.getId());
        ordersTotal.setPayUserNo(payUser.getMemberNO());
        ordersTotal.setPayUserName(payUser.getName());
        ordersTotal.setPayUserCIQ(payUser.getCIQ());
        ordersTotal.setPayUserMemberId(payUser.getMemberLevelId());
        if(StringUtils.noNull(payUser.getMemberLevelId())){
            MemberLevel memberLevel = commonService.selectOneByKey(MemberLevelMapper.class,payUser.getMemberLevelId());
            if(memberLevel != null){
                ordersTotal.setPayUserMemberNo(memberLevel.getHisNo());
            }
        }
        ordersTotal.setPayUserLevel(payUser.getUserLevel());
        ordersTotal.setPayUserAdviserId(payUser.getHisCorpUserId());
        ordersTotal.setPayUserAdviserName(payUser.getHisCorpUserName());
        if(StringUtils.noNull(payUser.getHisCorpUserId())){
            Employee employee = commonService.selectOneByKey(EmployeeMapper.class,payUser.getHisCorpUserId());
            if(employee != null){
                ordersTotal.setPayUserAdviserNo(employee.getEmployeeNo());
                ordersTotal.setPayUserAdviserName(employee.getCnName());
            }
        }
        ordersTotal.setPayUserShopId(payUser.getShopId());
        if(StringUtils.noNull(payUser.getShopId())){
            Shop shop1 = commonService.selectOneByKey(ShopMapper.class,payUser.getShopId());
            if(shop1 != null){
                ordersTotal.setPayUserShopNo(shop1.getCode());
                ordersTotal.setPayUserShopName(shop1.getName());
            }
        }
 
        //主业务
        try {
 
 
            /**
             * 处理支付记录
             */
            orderNodeBuilder.append("-开始处理订单支付记录");
            //计算金额信息-根据用户支付集合计算用户实际支付金额
            Map<String, Object> objectMap = OrderPayMoneyUtil.handPayMethod(payDto,amountList, ordersTotal, commonService, customParameter);
            //总订单
            ordersTotal= (OrdersTotal) objectMap.get("ordersTotal");
            //一级子订单用户实际支付金额,该Map用于统计用户按照项目部分付款
            Map<String,String>itemMap= (Map<String, String>) objectMap.get("itemMap");
            //订单的已支付现金金额(微信/支付宝支付/其他)
            BigDecimal payTotal= (BigDecimal) objectMap.get("payTotal");
            //订单的已支付储值金金额
            BigDecimal payRecharge= (BigDecimal) objectMap.get("payRecharge");
            //订单的已支付增值金金额
            BigDecimal payIncrement= (BigDecimal) objectMap.get("payIncrement");
            //订单现金支付总金额
            BigDecimal snapPayTotal= (BigDecimal) objectMap.get("snapPayTotal");
            //订单现金支付总金额
            BigDecimal snapExecuteTotal= (BigDecimal) objectMap.get("snapExecuteTotal");
            //订单已支付积分
            BigDecimal actualTotalPoints = (BigDecimal) objectMap.get("totalPoints");
            //用户支付方式集合,用于同步到his系统
            hisPayList= (JSONArray) objectMap.get("hisPayList");
            //存储卡项id,用户判断用户是否使用的是卡包进行结算
            List<String> cardIds= (List<String>) objectMap.get("cardIds");
            orderNodeBuilder.append("-结束处理订单支付记录");
 
            /**
             * 处理充值订单-增加储值金
             */
            if(orderTypeList.contains(ordersTotal.getType())){
                orderNodeBuilder.append("-开始处理充值订单增加储值金");
                OrderPayMoneyUtil.handRecharge(ordersTotal, amountList, objectMap, commonService);
                orderNodeBuilder.append("-结束处理充值订单增加储值金");
            }
 
            /**
             * 处理订单基本信息(总订单和子订单)
             */
            orderNodeBuilder.append("-开始处理订单基本信息");
            //更改订单基本信息(商品、项目、促销、卡项、卡集基本信息)
            //更新一级子订单或者二级子订单(需要处理未执行划扣金额、项目生成未执行划扣、商品生成提货单(目前没有库存不处理)、促销、卡项(目前不处理)、卡包)
            ordersTotal.getOrderInfo().setSnapPayTotal(snapPayTotal);
            ordersTotal.getOrderInfo().setSnapExecuteTotal(snapExecuteTotal);
            if(!orderTypeList.contains(ordersTotal.getType())){
                OrderPayMoneyUtil.payHandOrderItem(orderItemList,ordersTotal, itemMap,operator ,userMoney,cardIds,user,
                        couponAfterAmount,wOrderService,payTotal, payRecharge,payIncrement, actualTotalPoints,commonService,customParameter);
 
            }
            //更新总订单状态、金额信息、记录日志
            OrderPayUtil.payHandleOrderTotal(operator, ordersTotal, payTotal, payRecharge, couponAfterAmount,payIncrement,actualTotalPoints,commonService);
            orderNodeBuilder.append("-结束处理订单基本信息");
 
            //--非常重要:结账成功之后,重新算订单部分金额信息。注意:该程序只能运行一次
            orderInitService.initOrder(ordersTotal.getId(),true,true);
 
            //--直接划扣订单里面的所有项目
            if(payDto.getDirectDeduction() != null && payDto.getDirectDeduction().equals(BaseEntity.YES)){
                UserDeductionSingleTool.orderDeduction(ordersTotal,thirtApplication,deductionSingleService,commonService);
            }
 
            /**
             * 处理活动规则
             */
            orderNodeBuilder.append("-开始处理活动规则");
            OrderPayMoneyUtil.handActivity(ordersTotal, user, operator, userMoney,commonService,customParameter);
            orderNodeBuilder.append("-结束处理活动规则");
 
            //非主线业务
 
            /**
             * 用户升降级(调用航爷) 金额=用户支付的实付现金金额(不包含储值金)
             */
            if(snapPayTotal !=null && snapPayTotal.compareTo(BigDecimal.ZERO) == 1){
                try {
                    orderNodeBuilder.append("-开始处理用户升降级");
                    UserLevelUtil.order(userLevelRuleService, ordersTotal.getUserId(),ordersTotal.getId(),snapPayTotal,ordersTotal.getAppIdCode());
                    orderNodeBuilder.append("-结束处理用户升降级");
                }catch (Exception e){
                    String snapshot="处理用户升降级失败";
                    orderNodeBuilder.append("-处理用户升降级失败,异常原因:"+e.getMessage());
                    logger.error("处理用户升降级失败:" + e.getMessage());
                    //发送企业微信通知给工作人员
                    SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
                }
            }
 
            //用户活跃状态处理(先暂时不处理)
 
            /**
             * 快照
             */
            //订单快照
            if(OrderTotalConstants.STATUS_PAY == ordersTotal.getStatus() || OrderTotalConstants.STATUS_DONE == ordersTotal.getStatus()){
                // 状态 已支付与已完成
                try {
                    orderNodeBuilder.append("-开始处理订单快照");
                    OrdersSnapshotUtil.createOrdersSnapshot(customParameter, ordersTotal.getId(), commonService);
                    orderNodeBuilder.append("-结束处理订单快照");
                } catch (Exception e) {
                    String snapshot="处理订单快照失败";
                    orderNodeBuilder.append("-处理订单快照失败,异常原因:"+e.getMessage());
                    logger.error("生成快照失败:" + e.getMessage());
                    //发送企业微信通知给工作人员
                    SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
                    message=e.getMessage();
                }
            }
 
            Integer synHisOrderType=0;
 
            /**
             * 同步
             */
//            try {
//                //同步开单-同步订单到领建
//                if(ordersTotal.getHisSynStatus()==1){
//                    orderNodeBuilder.append("-开始处理创建订单同步订单到领建");
//                    synHisOrderType=1;
//                    String hisOrderId = OrderCreateUtil.syncOrder(ordersTotal, operator,ordersTotal.getOrderNo(),customParameter,commonService);
//                    if(StringUtils.isEmpty(hisOrderId)){
//                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"同步领建失败!领建标识为空");
//                    }
//                    data.put("hisOrderId",hisOrderId);
//                    ordersTotal.setHisOrderId(hisOrderId);
//                    orderNodeBuilder.append("-结束处理创建订单同步订单到领建");
//
//                    //同步结账-同步订单到领建
//                    orderNodeBuilder.append("-开始处理结账同步订单到领建");
//                    synHisOrderType=2;
//                    //封装支付方式,如果结账采用了优惠券,封装支付方式为优惠券到领建,如果是积分封装支付方式为积分
//                    OrderPayMoneyUtil.synOrderPayWay(ordersTotal, couponAfterAmount, hisPayList);
//                    //将p-his结账的订单同步到领建系统
//                    SynOrderUtil.synPayOrder(operator, ordersTotal, shop.getApiId(), hisPayList,customParameter,commonService);
//                    orderNodeBuilder.append("-结束处理结账同步订单到领建");
//                }
//
//
//                //同步结账-如果是卡包支付则需要扣减领建卡包次数操作(调用同步中心接口)
//                if(OrderTotalConstants.TYPE_CARD_BAG.equals(ordersTotal.getType())){
//                    orderNodeBuilder.append("-开始处理结账扣减领建卡包次数");
//                    synHisOrderType=3;
//                    //因为p-his开的已有卡项订单是用普通项目开过去的,所以这里需要调用同步中心接口扣减已有卡项次数,切掉领建该方法也需要去掉
//                    RefundUtil.handHisCardBag(commonService, customParameter, ordersTotal,0);
//                    orderNodeBuilder.append("-结束理结账扣减领建卡包次数");
//                }
//            }catch (Exception e){
//                String sysPhiskin="";
//                switch (synHisOrderType){
//                    case 1:
//                        sysPhiskin="领建创建订单失败";
//                        orderNodeBuilder.append("-领建创建订单失败,异常原因:"+e.getMessage());break;
//                    case 2:
//                        sysPhiskin="领建结账同步失败";
//                        orderNodeBuilder.append("-领建结账同步失败,异常原因:"+e.getMessage());break;
//                    case 3:
//                        sysPhiskin="领建扣减卡包同步失败";
//                        orderNodeBuilder.append("-领建扣减卡包同步失败,异常原因:"+e.getMessage());break;
//                }
//                logger.info("同步订单到领建异常(创建、结账、卡包扣减)!,异常原因:{}",e.getMessage(),e);
//                JSONObject object = new JSONObject();
//                object.put("ordersTotal",ordersTotal);
//                object.put("type",0);
//                object.put("operator",operator.toString());
//                object.put("shopApiId",shop.getApiId());
//                object.put("hisPayList",hisPayList.toString());
//                //同步结账或扣减领建卡包次数异常失败,保存重发记录,发送企业微信通知给开发人
//                OrderCreateUtil.orderSendNoticeResendRecord(ordersTotal, e, object,"/phip/resend/order/create/pay/cardBag","同步订单到领建异常(创建、结账、卡包扣减)!",synHisOrderType,commonService,customParameter);
//                //发送企业微信通知给工作人员
//                SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),sysPhiskin,commonService,customParameter);
//                message=e.getMessage();
//            }
            try {
                //同步结账-同步到康博佳
                if(PlatformPattern.PROD.equals(customParameter.getPlatformPattern()) && StringUtils.noNull(ordersTotal.getKoapOrderId())){
                    orderNodeBuilder.append("-开始处理同步康博佳结账");
                    //将p-his结账的订单同步到康博佳系统
                    SynOrderUtil.synKoapPayOrder(operator, ordersTotal, hisPayList,customParameter,commonService);
                    orderNodeBuilder.append("-结束处理同步康博佳结账");
                }
            }catch (Exception e){
                String koapPay="处理同步康博佳结账失败";
                orderNodeBuilder.append("-处理同步康博佳结账失败,异常原因:"+e.getMessage());
                logger.info("同步结账-同步订单到康博佳异常!,异常原因:{}",e.getMessage(),e);
                //封装请求参数
                JSONObject object = new JSONObject();
                object.put("ordersTotal",ordersTotal);
                object.put("operator",operator.toString());
                object.put("hisPayList",hisPayList.toString());
                //结账同步到康博佳失败,保存重发记录,发送企业微信通知给开发人
                OrderCreateUtil.orderSendNoticeResendRecord(ordersTotal, e, object,"接口名称","同步结账-同步订单到康博佳异常!",synHisOrderType,commonService,customParameter);
                //发送企业微信通知给工作人员
                SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),koapPay,commonService,customParameter);
                message=e.getMessage();
            }
 
            // 结账成功发送公众号通知给用户 -异步
            try {
                sendPublicNo(ordersTotal.getId(),commonService);
            } catch (TipsException | PlatTipsException e){
                logger.info("结账成功发送公众号通知给用户异常 -异步:{}", e.getMessage());
            } catch (Exception e){
                logger.info("结账成功发送公众号通知给用户异常 -异步:{}", e.getMessage(),e);
            }
 
            // 结账成功发送短信通知给用户 -异步
            try {
                sentSMSInfo(ordersTotal.getId(), commonService);
            } catch (Exception e){
                logger.info("结账成功发送短信通知给用户异常 -异步:{}", e.getMessage(),e);
            }
 
            //返回phis订单号、phis订单id
            data.put("orderId",ordersTotal.getId());
            data.put("orderCode",ordersTotal.getOrderNo());
 
            //记录日志(处理到具体节点(成功和失败))
            orderNodeBuilder.append("-结束结账订单");
            ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_PAY);
            ordersNodeLog.setContent(orderNodeBuilder.toString());
            ordersNodeLog.setOrderId(ordersTotal.getId());
            commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
 
        }catch (Exception e){
            String mainBusiness="结账失败";
            orderNodeBuilder.append("-结账失败,异常原因:"+e.getMessage());
            logger.info("结账异常:{}",e.getMessage(),e);
            //异常发送企业微信通知给工作人员
            SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),mainBusiness,commonService,customParameter);
            message=e.getMessage();
 
            //记录日志(处理到具体节点(成功和失败))
            orderNodeBuilder.append("-结束结账订单");
            ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_PAY);
            ordersNodeLog.setContent(orderNodeBuilder.toString());
            ordersNodeLog.setOrderId(ordersTotal.getId());
            commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
 
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账失败,异常原因:"+e.getMessage());
        }
 
        data.put("message",message);
 
 
 
        return data;
    }
 
    @Override
    public String getHisOrderNo(String hisOrderId, String orderId, SqlSentence sqlSentence, Map<String, Object> paramMap, SyncOrderService syncOrderService, CommonService commonService) {
        String hisOrderNo="";
        OrdersTotal ordersTotal=commonService.selectOneByKeyBlob(OrdersTotalMapper.class,orderId);
        if (ordersTotal != null && StringUtils.noNull(hisOrderId)) {
            try {
                hisOrderNo = SynOrderUtil.getOrderById(hisOrderId, orderId, sqlSentence, paramMap, syncOrderService, commonService);
            } catch (Exception ex) {
                logger.info("查询领建订单号异常:领建订单标识{},预约订单标识:{}",hisOrderId,orderId,ex);
            }
        }
        return hisOrderNo;
    }
 
 
 
    @Override
    @Async
    public void getExecution(Object orderId,User user) {
        Map<String,Object> map=new HashMap<>();
        SqlSentence sqlSentence = new SqlSentence();
        StringBuilder sql = new StringBuilder();
        sqlSentence.setM(map);
 
        map.put("orderId",orderId);
        map.put("type", OrderItemConstants.TYPE_PROJECT);
        sqlSentence.setSqlSentence(" type=#{m.type} and orderId=#{m.orderId}");
        int itemCount = commonService.selectCount(OrderItemMapper.class, sqlSentence);
        int sonCount = commonService.selectCount(OrderItemSonMapper.class, sqlSentence);
        if(itemCount==0 && sonCount==0){
            logger.info("异步获取未执行划扣itemId提示:一级子订单符合项目条数:{},二级子订单条数:{}",itemCount,sonCount);
            return;
        }
 
        OrdersTotal ordersTotal=commonService.selectOneByKeyBlob(OrdersTotalMapper.class,orderId);
        if(ordersTotal==null){
            logger.info("异步获取未执行划扣itemId提示:根据订单标识未找到订单信息!");
            return;
        }
        if(StringUtils.isEmpty(ordersTotal.getHisOrderId())){
            logger.info("异步获取未执行划扣itemId提示:该订单没有领建标识!p-his订单标识:{}",ordersTotal.getId());
            return;
        }
 
        sqlSentence.setSqlSentence("SELECT id,commonId,type FROM order_item WHERE orderId=#{m.orderId} ");
        List<OrderItem> orderItems=commonService.selectList(OrderItemMapper.class,sqlSentence);
        if(orderItems==null || orderItems.size()==0){
            logger.info("异步获取未执行划扣itemId提示:根据订单标识未找到一级子订单信息!");
            return;
        }
        List<String> itemIds = orderItems.stream().map(o -> o.getId()).collect(Collectors.toList());
 
        sqlSentence.setSqlSentence("SELECT id,goodsId,type FROM order_item_source WHERE orderId=#{m.orderId} ");
        List<OrderItemSon> orderItemSons=commonService.selectList(OrderItemSonMapper.class,sqlSentence);
        if(orderItemSons!=null && orderItemSons.size()>0){
            itemIds.addAll(orderItemSons.stream().map(o->o.getId()).collect(Collectors.toList()));
        }
 
        sql.append("SELECT id,orderItemId,commonId FROM user_project_item WHERE commonId in( ");
        SqlSplicingTool.selectBuilderIn(sql,itemIds);
        sqlSentence.setSqlSentence(sql.toString());
        List<UserProjectItem> userProjectItems=commonService.selectList(UserProjectItemMapper.class,sqlSentence);
        if(userProjectItems==null || userProjectItems.size()==0){
            logger.info("异步获取未执行划扣itemId提示:根据订单的一级子订单标识未找到用户未划扣信息!");
            return;
        }
        Map<String, UserProjectItem> userProjectItemMap = userProjectItems.stream().collect(Collectors.toMap(o -> o.getCommonId(),o->o));
 
        JSONObject object = new JSONObject();
        object.put("start", DateUtil.formatDate_3(new Date()));
        object.put("end",DateUtil.formatDate_3(new Date()));
        object.put("customerId",user.getApiId());
        String returnData = ApiPlatformUtil.getExecution(customParameter, object.toJSONString());
 
        if(StringUtils.noNull(returnData)){
            JSONObject jsonObject = JSONObject.parseObject(returnData);
            String code = jsonObject.getString("code");
            if("100".equals(code)){
                JSONObject data = jsonObject.getJSONObject("data");
                if(!data.isEmpty()){
                    JSONArray content = data.getJSONArray("content");
                    for(int j=0;j<content.size();j++){
                        JSONObject item = content.getJSONObject(j);
                        //订单领建标识
                        String hisOrderId = item.getString("orderId");
                        if(ordersTotal.getHisOrderId().equals(hisOrderId)){
                            //未执行划扣itemId
                            String itemId = item.getString("id");
                            JSONObject itemSon = item.getJSONObject("item");
                            if(itemSon!=null){
                                //项目领建标识
                                String hisProjectId = itemSon.getString("id");
                                map.put("hisProjectId",hisProjectId);
                                sqlSentence.setSqlSentence("SELECT id FROM project WHERE apiId=#{m.hisProjectId} and isDel=0 ");
                                Project project=commonService.selectOne(ProjectMapper.class,sqlSentence);
                                if(project!=null){
                                    for (OrderItem orderItem : orderItems) {
                                        map.clear();
                                        map.put("itemId",itemId);
                                        if(OrderItemConstants.TYPE_PROJECT.equals(orderItem.getType())){
                                            if(orderItem.getCommonId().equals(project.getId())){
                                                UserProjectItem userProjectItem = userProjectItemMap.get(orderItem.getId());
                                                if(userProjectItem!=null){
                                                    map.put("id",userProjectItem.getId());
                                                    sqlSentence.setSqlSentence(" itemId=#{m.itemId} where id=#{m.id} and isDel=0 ");
                                                    commonService.updateWhere(UserProjectItemMapper.class,sqlSentence);
                                                }
                                            }
                                        }else if(OrderItemConstants.TYPE_PROMOTION.equals(orderItem.getType()) || OrderItemConstants.CARD_BAG.equals(orderItem.getType())){
                                            for (OrderItemSon orderItemSon : orderItemSons) {
                                                if(orderItemSon.getGoodsId().equals(project.getId())){
                                                    UserProjectItem userProjectItem = userProjectItemMap.get(orderItemSon.getId());
                                                    if(userProjectItem!=null){
                                                        map.put("id",userProjectItem.getId());
                                                        sqlSentence.setSqlSentence(" itemId=#{m.itemId} where id=#{m.id} and isDel=0 ");
                                                        commonService.updateWhere(UserProjectItemMapper.class,sqlSentence);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }else{
                                    logger.info("异步获取未执行划扣itemId提示:未找到项目信息!领建标识:{}",hisProjectId);
                                }
                            }
                        }
 
                    }
                }
            }else{
                logger.info("获取卡包标识:根据订单获取卡包信息"+returnData);
            }
        }else{
            logger.info("获取卡包信息操作解析第三方参数为空"+returnData);
        }
    }
 
    @Override
    @Async
    public void sendPublicNo(String  orderId, CommonService commonService) {
        try {
            OrdersTotal ordersTotal=commonService.selectOneByKeyBlob(OrdersTotalMapper.class,orderId);
            SqlSentence sqlSentence = new SqlSentence();
            Map<String,Object> map=new HashMap<>();
            sqlSentence.setM(map);
            map.put("isDel",BaseEntity.NO);
            map.put("orderId",orderId);
            sqlSentence.setSqlSentence("select * from consume_pay where orderId=#{m.orderId} and isDel=#{m.isDel}");
            List<ConsumePay> consumePays=commonService.selectList(ConsumePayMapper.class,sqlSentence);
            sqlSentence.setSqlSentence("select * from coupon_order_discount_log where orderId=#{m.orderId} and isDel=#{m.isDel}");
            List<CouponOrderDiscountLog> couponOrderDiscountLog=commonService.selectList(CouponOrderDiscountLogMapper.class,sqlSentence);
            String payMethod="";
            String ln="\r\n";
            if(consumePays==null ||consumePays.size()==0){
                payMethod=payMethod.concat("实付:").concat(ln).concat("1、储值金:0,").concat(ln).concat("2、增值金:0").concat(ln).concat("3、优惠券抵扣:0");
            }if(consumePays!=null && consumePays.size()>0){
                String storedValueFund="0";
                String valueAddedFund="0";
                String couponDisAmout="0";
                for (int i = 0; i < consumePays.size(); i++) {
                    ConsumePay consumePay = consumePays.get(i);
                    if(PayMethodTypeConstants.PAY_ADD_FUND.equals(consumePay.getNumberNo())){
                        valueAddedFund=consumePay.getActualTotal().toString();
                    }
                    if(PayMethodTypeConstants.PAY_STORED.equals(consumePay.getNumberNo())){
                        storedValueFund=consumePay.getActualTotal().toString();
                    }
                    if(!(PayMethodTypeConstants.PAY_ADD_FUND.equals(consumePay.getNumberNo()) || PayMethodTypeConstants.PAY_STORED.equals(consumePay.getNumberNo()))){
                        int num=i+4;
                        if(i==consumePays.size()-1){
                            if(PayMethodTypeConstants.PAY_CARD.equals(consumePay.getNumberNo())){
                                payMethod=payMethod+num+"、"+consumePay.getName()+":"+"-";
                            }else{
                                payMethod=payMethod+num+"、"+consumePay.getName()+":"+consumePay.getActualTotal();
                            }
                        }else {
                            payMethod=payMethod+num+"、"+consumePay.getName()+":"+consumePay.getActualTotal()+ln;
                        }
                    }
                }
                if(couponOrderDiscountLog!=null && couponOrderDiscountLog.size()>0){
                    couponDisAmout=couponOrderDiscountLog.stream().collect(Collectors.summingDouble(o->o.getDiscountTotal().doubleValue())).toString();
//                    couponDisAmout=couponOrderDiscountLog.getDiscountTotal().toString();
                }
                payMethod="实付:"+ln+String.format("1、储值金: %s "+ln+"2、增值金: %s "+ln+"3、优惠券抵扣: %s "+ln,storedValueFund,valueAddedFund,couponDisAmout).concat(payMethod);
            }
            if(ordersTotal!=null) {
                GzhTemplateVO gzhTemplateVO = new GzhTemplateVO();
 
                UserUnionHis unionHis = getUserUnionHisByUserId(ordersTotal.getUserId());
                if (unionHis ==null || StringUtils.isEmpty(unionHis.getOpenId())) {
                    logger.info("结账发送用户公众号消息失败,该用户没有openId,用户标识:{}", ordersTotal.getUserId());
                    return;
                }
                JSONObject object = new JSONObject();
                JSONObject first = new JSONObject();
                first.put("value", "您好,您的订单已付款成功,点击查看明细");
                object.put("first", first);
 
                String status = OrderTotalConstants.STATUS_PAY == ordersTotal.getStatus() ? "已支付" : "";
 
                JSONObject keyword1 = new JSONObject();
                keyword1.put("value", ordersTotal.getOrderNo());
                object.put("keyword1", keyword1);
 
                JSONObject keyword2 = new JSONObject();
                keyword2.put("value", status);
                object.put("keyword2", keyword2);
 
                JSONObject keyword3 = new JSONObject();
                // 卡包订单不显示金额
                Object shouldTotal;
                if (OrderTotalConstants.TYPE_CARD_BAG.equals(ordersTotal.getType())){
                    shouldTotal = "-";
                } else {
                    // 保留两位小数处理
                    DecimalFormat df = new DecimalFormat("#,##0.00");
                    shouldTotal = df.format(ordersTotal.getShouldTotal());
                }
                keyword3.put("value", shouldTotal);
                object.put("keyword3", keyword3);
 
                JSONObject keyword4 = new JSONObject();
                keyword4.put("value", DateUtil.formatDate(ordersTotal.getCreateTime(),"yyyy-MM-dd HH:mm"));
                object.put("keyword4", keyword4);
 
                // remark 备注
                JSONObject remark = new JSONObject();
                remark.put("value", payMethod);
                object.put("remark", remark);
 
                //String url = String.format("/pages/Order_Description/order_payment?hisId=%s", ordersTotal.getId());
                //2023-02-06 批量确定订单
                String url = "/packages/order/orderConfirm";
 
                gzhTemplateVO.setTouser(unionHis.getOpenId());
                if(PlatformPattern.PROD.equals(customParameter.getPlatformPattern())){
                    gzhTemplateVO.setTemplateId("NWnxYJ_3gNV0OAxtmYWcf5cB12qFMUnLYmqoKFrkp4I");
//                    gzhTemplateVO.setTemplateId("5GqBNAWzbln7IlGR0I0SouA8IU8xVciy7w2iLt-zxBI");
                }else{
                    gzhTemplateVO.setTemplateId("5GqBNAWzbln7IlGR0I0SouA8IU8xVciy7w2iLt-zxBI");
                }
                gzhTemplateVO.setUrl(url);
                gzhTemplateVO.setType(1);
                gzhTemplateVO.setData(object.toJSONString());
                logger.info("请求发送公众号通知方法-打印请求发送公众号通知参数:{}", JSONObject.toJSONString(gzhTemplateVO));
                Result result = sGzhTemplateService.template(gzhTemplateVO);
                logger.info("请求发送公众号通知方法-返回数据:{}", JSONObject.toJSONString(result));
                if (result != null) {
                    result.checkTips();
                } else {
                    throw new TipsException("请求发送公众号通知方法,返回数据为空!");
                }
            }
        }catch (Exception e){
            logger.error("结账发送用户公众号消息失败",e.getMessage(),e);
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账发送用户公众号消息失败!");
        }
    }
 
    @Override
    @Async
    public void sentSMSInfo(String  orderId, CommonService commonService){
        // 跳转链接
        String secondaryItemStr = getSMSUrl();
        // 添加定时器任务处理
        TimerHandleTool.addTask(commonService, TimerHandleItem.TYPE_ORDER_CONFIRM_SMS_INFO, orderId, secondaryItemStr);
    }
 
    /**
     * 生成需要发送短信的地址
     * @return 返回
     */
    private String getSMSUrl() {
        // 生成小程序链接
        String urlLink = null;
        // 正式区在拿取链接
        if (PlatformPattern.PROD.equals(customParameter.getPlatformPatternMoney())) {
            // 获取用户CRM小程序token
            ApplyParameter applyParameter = ApplyParameterTool.getMpParameter("wx71e6babac80abcee", commonService);
            if (applyParameter == null) {
                throw new PlatTipsException(PlatformCode.ERROR_TIPS, "mpId is error");
            }
            // 获取范围密钥
            SysParameter sysParameter = systemParameterService.getAccessToken(applyParameter.getMpAppId(), applyParameter.getMpSecretKey());
            if (sysParameter == null) {
                throw new PlatTipsException(PlatformCode.ERROR_SYSTEM, "服务错误" + SystemCode.ERROR_GET_CORP_TOKEN);
            }
 
            // 更换链接 原CRM 1.0 /pages/recharge/incrementInfo
            String result = SendSMSTool.getAooLetUrl(sysParameter.getParamValue(), "/packages/order/orderConfirm", "", "release");
            if (!StringUtils.isEmpty(result)) {
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject.getInteger("errcode") != 0) {
                    throw new PlatTipsException(PlatformCode.ERROR_SYSTEM, "生成短信小程序路径错误:" + jsonObject.getString("msg") + SystemCode.ERROR_GET_CORP_TOKEN);
                }
                urlLink = jsonObject.getString("url_link");
            }
        } else {
            // 测试区跳转百度
            urlLink = "https://wxaurl.cn/6666";
        }
        return urlLink;
    }
 
    @Override
    @Async
    public void sendUserConsultant(String userId,String orderNo,String orderId,JSONObject commissionObject, CommonService commonService) {
        OrdersTotal ordersTotal=commonService.selectOneByKeyBlob(OrdersTotalMapper.class,orderId);
        if(ordersTotal!=null){
            try {
                SqlSentence sqlSentence = new SqlSentence();
                Map<String,Object> map=new HashMap<>();
                sqlSentence.setM(map);
                map.put("orderId",ordersTotal.getId());
                map.put("isDel",BaseEntity.NO);
                sqlSentence.setSqlSentence("select * from orders_info where orderId=#{m.orderId} and isDel=#{m.isDel}");
                OrderInfo orderInfo = commonService.selectOne(OrderInfoMapper.class, sqlSentence);
                if(orderInfo!=null && orderInfo.getIsOldBringNew()==null){
                    orderInfo.setIsOldBringNew(BaseEntity.NO);
                }
                User user=commonService.selectOneByKeyBlob(UserMapper.class,userId);
                if(user!=null && StringUtils.noNull(user.getHisCorpUserId())){
                    Employee employee=commonService.selectOneByKeyBlob(EmployeeMapper.class,user.getHisCorpUserId());
                    if(employee!=null && StringUtils.noNull(employee.getUserId())){
                        // 企业微信员工标识有更新时推送企业微信消息
                        // 获取token
                        String at = AppoitmentWeiXinCorpMpUtil.getApplicationAccessToken(customParameter.getCorpAppId(),customParameter.getCorpMpSecret(),commonService);
                        if (at != null && orderInfo.getIsOldBringNew()==BaseEntity.YES) {
                            BigDecimal newMoney=commissionObject.getBigDecimal("beInviterMoney")==null?BigDecimal.ZERO:commissionObject.getBigDecimal("beInviterMoney");
                            BigDecimal oldMoney=commissionObject.getBigDecimal("inviterMoney")==null?BigDecimal.ZERO:commissionObject.getBigDecimal("inviterMoney");
                            String oldUserName=StringUtils.isEmpty(commissionObject.getString("oldUserName"))?"":commissionObject.getString("oldUserName");
                            String newUserNmae=StringUtils.isEmpty(commissionObject.getString("newUserName"))?"":commissionObject.getString("newUserName");
                            String sendDate = MessageTemplate.sendIsOldUserConsultant(employee.getUserId(),orderNo, customParameter.getCorpMpAppId(), newMoney,oldMoney,oldUserName,newUserNmae);
                            SendMessageTool.sendMessge(sendDate,at);
                        }else if(at!=null){
                            String sendDate = MessageTemplate.sendUserConsultant(employee.getUserId(),orderNo, customParameter.getCorpMpAppId(), user.getName());
                            SendMessageTool.sendMessge(sendDate,at);
                        }
                    }else{
                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账成功发送企业微信通知给用户所属顾问,员工找不到userId!");
                    }
                }else{
                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账成功发送企业微信通知给用户所属顾问,用户找不到或者用户所属顾问为空!");
                }
            }catch (Exception e){
                logger.error("结账成功发送企业微信通知给用户所属顾问消息失败",e);
                throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账成功发送企业微信通知给用户所属顾问消息失败!");
            }
        }else{
            logger.error("结账成功发送企业微信通知给用户所属顾问消息失败,未找到总订单信息!订单标识:{}",orderId);
            throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账成功发送企业微信通知给用户所属顾问消息失败,未找到总订单信息!");
        }
    }
 
    @Override
    public void newMarketingRejectAduit(Integer type,String commonId, Integer commonType, String examEmplId, String examEmplName) {
        JbpmParamUtil.newMarketingRejectAduit(type,commonId,commonType,examEmplId,examEmplName,commonService);
    }
 
    @Override
    public void newMarketingSuccessAduit(Integer type,String commonId, Integer commonType, String examEmplId, String examEmplName) {
        JbpmParamUtil.newMarketingSuccessAduit(type,commonId,commonType,examEmplId,examEmplName,commonService);
    }
 
    @Override
    public void statementPerformanceInfo(String orderId) {
        logger.info("进入保存报表");
 
        //新增收录确认表
        PerformanceInfoTool.handOrderPerformanceInfo(commonService,orderId ,BaseEntity.NO);
    }
 
    @Override
    public void statementConsultantCash(String orderId) {
        //记录咨询师现金业绩报表数据
        ConsultantCashReportTool.handConsultantCash(commonService, orderId);
    }
 
    /**
     * 获取用户的openId
     * @param userId 用户id
     * @return 返回
     */
    private UserUnionHis getUserUnionHisByUserId(String userId){
        SqlSentence sqlSentence = new SqlSentence();
        Map<String, Object> sqlValue = new HashMap<>();
        sqlValue.put("isDel", BaseEntity.NO);
        sqlValue.put("userId", userId);
        String sql = "SELECT openId from gzh_focus_record WHERE userId = #{m.userId} AND isDel = #{m.isDel} ORDER BY createTime DESC LIMIT 1";
        sqlSentence.sqlSentence(sql, sqlValue);
        return commonService.selectOne(UserUnionHisMapper.class, sqlSentence);
    }
 
    /**
     * 订单操作后自动打标签
     * @param userId 用户id
     */
    @Override
    public void autoTag(String userId) {
        try {
            logger.info("处理订单操作后自动打标签, 用户id:{}", userId);
            // 创建用户已消费项目标签
            UserLabelTool.builderOrderProjectTag(sUserTagInfoService, commonService, userId);
        }  catch (Exception ex) {
            logger.error("处理订单操作后自动打标签失败,用户id:{}", userId, ex);
        }
    }
 
    /** 计算订单应付金额 */
    @Override
    public Map<String, Object> countOrderShouldTotal(Shop shop, List<OrderItem> orderItemList) {
        //总订单订单售价总金额
        BigDecimal totalPrice=BigDecimal.ZERO;
        //总订单订单原价总金额
        BigDecimal oriTotal=BigDecimal.ZERO;
        //总订单应付支付总金额
        BigDecimal shouldOrderTotal=BigDecimal.ZERO;
        //总订单的折扣金额
        BigDecimal discountTotal=BigDecimal.ZERO;
        //调用处理方法获取计算后的金额信息
        Map<String, Object> handOrderItemMap = OrderCreateUtil.handOrderItem(null, shop,null, orderItemList, totalPrice, shouldOrderTotal,discountTotal,oriTotal, commonService, systemParameterMapper);
        return handOrderItemMap;
    }
}