Pu Zhibing
2025-04-03 22839ef1aee121cb9b96f4db3b0930667595022f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
package com.ruoyi.order.service.impl;
 
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.account.api.feignClient.*;
import com.ruoyi.account.api.model.*;
import com.ruoyi.account.api.vo.CouponInfoVo;
import com.ruoyi.account.api.vo.PaymentUserCoupon;
import com.ruoyi.account.api.vo.PaymentUserCouponVo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.order.event.PayEvent;
import com.ruoyi.order.mapper.ShoppingCartMapper;
import com.ruoyi.order.model.Order;
import com.ruoyi.order.model.OrderBalancePayment;
import com.ruoyi.order.model.OrderGood;
import com.ruoyi.order.model.ShoppingCart;
import com.ruoyi.order.service.*;
import com.ruoyi.order.util.payment.PaymentUtil;
import com.ruoyi.order.util.payment.model.CloseOrderResult;
import com.ruoyi.order.util.payment.model.UniPayCallbackResult;
import com.ruoyi.order.util.payment.model.UniPayResult;
import com.ruoyi.order.vo.*;
import com.ruoyi.other.api.domain.*;
import com.ruoyi.other.api.feignClient.*;
import com.ruoyi.other.api.vo.GetGoodsBargainPrice;
import com.ruoyi.other.api.vo.GetGoodsShopByGoodsIds;
import com.ruoyi.other.api.vo.GetSeckillActivityInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
@Slf4j
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
 
    @Resource
    private TokenService tokenService;
 
    @Resource
    private GoodsClient goodsClient;
 
    @Resource
    private GoodsShopClient goodsShopClient;
 
    @Resource
    private AppUserClient appUserClient;
 
    @Resource
    private GoodsAreaClient goodsAreaClient;
 
    @Resource
    private GoodsVipClient goodsVipClient;
 
    @Resource
    private SeckillActivityInfoClient seckillActivityInfoClient;
 
    @Resource
    private GoodsBargainPriceClient goodsBargainPriceClient;
 
    @Resource
    private OrderService orderService;
 
    @Resource
    private OrderGoodService orderGoodService;
 
    @Resource
    private ShopClient shopClient;
 
    @Resource
    private OrderActivityInfoClient orderActivityInfoClient;
 
    @Resource
    private BaseSettingClient baseSettingClient;
 
    @Resource
    private UserAddressClient userAddressClient;
 
    @Resource
    private UserCouponClient userCouponClient;
 
    @Resource
    private SystemConfigClient systemConfigClient;
 
    @Resource
    private UserPointClient userPointClient;
 
    @Resource
    private BalanceChangeRecordClient balanceChangeRecordClient;
 
    @Resource
    private CommissionService commissionService;
 
    @Resource
    private PointSettingClient pointSettingClient;
    
    @Resource
    private OrderBalancePaymentService orderBalancePaymentService;
    
    @Resource
    private RedisTemplate redisTemplate;
 
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;
    
    
    
    
    
    
    
    
    /**
     * 获取购物车列表
     * @param type
     * @param shopId
     * @return
     */
    @Override
    public List<MyShoppingCartVo> getMyShoppingCart(Integer type, Integer shopId) {
        Long userid = tokenService.getLoginUserApplet().getUserid();
        AppUser appUser = appUserClient.getAppUserById(userid);
        //获取对应类型的商品数据
        List<Goods> data = goodsClient.getGoodsByType(type).getData();
        if(null == data){
            throw new RuntimeException("根据类型(1=服务商品,2=单品商品)获取商品数据失败");
        }
        List<Integer> goodsIds = data.stream().map(Goods::getId).collect(Collectors.toList());
        if(goodsIds.isEmpty()){
            return new ArrayList<>();
        }
        //查询符合商品类型的商品数据
        List<ShoppingCart> list = this.list(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getAppUserId, userid)
                .in(ShoppingCart::getGoodsId, goodsIds).eq(ShoppingCart::getStatus, 1));
        //删除过期的秒杀活动商品
        List<ShoppingCart> list1 = new ArrayList<>();
        for (ShoppingCart shoppingCart : list) {
            if(shoppingCart.getType() == 2){
                GetSeckillActivityInfo info = new GetSeckillActivityInfo();
                info.setGoodsId(shoppingCart.getGoodsId());
                info.setVip(appUser.getVipId());
                GoodsSeckill data1 = seckillActivityInfoClient.getSeckillActivityInfo(info).getData();
                if(null != data1){
                    SeckillActivityInfo seckillActivityInfo = seckillActivityInfoClient.getSeckillActivityInfoById(data1.getSeckillActivityInfoId()).getData();
                    if(null != seckillActivityInfo && (seckillActivityInfo.getIsShelves() == 1 &&
                            seckillActivityInfo.getStartTime().isBefore(LocalDateTime.now()) && seckillActivityInfo.getEndTime().isAfter(LocalDateTime.now()))){
                        
                        list1.add(shoppingCart);
                        continue;
                    }
                }
                this.removeById(shoppingCart.getId());
            }else{
                list1.add(shoppingCart);
            }
        }
        
        //构建返回数据
        List<MyShoppingCartVo> page = buildDetail(appUser, shopId, list1, null);
        return page;
    }
 
 
    /**
     * 获取支付价格
     * @param appUser
     * @param goodsId
     * @param shopId
     * @return
     */
    public Price getPrice(AppUser appUser, Integer goodsId, Integer type, Integer shopId){
        //获取支付价格
        //秒杀活动>门店特价>地区价格>会员价格
        //判断是否有秒杀活动
        Price price = new Price();
        GetSeckillActivityInfo info = new GetSeckillActivityInfo();
        info.setGoodsId(goodsId);
        info.setVip(appUser.getVipId());
        GoodsSeckill goodsSeckill = seckillActivityInfoClient.getSeckillActivityInfo(info).getData();
        //没有秒杀活动或者添加的普通商品则不使用秒杀活动价格
        if((null == goodsSeckill || (null == goodsSeckill.getCashPayment() && null == goodsSeckill.getPointPayment())) || type == 1){
            //没有秒杀价,则判断门店特价
            GetGoodsBargainPrice goodsBargainPrice = new GetGoodsBargainPrice();
            goodsBargainPrice.setGoodsId(goodsId);
            goodsBargainPrice.setVip(appUser.getVipId());
            GoodsBargainPriceDetail bargainPriceDetail = null;
            if (shopId != null){
                goodsBargainPrice.setShopId(shopId);
                bargainPriceDetail = goodsBargainPriceClient.getGoodsBargainPrice(goodsBargainPrice).getData();
            }
            if(null == bargainPriceDetail){
                //没有门店特价,判断地区价格配置
                GoodsArea area = new GoodsArea();
                area.setDistrictsCode(appUser.getDistrictCode());
                area.setCityCode(appUser.getCityCode());
                area.setProvinceCode(appUser.getProvinceCode());
                area.setVip(appUser.getVipId());
                area.setGoodsId(goodsId);
                GoodsArea goodsArea = goodsAreaClient.getGoodsArea(area).getData();
                if(null == goodsArea || (null == goodsArea.getCashPayment() && null == goodsArea.getPointPayment())){
                    //没有地区价格,则使用会员价格
                    GoodsVip goodsVip = goodsVipClient.getGoodsVip(goodsId, appUser.getVipId()).getData();
                    if(null == goodsVip || (null == goodsVip.getCashPayment() && null == goodsVip.getPointPayment())){
                        //没有配置价格,直接使用原始基础价格
                        return null;
                    }else{
                        price.setCash(goodsVip.getSellingPrice());
                        price.setPoint(goodsVip.getIntegral());
                        price.setCashPayment(null != goodsVip.getCashPayment() && goodsVip.getCashPayment() == 1);
                        price.setPointPayment(null != goodsVip.getPointPayment() && goodsVip.getPointPayment() == 1);
                        price.setEarnSpendingPoints(goodsVip.getEarnSpendingPoints());
                        price.setSuperiorSubcommission(goodsVip.getSuperiorSubcommission());
                        price.setSuperiorRebatePoints(goodsVip.getSuperiorRebatePoints());
                        price.setSuperiorType(goodsVip.getSuperiorType());
                        price.setSuperiorPriceType(goodsVip.getSuperiorPriceType());
                        price.setServuceShopCharges(goodsVip.getServuceShopCharges());
                        price.setServuceShopPoints(goodsVip.getServuceShopPoints());
                        price.setTechnicianPoints(goodsVip.getTechnicianPoints());
                        price.setBoundShopCharges(goodsVip.getBoundShopCharges());
                        price.setBoundShopPoints(goodsVip.getBoundShopPoints());
                        price.setBoundShopSuperiorsCharges(goodsVip.getBoundShopSuperiorsCharges());
                        price.setBoundShopSuperiorsPoints(goodsVip.getBoundShopSuperiorsPoints());
                    }
                }else{
                    price.setCash(goodsArea.getSellingPrice());
                    price.setPoint(goodsArea.getIntegral());
                    price.setCashPayment(null !=goodsArea.getCashPayment() && goodsArea.getCashPayment() == 1);
                    price.setPointPayment(null !=goodsArea.getPointPayment() && goodsArea.getPointPayment() == 1);
                    price.setEarnSpendingPoints(goodsArea.getEarnSpendingPoints());
                    price.setSuperiorSubcommission(goodsArea.getSuperiorSubcommission());
                    price.setSuperiorRebatePoints(goodsArea.getSuperiorRebatePoints());
                    price.setSuperiorType(goodsArea.getSuperiorType());
                    price.setSuperiorPriceType(goodsArea.getSuperiorPriceType());
                    price.setServuceShopCharges(goodsArea.getServuceShopCharges());
                    price.setServuceShopPoints(goodsArea.getServuceShopPoints());
                    price.setTechnicianPoints(goodsArea.getTechnicianPoints());
                    price.setBoundShopCharges(goodsArea.getBoundShopCharges());
                    price.setBoundShopPoints(goodsArea.getBoundShopPoints());
                    price.setBoundShopSuperiorsCharges(goodsArea.getBoundShopSuperiorsCharges());
                    price.setBoundShopSuperiorsPoints(goodsArea.getBoundShopSuperiorsPoints());
                }
            }else{
                price.setCash(bargainPriceDetail.getSellingPrice());
                price.setPoint(bargainPriceDetail.getIntegral());
                price.setCashPayment(bargainPriceDetail.getSellingPrice() != null);
                price.setPointPayment(bargainPriceDetail.getIntegral() != null);
                //门店特价,消费积分使用会员等级的消费积分
                GoodsArea area = new GoodsArea();
                area.setDistrictsCode(appUser.getDistrictCode());
                area.setCityCode(appUser.getCityCode());
                area.setProvinceCode(appUser.getProvinceCode());
                area.setVip(appUser.getVipId());
                GoodsArea goodsArea = goodsAreaClient.getGoodsArea(area).getData();
                if(null != goodsArea){
                    price.setEarnSpendingPoints(goodsArea.getEarnSpendingPoints());
                    price.setSuperiorSubcommission(goodsArea.getSuperiorSubcommission());
                    price.setSuperiorRebatePoints(goodsArea.getSuperiorRebatePoints());
                    price.setSuperiorType(goodsArea.getSuperiorType());
                    price.setSuperiorPriceType(goodsArea.getSuperiorPriceType());
                    price.setServuceShopCharges(goodsArea.getServuceShopCharges());
                    price.setServuceShopPoints(goodsArea.getServuceShopPoints());
                    price.setTechnicianPoints(goodsArea.getTechnicianPoints());
                    price.setBoundShopCharges(goodsArea.getBoundShopCharges());
                    price.setBoundShopPoints(goodsArea.getBoundShopPoints());
                    price.setBoundShopSuperiorsCharges(goodsArea.getBoundShopSuperiorsCharges());
                    price.setBoundShopSuperiorsPoints(goodsArea.getBoundShopSuperiorsPoints());
                }else{
                    GoodsVip goodsVip = goodsVipClient.getGoodsVip(goodsId, appUser.getVipId()).getData();
                    price.setEarnSpendingPoints(goodsVip.getEarnSpendingPoints());
                    price.setSuperiorSubcommission(goodsVip.getSuperiorSubcommission());
                    price.setSuperiorRebatePoints(goodsVip.getSuperiorRebatePoints());
                    price.setSuperiorType(goodsVip.getSuperiorType());
                    price.setSuperiorPriceType(goodsVip.getSuperiorPriceType());
                    price.setServuceShopCharges(goodsVip.getServuceShopCharges());
                    price.setServuceShopPoints(goodsVip.getServuceShopPoints());
                    price.setTechnicianPoints(goodsVip.getTechnicianPoints());
                    price.setBoundShopCharges(goodsVip.getBoundShopCharges());
                    price.setBoundShopPoints(goodsVip.getBoundShopPoints());
                    price.setBoundShopSuperiorsCharges(goodsVip.getBoundShopSuperiorsCharges());
                    price.setBoundShopSuperiorsPoints(goodsVip.getBoundShopSuperiorsPoints());
                }
            }
        }else{
            //构建价格数据
            if(goodsSeckill.getCashPayment() == 1 && goodsSeckill.getPointPayment() == 1){
                price.setCash(goodsSeckill.getSellingPrice());
                price.setPoint(goodsSeckill.getIntegral());
            }
            if(goodsSeckill.getCashPayment() == 1 && goodsSeckill.getPointPayment() == 0){
                price.setCash(goodsSeckill.getSellingPrice());
            }
            if(goodsSeckill.getCashPayment() == 0 && goodsSeckill.getPointPayment() == 1){
                price.setPoint(goodsSeckill.getIntegral());
            }
            price.setCashPayment(null != goodsSeckill.getCashPayment() && goodsSeckill.getCashPayment() == 1);
            price.setPointPayment(null != goodsSeckill.getPointPayment() && goodsSeckill.getPointPayment() == 1);
            price.setEndTime(goodsSeckill.getEndTime());
            price.setEarnSpendingPoints(goodsSeckill.getEarnSpendingPoints());
            price.setSuperiorSubcommission(goodsSeckill.getSuperiorSubcommission());
            price.setSuperiorRebatePoints(goodsSeckill.getSuperiorRebatePoints());
            price.setSuperiorType(goodsSeckill.getSuperiorType());
            price.setSuperiorPriceType(goodsSeckill.getSuperiorPriceType());
            price.setServuceShopCharges(goodsSeckill.getServuceShopCharges());
            price.setServuceShopPoints(goodsSeckill.getServuceShopPoints());
            price.setTechnicianPoints(goodsSeckill.getTechnicianPoints());
            price.setBoundShopCharges(goodsSeckill.getBoundShopCharges());
            price.setBoundShopPoints(goodsSeckill.getBoundShopPoints());
            price.setBoundShopSuperiorsCharges(goodsSeckill.getBoundShopSuperiorsCharges());
            price.setBoundShopSuperiorsPoints(goodsSeckill.getBoundShopSuperiorsPoints());
        }
        return price;
    }
 
 
 
 
    @Override
    public Long addGoods(ShoppingCart shoppingCart) {
        Long userid = tokenService.getLoginUserApplet().getUserid();
        long goodsSaleNum = orderService.getGoodsSaleNum(shoppingCart.getGoodsId(), null, userid);
        long count = count(new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getGoodsId, shoppingCart.getGoodsId())
                .eq(ShoppingCart::getStatus,1)
                .eq(ShoppingCart::getAppUserId, userid));
        goodsSaleNum += count;
        Goods goods = goodsClient.getGoodsById(shoppingCart.getGoodsId()).getData();
 
        Integer maxNum = 0;
        if(shoppingCart.getType() == 2){
            R<SeckillActivityInfo> r = seckillActivityInfoClient.getSeckillActivityInfoByGoodsId(shoppingCart.getGoodsId());
            if (R.isError(r)){
                throw new ServiceException("获取秒杀商品失败!");
            }
            SeckillActivityInfo seckillActivityInfo = r.getData();
            maxNum = seckillActivityInfo.getMaxNum();
        }else {
            maxNum = goods.getPurchaseLimit();
        }
 
        if(null != goods.getPurchaseLimit() && -1 != maxNum && (goodsSaleNum + shoppingCart.getNumber()) > maxNum){
            throw new ServiceException("超出购买数量限制");
        }
        ShoppingCart one = this.getOne(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getAppUserId, userid)
                .eq(ShoppingCart::getGoodsId, shoppingCart.getGoodsId()).eq(ShoppingCart::getType, shoppingCart.getType()).eq(ShoppingCart::getStatus, 1));
        if(null != one){
            one.setNumber(one.getNumber() + shoppingCart.getNumber());
            this.updateById(one);
            return one.getId();
        }else{
            shoppingCart.setAppUserId(userid);
            shoppingCart.setStatus(1);
            this.save(shoppingCart);
            return shoppingCart.getId();
        }
    }
 
 
    /**
     * 修改购物车数量
     * @param setGoodsNumber
     * @return
     */
    @Override
    public R setGoodsNumber(SetGoodsNumber setGoodsNumber) {
 
        ShoppingCart shoppingCart = this.getById(setGoodsNumber.getId());
        if(0 >= setGoodsNumber.getNumber()){
            return R.fail("修改数量不能小于等于0");
        }
 
        if(null != shoppingCart){
 
            Goods goods1 = goodsClient.getGoodsById(shoppingCart.getGoodsId()).getData();
            if(null != goods1.getPurchaseLimit() && -1 != goods1.getPurchaseLimit()
                    && goods1.getPurchaseLimit() < setGoodsNumber.getNumber()
                    && setGoodsNumber.getNumber() >= shoppingCart.getNumber()){
                return R.fail("修改数量不能大于限购数量");
            }
 
            shoppingCart.setNumber(setGoodsNumber.getNumber());
            this.updateById(shoppingCart);
        }
        return R.ok();
    }
 
 
    /**
     * 确认购物车订单
     * @param confirmOrder
     * @return
     */
    @Override
    public ConfirmOrderVo confirmOrder(ConfirmOrder confirmOrder) {
        Integer position = confirmOrder.getPosition();
        Long userid = tokenService.getLoginUserApplet().getUserid();
        //直接购买商品
        if(2 == position){
            //先加入购物车
            String goodsJson = confirmOrder.getGoodsJson();
            JSONArray objects = JSON.parseArray(goodsJson);
            Long id = objects.getJSONObject(0).getLong("id");
            Integer num1 = objects.getJSONObject(0).getInteger("num");
            Integer type = objects.getJSONObject(0).getInteger("type");
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setAppUserId(userid);
            shoppingCart.setGoodsId(id.intValue());
            shoppingCart.setNumber(num1);
            shoppingCart.setType(type);
            shoppingCart.setStatus(0);
            this.save(shoppingCart);
            confirmOrder.setGoodsJson("[{\"id\": " + shoppingCart.getId() + ", \"num\": " + num1 + ",\"type\":" + type + "}]");
        }
        AppUser appUser = appUserClient.getAppUserById(userid);
        Integer shopId = confirmOrder.getShopId();
        Shop shop = shopClient.getShopById(shopId).getData();
        String goodsJson = confirmOrder.getGoodsJson();
        List<Long> ids = new ArrayList<>();
        JSONArray objects = JSON.parseArray(goodsJson);
        for (int i = 0; i < objects.size(); i++) {
            Long id = objects.getJSONObject(i).getLong("id");
            ids.add(id);
        }
        List<ShoppingCart> list = this.listByIds(ids);
        ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo();
        //构建商品明细列表
        List<MyShoppingCartVo> goodsList = buildDetail(appUser, shopId, list, objects);
        confirmOrderVo.setGoodsList(goodsList);
        confirmOrderVo.setShopId(confirmOrder.getShopId());
        confirmOrderVo.setShopName(shop.getName());
        //现金支付
        if(confirmOrder.getPaymentType() == 1){
            BigDecimal bigDecimal = BigDecimal.ZERO;
            for (MyShoppingCartVo myShoppingCartVo : goodsList) {
                bigDecimal = bigDecimal.add(myShoppingCartVo.getCash().multiply(new BigDecimal(myShoppingCartVo.getNumber())));
            }
            confirmOrderVo.setOrderMoney(bigDecimal);
        }else{
            int sum = 0;
            for (MyShoppingCartVo myShoppingCartVo : goodsList) {
                sum += ((null != myShoppingCartVo.getPoint() ? myShoppingCartVo.getPoint() : 0) * myShoppingCartVo.getNumber());
            }
            confirmOrderVo.setOrderPoint(sum);
        }
 
        BigDecimal orderMoney = confirmOrderVo.getOrderMoney();
        BigDecimal paymentMoney = orderMoney;
        //总优惠金额
        BigDecimal activityAmount = BigDecimal.ZERO;
 
        BaseSetting baseSetting = baseSettingClient.getBaseSetting(4).getData();
        confirmOrderVo.setUseSimultaneously(JSON.parseObject(baseSetting.getContent()).getInteger("status") == 1);
        //减去优惠券优惠金额
        CouponInfoVo couponInfoVo = null;
        if(null != confirmOrder.getCouponId() && 2 != confirmOrder.getPaymentType()){
            couponInfoVo = userCouponClient.getCouponInfo(confirmOrder.getCouponId()).getData();
            String forGoodIds = couponInfoVo.getForGoodIds();
            String[] split = forGoodIds.split(",");
            List<String> parseArray = Arrays.asList(split);
            //全部商品
            if("-1".equals(forGoodIds)){
                //满减
                if(1 == couponInfoVo.getCouponType() && couponInfoVo.getConditionAmount().compareTo(paymentMoney) <= 0){
                    paymentMoney = paymentMoney.subtract(couponInfoVo.getDiscountAmount());
                    activityAmount = activityAmount.add(couponInfoVo.getDiscountAmount());
                }
                //代金券
                if(2 == couponInfoVo.getCouponType()){
                    paymentMoney = paymentMoney.subtract(couponInfoVo.getMoneyAmount());
                    activityAmount = activityAmount.add(couponInfoVo.getMoneyAmount());
                    if(paymentMoney.compareTo(BigDecimal.ZERO) < 0){
                        paymentMoney = BigDecimal.ZERO;
                    }
                }
                //折扣券
                if(3 == couponInfoVo.getCouponType()){
                    BigDecimal paymentMoney1 = couponInfoVo.getDiscount().divide(new BigDecimal(10)).multiply(paymentMoney);
                    BigDecimal bigDecimal = paymentMoney.subtract(paymentMoney1).setScale(2, RoundingMode.HALF_EVEN);
                    paymentMoney = paymentMoney1;
                    activityAmount = activityAmount.add(bigDecimal);
                }
            }else{
                //部分商品,需要计算参与优惠商品的支付金额,然后再对商品进行优惠券处理
                paymentMoney = BigDecimal.ZERO;
                BigDecimal goodsMoney = BigDecimal.ZERO;
                for (MyShoppingCartVo myShoppingCartVo : goodsList) {
                    String goodsId = myShoppingCartVo.getGoodsId().toString();
                    BigDecimal cash = myShoppingCartVo.getCash().multiply(new BigDecimal(myShoppingCartVo.getNumber()));
                    if(parseArray.contains(goodsId)){
                        goodsMoney = goodsMoney.add(cash);
                    }else{
                        paymentMoney = paymentMoney.add(cash);
                    }
                }
 
                //满减
                if(1 == couponInfoVo.getCouponType() && couponInfoVo.getConditionAmount().compareTo(goodsMoney) <= 0){
                    goodsMoney = goodsMoney.subtract(couponInfoVo.getDiscountAmount());
                    activityAmount = activityAmount.add(couponInfoVo.getDiscountAmount());
                }
                //代金券
                if(2 == couponInfoVo.getCouponType()){
                    goodsMoney = goodsMoney.subtract(couponInfoVo.getMoneyAmount());
                    activityAmount = activityAmount.add(couponInfoVo.getMoneyAmount());
                    if(goodsMoney.compareTo(BigDecimal.ZERO) < 0){
                        goodsMoney = BigDecimal.ZERO;
                    }
                }
                //折扣券
                if(3 == couponInfoVo.getCouponType()){
                    BigDecimal paymentMoney1 = couponInfoVo.getDiscount().divide(new BigDecimal(10)).multiply(goodsMoney);
                    BigDecimal bigDecimal = goodsMoney.subtract(paymentMoney1).setScale(2, RoundingMode.HALF_EVEN);
                    goodsMoney = paymentMoney1;
                    activityAmount = activityAmount.add(bigDecimal);
                }
                paymentMoney = paymentMoney.add(goodsMoney);
            }
        }
 
        //查询当前是否有订单活动
        List<OrderActivityInfo> orderActivityInfo = orderActivityInfoClient.getNowOrderActivityInfo(appUser.getVipId()).getData();
        //满XX才打折,只有现金才能优惠
        if((confirmOrderVo.getUseSimultaneously() || (!confirmOrderVo.getUseSimultaneously() && activityAmount.equals(BigDecimal.ZERO)))
                && null != orderActivityInfo && confirmOrder.getPaymentType() == 1){
            BigDecimal zyh = BigDecimal.ZERO;
            OrderActivityInfo activityInfo1 = null;
            for (OrderActivityInfo activityInfo : orderActivityInfo) {
                if(activityInfo.getConditionAmount().compareTo(paymentMoney) <= 0){
                    //优惠后的支付金额
                    BigDecimal multiply = activityInfo.getDiscount().divide(new BigDecimal(10)).multiply(paymentMoney);
                    //优惠金额
                    BigDecimal bigDecimal = paymentMoney.subtract(multiply).setScale(2, RoundingMode.HALF_EVEN);
                    if(bigDecimal.compareTo(zyh) > 0){
                        zyh = bigDecimal;
                        activityInfo1 = activityInfo;
                    }
                }
            }
 
            if(null != activityInfo1){
                confirmOrderVo.setActivityName(activityInfo1.getActivityName());
                paymentMoney = paymentMoney.subtract(zyh);
                activityAmount = activityAmount.add(zyh);
            }
        }
        confirmOrderVo.setDiscountAmount(activityAmount);
        int earnPoint = goodsList.stream().mapToInt(MyShoppingCartVo::getEarnSpendingPoints).sum();
        confirmOrderVo.setEarnPoint(earnPoint);
        if(null != paymentMoney && BigDecimal.ZERO.compareTo(paymentMoney) > 0){
            paymentMoney = BigDecimal.ZERO;
        }
 
        //支付金额,订单金额-订单优惠
        confirmOrderVo.setPayMoney(paymentMoney);
        confirmOrderVo.setResidualPoint(appUser.getAvailablePoint().intValue());
        //获取默认收货地址
        UserAddress userAddress = userAddressClient.getDefaultUserAddress(userid).getData();
        if(null != userAddress){
            userAddress.setIdStr(userAddress.getId().toString());
            userAddress.setRecieveAddress(userAddress.getProvince() + userAddress.getCity() + userAddress.getDistrict() + userAddress.getRecieveAddress());
            confirmOrderVo.setUserAddress(userAddress);
        }
        confirmOrderVo.setPaymentType(confirmOrder.getPaymentType());
        //获取用户优惠券,用户全部优惠券,不能使用的需要标识出来置灰展示
        PaymentUserCoupon paymentUserCoupon = new PaymentUserCoupon();
        paymentUserCoupon.setUserId(userid);
        paymentUserCoupon.setOrderMoney(orderMoney);
        paymentUserCoupon.setType(confirmOrder.getType());
        if(confirmOrder.getPaymentType() == 1){
            List<PaymentUserCouponVo> data = userCouponClient.getPaymentUserCoupon(paymentUserCoupon).getData();
            if(null != data){
                for (PaymentUserCouponVo couponInfo : data) {
                    List<String> forGoodIds = couponInfo.getForGoodIds();
                    //全部商品适用
                    if(null == forGoodIds){
                        //满减券
                        if(1 == couponInfo.getCouponType() && orderMoney.compareTo(couponInfo.getConditionAmount()) >= 0){
                            couponInfo.setAvailable(true);
                        }
                        //代金券和折扣券
                        if(2 == couponInfo.getCouponType() || 3 == couponInfo.getCouponType()){
                            couponInfo.setAvailable(true);
                        }
                    }else{
                        //部分商品适用
                         BigDecimal goodsMoney = BigDecimal.ZERO;
                        for (MyShoppingCartVo myShoppingCartVo : goodsList) {
                            Integer goodsId = myShoppingCartVo.getGoodsId();
                            BigDecimal cash = myShoppingCartVo.getCash();
                            if(forGoodIds.contains(String.valueOf(goodsId))){
                                goodsMoney = goodsMoney.add(cash);
                            }
                        }
                        //满减
                        if(1 == couponInfo.getCouponType() && couponInfo.getConditionAmount().compareTo(goodsMoney) <= 0){
                            couponInfo.setAvailable(true);
                        }
                        //代金券
                        if(2 == couponInfo.getCouponType() || 3 == couponInfo.getCouponType()){
                            couponInfo.setAvailable(true);
                        }
                    }
                }
            }
            confirmOrderVo.setCoupon(data);
        }
        //获取快递策略
        SystemConfig systemConfig = systemConfigClient.getSystemConfig(3).getData();
        JSONObject jsonObject = JSON.parseObject(systemConfig.getContent());
        confirmOrderVo.setExpressFee(jsonObject.getBigDecimal("freight"));
        List<String> vip = Arrays.asList(jsonObject.getString("freeVip").split(","));
        //包邮条件(所有会员或者满足条件的会员)
        if(vip.get(0).equals("0") || vip.contains(appUser.getVipId().toString())){
            if(confirmOrder.getPaymentType() == 1){
                //现金支付,支付金额满足包邮条件
                BigDecimal cash = jsonObject.getBigDecimal("freeFreight");
                if(confirmOrderVo.getPayMoney().compareTo(cash) >= 0){
                    confirmOrderVo.setExpressFee(BigDecimal.ZERO);
                }
            }else{
                //积分支付,支付积分是否满足包邮条件
                Integer point = jsonObject.getInteger("freeIntegral");
                if(confirmOrderVo.getOrderPoint().compareTo(point) >= 0){
                    confirmOrderVo.setExpressFee(BigDecimal.ZERO);
                }
            }
        }
        return confirmOrderVo;
    }
 
 
    /**
     * 构建购物车商品列表
     * @param appUser
     * @param shopId
     * @param list
     * @param objects
     * @return
     */
    private List<MyShoppingCartVo> buildDetail(AppUser appUser, Integer shopId, List<ShoppingCart> list, JSONArray objects){
        List<MyShoppingCartVo> page = new ArrayList<>();
        for (ShoppingCart shoppingCart : list) {
            Goods goods = goodsClient.getGoodsById(shoppingCart.getGoodsId()).getData();
            MyShoppingCartVo vo = new MyShoppingCartVo();
            vo.setId(shoppingCart.getId().toString());
            vo.setType(shoppingCart.getType());
            vo.setGoodsId(goods.getId());
            vo.setHomePicture(goods.getHomePagePicture());
            vo.setName(goods.getName());
            int num = shoppingCart.getNumber();
            if(null != objects){
                for (int i = 0; i < objects.size(); i++) {
                    Long id = objects.getJSONObject(i).getLong("id");
                    if(id.equals(shoppingCart.getId())){
                        num = objects.getJSONObject(i).getInteger("num");
                        break;
                    }
                }
            }
            //获取支付价格
            Price price = getPrice(appUser, shoppingCart.getGoodsId(), shoppingCart.getType(), shopId);
            if(null == price){
                price = new Price();
                //使用商品的基础价格
                price.setCash(1 == goods.getCashPayment() ? goods.getSellingPrice() : null);
                price.setPoint(1 == goods.getPointPayment() ? goods.getIntegral() : null);
                price.setCashPayment(goods.getCashPayment() == 1);
                price.setPointPayment(goods.getPointPayment() == 1);
            }
            vo.setCash(price.getCash());
            vo.setPoint(price.getPoint());
            vo.setCashPayment(price.getCashPayment());
            vo.setPointPayment(price.getPointPayment());
            vo.setEndTime(price.getEndTime());
            vo.setOriginalPrice(goods.getOriginalPrice().toString());
            vo.setNumber(num);
            GoodsShop goodsShop = new GoodsShop();
            goodsShop.setGoodsId(shoppingCart.getGoodsId());
            goodsShop.setShopId(shopId);
            GoodsShop goodsShop1 = goodsShopClient.getGoodsShop(goodsShop).getData();
            vo.setVerifiable(goods.getAppointStore() != 1 || null != goodsShop1);
            //判断当前数量是否已经超出限购数量(需要计算已经购买的数量)
            if(null == goods.getPurchaseLimit() || -1 == goods.getPurchaseLimit()){
                vo.setPurchaseLimit(false);
                vo.setPurchaseLimitNum(-1);
            }else{
                List<Order> orders = orderService.list(new LambdaQueryWrapper<Order>().eq(Order::getAppUserId, appUser.getId()).eq(Order::getDelFlag, 0).in(Order::getOrderStatus, Arrays.asList(4, 8)));
                List<Long> orderIds = orders.stream().map(Order::getId).collect(Collectors.toList());
                int sum = 0;
                if(!orderIds.isEmpty()){
                    List<OrderGood> orderGoodList = orderGoodService.list(new LambdaQueryWrapper<OrderGood>().in(OrderGood::getOrderId, orderIds)
                            .eq(OrderGood::getGoodsId, shoppingCart.getGoodsId()).eq(OrderGood::getDelFlag, 0));
                    sum = orderGoodList.stream().mapToInt(OrderGood::getNum).sum();
                }
                vo.setPurchaseLimit((num + sum) > goods.getPurchaseLimit());
                vo.setPurchaseLimitNum(goods.getPurchaseLimit() - sum);
            }
            vo.setDistributionMode(goods.getDistributionMode());
            vo.setEarnSpendingPoints(price.getEarnSpendingPoints() * shoppingCart.getNumber());
            vo.setSuperiorSubcommission(price.getSuperiorSubcommission().multiply(new BigDecimal(shoppingCart.getNumber())));
            vo.setSuperiorRebatePoints(price.getSuperiorRebatePoints() * shoppingCart.getNumber());
            vo.setSuperiorType(price.getSuperiorType());
            vo.setSuperiorPriceType(price.getSuperiorPriceType());
            vo.setServuceShopCharges(price.getServuceShopCharges().multiply(new BigDecimal(shoppingCart.getNumber())));
            vo.setServuceShopPoints(price.getServuceShopPoints() * shoppingCart.getNumber());
            vo.setTechnicianPoints(price.getTechnicianPoints() * shoppingCart.getNumber());
            vo.setBoundShopCharges(price.getBoundShopCharges().multiply(new BigDecimal(shoppingCart.getNumber())));
            vo.setBoundShopPoints(price.getBoundShopPoints() * shoppingCart.getNumber());
            vo.setBoundShopSuperiorsCharges(price.getBoundShopSuperiorsCharges().multiply(new BigDecimal(shoppingCart.getNumber())));
            vo.setBoundShopSuperiorsPoints(price.getBoundShopSuperiorsPoints() * shoppingCart.getNumber());
            page.add(vo);
        }
        return page;
    }
 
 
    /**
     * 购物车支付操作
     * @param shoppingCartPayment
     * @return
     */
    @Override
    public R shoppingCartPayment(ShoppingCartPayment shoppingCartPayment) {
        Long userid = tokenService.getLoginUserApplet().getUserid();
        AppUser appUser = appUserClient.getAppUserById(userid);
        Integer shopId = shoppingCartPayment.getShopId();
        String goodsJson = shoppingCartPayment.getGoodsJson();
        List<Long> ids = new ArrayList<>();
        Integer num = 0;
        JSONArray objects = JSON.parseArray(goodsJson);
        for (int i = 0; i < objects.size(); i++) {
            Long id = objects.getJSONObject(i).getLong("id");
            Integer num1 = objects.getJSONObject(i).getInteger("num");
            Integer type = objects.getJSONObject(i).getInteger("type");
            num += num1;
            ShoppingCart shoppingCart = this.getById(id);
            //判断当前数量是否已经超出限购数量(需要计算已经购买的数量)
            Integer goodsSaleNum = orderService.getGoodsSaleNum(shoppingCart.getGoodsId(), type, userid);
            Goods goods = goodsClient.getGoodsById(shoppingCart.getGoodsId()).getData();
            if(1 == type){
                if(null != goods.getPurchaseLimit() && -1 != goods.getPurchaseLimit() && (goodsSaleNum + num1) > goods.getPurchaseLimit()){
                    return R.fail(goods.getName() + "已超出购买上限");
                }
            }else{
                GetSeckillActivityInfo info = new GetSeckillActivityInfo();
                info.setGoodsId(shoppingCart.getGoodsId());
                info.setVip(appUser.getVipId());
                GoodsSeckill goodsSeckill = seckillActivityInfoClient.getSeckillActivityInfo(info).getData();
                if(null != goodsSeckill ){
                    SeckillActivityInfo activityInfo = seckillActivityInfoClient.getSeckillActivityInfoById(goodsSeckill.getSeckillActivityInfoId()).getData();
                    if(null != activityInfo.getMaxNum() && -1 != activityInfo.getMaxNum() && (goodsSaleNum + num1) > activityInfo.getMaxNum()){
                        return R.fail(goods.getName() + "已超出秒杀活动购买上限");
                    }
                }
            }
            
            if(goods.getStatus() == 1){
                throw new RuntimeException(goods.getName() + "商品已被下架");
            }
            if(!goods.getCommodityAuthority().contains("-1") && !goods.getCommodityAuthority().contains(appUser.getVipId().toString())){
                throw new RuntimeException("无权限购买" + goods.getName());
            }
            
            ids.add(id);
        }
 
        List<ShoppingCart> list = this.listByIds(ids);
        //构建商品明细列表
        List<MyShoppingCartVo> goodsList = buildDetail(appUser, shopId, list, objects);
        //判断支付当时是否正确
        if(1 == shoppingCartPayment.getPaymentType() || 2 == shoppingCartPayment.getPaymentType()){
            //现金支付
            long count = goodsList.stream().filter(s -> s.getCashPayment()).count();
            if(count != goodsList.size()){
                return R.fail("支付方式不正确");
            }
        } else if(3 == shoppingCartPayment.getPaymentType()){
            //积分支付
            long count = goodsList.stream().filter(s -> s.getPointPayment()).count();
            if(count != goodsList.size()){
                return R.fail("支付方式不正确");
            }
        }else{
            return R.fail("支付方式不正确");
        }
        //判断门店是都可以核销所有的商品
        List<Integer> goodsIds = goodsList.stream().map(MyShoppingCartVo::getGoodsId).collect(Collectors.toList());
        GetGoodsShopByGoodsIds goodsShopByGoodsIds = new GetGoodsShopByGoodsIds();
        goodsShopByGoodsIds.setGoodsIds(goodsIds);
        goodsShopByGoodsIds.setShopId(shopId);
        List<GoodsShop> data = goodsShopClient.getGoodsShopByGoodsIds(goodsShopByGoodsIds).getData();
        List<Integer> collect = data.stream().map(GoodsShop::getGoodsId).collect(Collectors.toList());
        if(data.size() != goodsList.size()){
            String goodsName = "";
            for (Integer goodsId : goodsIds) {
                Goods goods = goodsClient.getGoodsById(goodsId).getData();
                if(goods.getType() == 1 && 1 == goods.getAppointStore() && !collect.contains(goodsId)){
                    goodsName = goods.getName();
                    break;
                }
            }
            if(StringUtils.isNotEmpty(goodsName)){
                return R.fail(goodsName + "不能在该门店核销");
            }
        }
        //开始构建支付信息
        //现金支付的订单金额
        BigDecimal orderMoney = BigDecimal.ZERO;
        //折扣(9折)
        BigDecimal discount = null;
        //积分支付的订单积分
        Integer orderPoint = 0;
        if(3 != shoppingCartPayment.getPaymentType()){
            for (MyShoppingCartVo myShoppingCartVo : goodsList) {
                orderMoney = orderMoney.add(myShoppingCartVo.getCash().multiply(new BigDecimal(myShoppingCartVo.getNumber())));
            }
        }else{
            for (MyShoppingCartVo myShoppingCartVo : goodsList) {
                orderPoint += (myShoppingCartVo.getPoint() * myShoppingCartVo.getNumber());
            }
        }
        //现金的支付金额
        BigDecimal paymentMoney = orderMoney;
        //满减金额
        BigDecimal fullReductionAmount = BigDecimal.ZERO;
        //代金券抵扣金额
        BigDecimal moneyAmount = BigDecimal.ZERO;
        //折扣券抵扣金额
        BigDecimal discountAmount = BigDecimal.ZERO;
        //活动优惠金额
        BigDecimal activityAmount = BigDecimal.ZERO;
 
        //减去优惠券优惠金额
        CouponInfoVo couponInfoVo = null;
        if(null != shoppingCartPayment.getUserCouponId() && 3 != shoppingCartPayment.getPaymentType()){
            couponInfoVo = userCouponClient.getCouponInfo(shoppingCartPayment.getUserCouponId()).getData();
            String forGoodIds = couponInfoVo.getForGoodIds();
            String[] split = forGoodIds.split(",");
            List<String> parseArray = Arrays.asList(split);
            //全部商品
            if("-1".equals(forGoodIds)){
                //满减
                if(1 == couponInfoVo.getCouponType() && couponInfoVo.getConditionAmount().compareTo(paymentMoney) <= 0){
                    paymentMoney = paymentMoney.subtract(couponInfoVo.getDiscountAmount());
                    fullReductionAmount = fullReductionAmount.add(couponInfoVo.getDiscountAmount());
                }
                //代金券
                if(2 == couponInfoVo.getCouponType()){
                    paymentMoney = paymentMoney.subtract(couponInfoVo.getMoneyAmount());
                    moneyAmount = moneyAmount.add(couponInfoVo.getMoneyAmount());
                    if(paymentMoney.compareTo(BigDecimal.ZERO) < 0){
                        paymentMoney = BigDecimal.ZERO;
                    }
                }
                //折扣券
                if(3 == couponInfoVo.getCouponType()){
                    BigDecimal paymentMoney1 = couponInfoVo.getDiscount().divide(new BigDecimal(10)).multiply(paymentMoney);
                    BigDecimal bigDecimal = paymentMoney.subtract(paymentMoney1).setScale(2, RoundingMode.HALF_EVEN);
                    discount = couponInfoVo.getDiscount();
                    paymentMoney = paymentMoney1;
                    discountAmount = discountAmount.add(bigDecimal);
                }
            }else{
                //部分商品,需要计算参与优惠商品的支付金额,然后再对商品进行优惠券处理
                paymentMoney = BigDecimal.ZERO;
                BigDecimal goodsMoney = BigDecimal.ZERO;
                for (MyShoppingCartVo myShoppingCartVo : goodsList) {
                    String goodsId = myShoppingCartVo.getGoodsId().toString();
                    BigDecimal cash = myShoppingCartVo.getCash().multiply(new BigDecimal(myShoppingCartVo.getNumber()));
                    if(parseArray.contains(goodsId)){
                        goodsMoney = goodsMoney.add(cash);
                    }else{
                        paymentMoney = paymentMoney.add(cash);
                    }
                }
 
                //满减
                if(1 == couponInfoVo.getCouponType() && couponInfoVo.getConditionAmount().compareTo(goodsMoney) <= 0){
                    goodsMoney = goodsMoney.subtract(couponInfoVo.getDiscountAmount());
                    fullReductionAmount = fullReductionAmount.add(couponInfoVo.getDiscountAmount());
                }
                //代金券
                if(2 == couponInfoVo.getCouponType()){
                    goodsMoney = goodsMoney.subtract(couponInfoVo.getMoneyAmount());
                    moneyAmount = moneyAmount.add(couponInfoVo.getMoneyAmount());
                    if(goodsMoney.compareTo(BigDecimal.ZERO) < 0){
                        goodsMoney = BigDecimal.ZERO;
                    }
                }
                //折扣券
                if(3 == couponInfoVo.getCouponType()){
                    BigDecimal paymentMoney1 = couponInfoVo.getDiscount().divide(new BigDecimal(10)).multiply(goodsMoney);
                    BigDecimal bigDecimal = goodsMoney.subtract(paymentMoney1).setScale(2, RoundingMode.HALF_EVEN);
                    discount = couponInfoVo.getDiscount();
                    goodsMoney = paymentMoney1;
                    discountAmount = discountAmount.add(bigDecimal);
                }
                paymentMoney = paymentMoney.add(goodsMoney);
            }
        }
 
        //查询当前是否有订单活动
        List<OrderActivityInfo> orderActivityInfo = orderActivityInfoClient.getNowOrderActivityInfo(appUser.getVipId()).getData();
        BaseSetting baseSetting = baseSettingClient.getBaseSetting(4).getData();
        //系统活动设置(优惠券和活动能否同时使用)
        Integer status = JSON.parseObject(baseSetting.getContent()).getInteger("status");
        //满XX才打折,只有现金才能优惠
        //如果使用优惠券,则需要判断是否可以和同时使用,且活动满足使用条件。
        //没有使用优惠券,只需要判断是都满足使用条件
        OrderActivityInfo orderActivityInfo1 = null;
        if((1 == status || null == shoppingCartPayment.getUserCouponId()) &&
                null != orderActivityInfo && shoppingCartPayment.getPaymentType() != 3){
            //找出最优会的金额
            BigDecimal zyh = BigDecimal.ZERO;
            for (OrderActivityInfo activityInfo : orderActivityInfo) {
                if(activityInfo.getConditionAmount().compareTo(paymentMoney) <= 0){
                    BigDecimal paymentMoney1 = activityInfo.getDiscount().divide(new BigDecimal(10)).multiply(paymentMoney);
                    BigDecimal bigDecimal = paymentMoney.subtract(paymentMoney1).setScale(2, RoundingMode.HALF_EVEN);
                    if(bigDecimal.compareTo(zyh) > 0){
                        zyh = bigDecimal;
                        orderActivityInfo1 = activityInfo;
                    }
                }
            }
 
            paymentMoney = paymentMoney.subtract(zyh);
            activityAmount = activityAmount.add(zyh);
        }
 
        //可获得的消费积分
        int earnPoint = 0;
        for (MyShoppingCartVo myShoppingCartVo : goodsList) {
            earnPoint += myShoppingCartVo.getEarnSpendingPoints();
        }
 
        //获取快递策略,计算快递费
        BigDecimal expressFee = BigDecimal.ZERO;
        if(null != shoppingCartPayment.getUserAddressId()){
            SystemConfig systemConfig = systemConfigClient.getSystemConfig(3).getData();
            JSONObject jsonObject = JSON.parseObject(systemConfig.getContent());
            //快递费
            expressFee = jsonObject.getBigDecimal("freight");
            List<String> vip = Arrays.asList(jsonObject.getString("freeVip").split(","));
            //包邮条件(所有会员或者满足条件的会员)
            if(vip.get(0).equals("0") || vip.contains(appUser.getVipId().toString())){
                if(shoppingCartPayment.getPaymentType() != 3){
                    //现金支付,支付金额满足包邮条件
                    BigDecimal cash = jsonObject.getBigDecimal("freeFreight");
                    if(paymentMoney.compareTo(cash) >= 0){
                        expressFee = BigDecimal.ZERO;
                    }
                }else{
                    //积分支付,支付积分是否满足包邮条件
                    Integer point = jsonObject.getInteger("freeIntegral");
                    if(orderPoint.compareTo(point) >= 0){
                        expressFee = BigDecimal.ZERO;
                    }
                }
            }
        }
        if(BigDecimal.ZERO.compareTo(paymentMoney) > 0){
            paymentMoney = BigDecimal.ZERO;
        }
 
        //构建订单明细
        Order order = new Order();
        order.setAppUserId(userid);
        order.setNum(num);
        String goodPics = "";
        String goodName = "";
        for (MyShoppingCartVo myShoppingCartVo : goodsList) {
            goodPics += myShoppingCartVo.getHomePicture() + ",";
            goodName += myShoppingCartVo.getName() + ",";
        }
        order.setGoodPics(goodPics.substring(0, goodPics.length() - 1));
        order.setGoodName(goodName.substring(0, goodName.length() - 1));
        Goods goods = goodsClient.getGoodsById(goodsList.get(0).getGoodsId()).getData();
        order.setOrderType(goods.getType());
        order.setOrderStatus(goods.getType() == 1 ? 3 : (shoppingCartPayment.getDistributionMode() == 2 ? 1 : 2));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        order.setOrderNumber("QJS" + getNumber(3) + sdf.format(new Date()));
        order.setTotalAmount(orderMoney.setScale(2, RoundingMode.HALF_EVEN));
        order.setFullReductionAmount(fullReductionAmount);
        order.setMoneyAmount(moneyAmount);
        order.setDiscountAmount(discountAmount);
        order.setActivityAmount(activityAmount);
        order.setDiscountTotalAmount(fullReductionAmount.add(moneyAmount).add(discountAmount).add(activityAmount));
        order.setPaymentAmount(paymentMoney);
        order.setPoint(orderPoint);
        order.setPayMethod(shoppingCartPayment.getPaymentType());
        if(StringUtils.isNotEmpty(shoppingCartPayment.getExpectedDeliveryTime())){
            order.setExpectedDeliveryTime(shoppingCartPayment.getExpectedDeliveryTime());
        }
        if(3 != shoppingCartPayment.getPaymentType() && (fullReductionAmount.compareTo(BigDecimal.ZERO) > 0 ||moneyAmount.compareTo(BigDecimal.ZERO) > 0 || discountAmount.compareTo(BigDecimal.ZERO) > 0)){
            order.setCouponJson(JSON.toJSONString(couponInfoVo));
            order.setUserCouponId(shoppingCartPayment.getUserCouponId());
        }
        if(null != orderActivityInfo1){
            order.setActivityJson(JSON.toJSONString(orderActivityInfo1));
        }
        if(2 == shoppingCartPayment.getDistributionMode()){
            UserAddress address = userAddressClient.getUserAddressById(shoppingCartPayment.getUserAddressId()).getData();
            order.setExpressAmount(expressFee);
            order.setAddressJson(JSON.toJSONString(address));
        }
        order.setGetPoint(earnPoint);
        order.setPayStatus(1);
        order.setShopId(shoppingCartPayment.getShopId());
        order.setDelFlag(0);
        order.setCreateTime(LocalDateTime.now());
        order.setExpressPayMethod(shoppingCartPayment.getFreightPaymentType());
        order.setDistributionMode(shoppingCartPayment.getDistributionMode());
 
        if(2 == shoppingCartPayment.getPaymentType()){
            BigDecimal balance = appUser.getBalance();
            if(balance.compareTo(paymentMoney) < 0){
                return R.fail("账户余额不足");
            }
        }
        if(3 == shoppingCartPayment.getPaymentType()){
            Integer availablePoint = appUser.getAvailablePoint();
            if(availablePoint.compareTo(orderPoint) < 0){
                return R.fail("账户可用积分不足");
            }
        }
        //判断运费支付是否足够
        if(null != shoppingCartPayment.getFreightPaymentType() && 2 == shoppingCartPayment.getFreightPaymentType() && expressFee.compareTo(BigDecimal.ZERO) > 0){
            BigDecimal balance = appUser.getBalance();
            if(balance.compareTo(expressFee) < 0){
                return R.fail("账户余额不足");
            }
        }
 
        orderService.save(order);
        //构建订单明细数据
        for (MyShoppingCartVo myShoppingCartVo : goodsList) {
            OrderGood orderGood = new OrderGood();
            orderGood.setGoodsId(myShoppingCartVo.getGoodsId());
            orderGood.setOrderId(order.getId());
            for (int i = 0; i < objects.size(); i++) {
                Long id = objects.getJSONObject(i).getLong("id");
                if(myShoppingCartVo.getId().equals(id.toString())){
                    ShoppingCart shoppingCart = this.getById(id);
                    Integer num1 = objects.getJSONObject(i).getInteger("num");
                    Integer type = objects.getJSONObject(i).getInteger("type");
                    orderGood.setNum(num1);
                    orderGood.setType(type);
                    if(2 == type){
                        GetSeckillActivityInfo info = new GetSeckillActivityInfo();
                        info.setGoodsId(myShoppingCartVo.getGoodsId());
                        info.setVip(appUser.getVipId());
                        GoodsSeckill goodsSeckill = seckillActivityInfoClient.getSeckillActivityInfo(info).getData();
                        if(null != goodsSeckill){
                            orderGood.setSeckillJson(JSON.toJSONString(goodsSeckill));
                        }
                    }
                    Goods goods1 = goodsClient.getGoodsById(shoppingCart.getGoodsId()).getData();
                    orderGood.setGoodJson(JSON.toJSONString(goods1));
                    break;
                }
            }
            orderGood.setDelFlag(0);
            orderGood.setCreateTime(LocalDateTime.now());
            orderGood.setEarnSpendingPoints(myShoppingCartVo.getEarnSpendingPoints());
            orderGood.setSuperiorSubcommission(myShoppingCartVo.getSuperiorSubcommission());
            orderGood.setSuperiorRebatePoints(myShoppingCartVo.getSuperiorRebatePoints());
            orderGood.setSuperiorType(myShoppingCartVo.getSuperiorType());
            orderGood.setSuperiorPriceType(myShoppingCartVo.getSuperiorPriceType());
            orderGood.setServuceShopCharges(myShoppingCartVo.getServuceShopCharges());
            orderGood.setServuceShopPoints(myShoppingCartVo.getServuceShopPoints());
            orderGood.setTechnicianPoints(myShoppingCartVo.getTechnicianPoints());
            orderGood.setBoundShopCharges(myShoppingCartVo.getBoundShopCharges());
            orderGood.setBoundShopPoints(myShoppingCartVo.getBoundShopPoints());
            orderGood.setBoundShopSuperiorsCharges(myShoppingCartVo.getBoundShopSuperiorsCharges());
            orderGood.setBoundShopSuperiorsPoints(myShoppingCartVo.getBoundShopSuperiorsPoints());
            orderGood.setCashPayment(myShoppingCartVo.getCashPayment() ? 1 : 0);
            orderGood.setPointPayment(myShoppingCartVo.getPointPayment() ? 1 : 0);
            orderGood.setSellingPrice(myShoppingCartVo.getCash());
            orderGood.setIntegral(myShoppingCartVo.getPoint());
            orderGoodService.save(orderGood);
        }
 
        //开始构建支付数据
        //现金支付
        paymentMoney = paymentMoney.add(expressFee).setScale(2, RoundingMode.HALF_EVEN);
        if(BigDecimal.ZERO.compareTo(paymentMoney) > 0){
            paymentMoney = BigDecimal.ZERO;
        }
        if(1 == shoppingCartPayment.getPaymentType()){
            if(BigDecimal.ZERO.compareTo(paymentMoney) < 0){
                //调起微信支付
                String goodsNames = goodsList.stream().map(MyShoppingCartVo::getName).collect(Collectors.joining("\n"));
                UniPayResult uniPayResult = PaymentUtil.uniPay(order.getOrderNumber(), paymentMoney.doubleValue(), order.getOrderType() == 1 ? "购买服务商品" : "购买单品商品",
                        goodsNames, "", "/order/shopping-cart/shoppingCartPaymentCallback", appUser.getWxOpenid(), null);
                if(null == uniPayResult || !"100".equals(uniPayResult.getRa_Code())){
                    return R.fail(null == uniPayResult ? "支付失败" : uniPayResult.getRb_CodeMsg());
                }
                String rc_result = uniPayResult.getRc_Result();
                JSONObject jsonObject = JSON.parseObject(rc_result);
                jsonObject.put("orderId", order.getId().toString());
                //将支付数据添加到redis队列中,便于定时任务去校验是否完成支付,没有完成支付支付,15分钟后关闭订单。
                long second = LocalDateTime.now().plusMinutes(15).toEpochSecond(ZoneOffset.UTC);
                redisTemplate.opsForZSet().add("OrderPayment", order.getOrderNumber(), second);
                return R.ok(jsonObject.toJSONString());
            }else{
 
                earnPoint = order.getGetPoint();
                appUser = appUserClient.getAppUserById(order.getAppUserId());
                Integer lavePoint = appUser.getLavePoint();
                paymentMoney = order.getPaymentAmount();
                //构建积分流水记录
                if(earnPoint > 0){
                    PointSetting pointSetting = pointSettingClient.getPointSetting(appUser.getVipId()).getData();
                    int earnPoint1 = 0;
                    if(null != pointSetting && 1 == pointSetting.getBuyPointOpen()){
                        earnPoint1 = new BigDecimal(earnPoint).multiply(pointSetting.getBuyPoint().divide(new BigDecimal(100))).intValue();
                    }
                    appUser.setShopPoint(appUser.getShopPoint() + earnPoint);
                    appUser.setLavePoint(appUser.getLavePoint() + earnPoint);
                    appUser.setTotalPoint(appUser.getTotalPoint() + earnPoint);
                    appUser.setAvailablePoint(appUser.getAvailablePoint() + earnPoint1);
                    appUser.setTotalAvailablePoint(appUser.getTotalAvailablePoint() + earnPoint1);
 
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("shopPoint", earnPoint);
                    jsonObject.put("availablePoint", earnPoint1);
                    if(null != pointSetting && 1 == pointSetting.getBuyPointGift()){
                        appUser.setTransferablePoint(appUser.getTransferablePoint() + earnPoint1);
                        jsonObject.put("transferablePoint", earnPoint1);
                    }
 
                    if(earnPoint > 0){
                        UserPoint userPoint = new UserPoint();
                        userPoint.setType(1);
                        userPoint.setVariablePoint(earnPoint);
                        userPoint.setCreateTime(LocalDateTime.now());
                        userPoint.setAppUserId(appUser.getId());
                        userPoint.setObjectId(order.getId());
                        userPoint.setExtention(jsonObject.toJSONString());
                        userPoint.setChangeDirection(1);
                        userPointClient.saveUserPoint(userPoint);
                    }
                }
                appUser.setShopAmount(appUser.getShopAmount().add(paymentMoney).setScale(2, RoundingMode.HALF_EVEN));
                appUser.setLastShopTime(LocalDateTime.now());
                appUserClient.editAppUserById(appUser);
                //变更等级
                applicationEventPublisher.publishEvent(new PayEvent(JSON.toJSONString(appUser)));
                //修改订支付状态
                order.setPayStatus(2);
                //自提
                if(order.getOrderType() == 1 && StringUtils.isEmpty(order.getAddressJson())){
                    order.setOrderStatus(2);
                }
                orderService.updateById(order);
 
                //处理优惠券
                if(null != order.getUserCouponId()){
                    UserCoupon userCoupon = userCouponClient.getUserCoupon(order.getUserCouponId()).getData();
                    if(null != userCoupon && null == userCoupon.getUseTime()){
                        userCoupon.setStatus(2);
                        userCoupon.setUseTime(LocalDateTime.now());
                        userCouponClient.editUserCoupon(userCoupon);
                    }
                }
                
 
                //删除购物车数据
                userid = tokenService.getLoginUserApplet().getUserid();
                List<OrderGood> list1 = orderGoodService.list(new LambdaQueryWrapper<OrderGood>().eq(OrderGood::getOrderId, order.getId()));
                List<Integer> goodsIds1 = list1.stream().map(OrderGood::getGoodsId).collect(Collectors.toList());
                this.remove(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getAppUserId, userid).in(ShoppingCart::getGoodsId, goodsIds1));
 
            }
        }
        //账户余额
        BigDecimal redPacketAmount = BigDecimal.ZERO;
        BigDecimal distributionAmount = BigDecimal.ZERO;
        if(2 == shoppingCartPayment.getPaymentType()){
            BigDecimal totalRedPacketAmount = appUser.getTotalRedPacketAmount();
            BigDecimal totalDistributionAmount = appUser.getTotalDistributionAmount();
            BigDecimal balance = appUser.getBalance();
            //红包金额满足支付
            BigDecimal paymentMoney1 = paymentMoney;
            balance = balance.subtract(paymentMoney1);
            appUser.setBalance(balance);
 
//            if(paymentMoney1.compareTo(totalRedPacketAmount) <= 0){
//                totalRedPacketAmount = totalRedPacketAmount.subtract(paymentMoney1);
//                balance = balance.subtract(paymentMoney1);
//                appUser.setTotalRedPacketAmount(totalRedPacketAmount);
//                appUser.setBalance(balance);
//                redPacketAmount = paymentMoney1;
//            }else{
//                paymentMoney1 = paymentMoney1.subtract(totalRedPacketAmount);
//                redPacketAmount = totalRedPacketAmount;
//                totalRedPacketAmount = BigDecimal.ZERO;
//                if(paymentMoney1.compareTo(totalDistributionAmount) <= 0){
////                    totalDistributionAmount = totalDistributionAmount.subtract(paymentMoney1);
//                    balance = balance.subtract(paymentMoney1);
//                    appUser.setTotalRedPacketAmount(totalRedPacketAmount);
////                    appUser.setTotalDistributionAmount(totalDistributionAmount);
//                    appUser.setBalance(balance);
//                    distributionAmount = paymentMoney1;
//                }else{
//                    paymentMoney1 = paymentMoney1.subtract(totalDistributionAmount);
//                    totalDistributionAmount = BigDecimal.ZERO;
//                    balance = balance.subtract(paymentMoney1);
//                    appUser.setTotalRedPacketAmount(totalRedPacketAmount);
////                    appUser.setTotalDistributionAmount(totalDistributionAmount);
//                    appUser.setBalance(balance);
//                    distributionAmount = totalDistributionAmount;
//                }
//            }
            //构建积分流水记录
            if(earnPoint > 0){
                PointSetting pointSetting = pointSettingClient.getPointSetting(appUser.getVipId()).getData();
                int earnPoint1 = 0;
                if(null != pointSetting && 1 == pointSetting.getBuyPointOpen()){
                    earnPoint1 = new BigDecimal(earnPoint).multiply(pointSetting.getBuyPoint().divide(new BigDecimal(100))).intValue();
                }
                appUser.setShopPoint(appUser.getShopPoint() + earnPoint);
                appUser.setLavePoint(appUser.getLavePoint() + earnPoint);
                appUser.setTotalPoint(appUser.getTotalPoint() + earnPoint);
                appUser.setAvailablePoint(appUser.getAvailablePoint() + earnPoint1);
                appUser.setTotalAvailablePoint(appUser.getTotalAvailablePoint() + earnPoint1);
 
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("shopPoint", earnPoint);
                jsonObject.put("availablePoint", earnPoint1);
                if(null != pointSetting && 1 == pointSetting.getBuyPointGift()){
                    appUser.setTransferablePoint(appUser.getTransferablePoint() + earnPoint1);
                    jsonObject.put("transferablePoint", earnPoint1);
                }
 
                if(earnPoint > 0){
                    UserPoint userPoint = new UserPoint();
                    userPoint.setType(1);
                    userPoint.setVariablePoint(earnPoint);
                    userPoint.setCreateTime(LocalDateTime.now());
                    userPoint.setAppUserId(appUser.getId());
                    userPoint.setObjectId(order.getId());
                    userPoint.setExtention(jsonObject.toJSONString());
                    userPoint.setChangeDirection(1);
                    userPointClient.saveUserPoint(userPoint);
                }
            }
            appUser.setShopAmount(appUser.getShopAmount().add(paymentMoney).setScale(2, RoundingMode.HALF_EVEN));
            appUser.setLastShopTime(LocalDateTime.now());
            appUserClient.editAppUserById(appUser);
            //变更等级
            applicationEventPublisher.publishEvent(new PayEvent(JSON.toJSONString(appUser)));
            //构建余额明细变动记录
            BalanceChangeRecord balanceChangeRecord = new BalanceChangeRecord();
            balanceChangeRecord.setAppUserId(appUser.getId());
            balanceChangeRecord.setVipId(appUser.getVipId());
            balanceChangeRecord.setOrderId(order.getId());
            balanceChangeRecord.setChangeType(5);
            balanceChangeRecord.setChangeAmount(paymentMoney);
            balanceChangeRecord.setDelFlag(0);
            balanceChangeRecord.setCreateTime(LocalDateTime.now());
            balanceChangeRecord.setChangeDirection(-1);
            balanceChangeRecordClient.saveBalanceChangeRecord(balanceChangeRecord);
            //修改订支付状态
            order.setPayStatus(2);
            if(goods.getType() == 2 && null == shoppingCartPayment.getUserAddressId()){
                order.setOrderStatus(2);
            }
            orderService.updateById(order);
            //删除购物车数据
            this.removeBatchByIds(ids);
            //处理优惠券
            if(null != order.getUserCouponId()){
                UserCoupon userCoupon = userCouponClient.getUserCoupon(order.getUserCouponId()).getData();
                if(null != userCoupon && null == userCoupon.getUseTime()){
                    userCoupon.setUseTime(LocalDateTime.now());
                    userCouponClient.editUserCoupon(userCoupon);
                }
            }
            
        }
        //积分支付
        if(3 == shoppingCartPayment.getPaymentType()){
            //先完成快递费支付后再处理后续的逻辑
            if(expressFee.compareTo(BigDecimal.ZERO) > 0){
                if(shoppingCartPayment.getFreightPaymentType() == 1){
                    //调起微信支付
                    UniPayResult uniPayResult = PaymentUtil.uniPay("K" + order.getOrderNumber(), expressFee.doubleValue(), order.getOrderType() == 1 ? "购买服务商品快递费" : "购买单品商品快递费",
                            "快递费", "", "/order/shopping-cart/shoppingCartMaterialFlowPaymentCallback", appUser.getWxOpenid(), null);
                    if(null == uniPayResult || !"100".equals(uniPayResult.getRa_Code())){
                        return R.fail(null == uniPayResult ? "支付失败" : uniPayResult.getRb_CodeMsg());
                    }
                    String rc_result = uniPayResult.getRc_Result();
                    JSONObject jsonObject = JSON.parseObject(rc_result);
                    jsonObject.put("orderId", order.getId().toString());
                    //将支付数据添加到redis队列中,便于定时任务去校验是否完成支付,没有完成支付支付,15分钟后关闭订单。
                    long second = LocalDateTime.now().plusMinutes(15).toEpochSecond(ZoneOffset.UTC);
                    redisTemplate.opsForZSet().add("MaterialFlowPayment", "K" + order.getOrderNumber(), second);
                    return R.ok(jsonObject.toJSONString());
                }
            }
 
            Integer lavePoint = appUser.getLavePoint();
            //扣减订单支付积分
            appUser.setLavePoint(appUser.getLavePoint() - orderPoint);
            appUser.setAvailablePoint(appUser.getAvailablePoint() - orderPoint);
            //可转增积分
            Integer transferablePoint = appUser.getTransferablePoint();
            Integer tra = 0;
            if(transferablePoint > 0){
                tra = transferablePoint - orderPoint;
                appUser.setTransferablePoint(tra >= 0 ? tra : 0);
            }else{
                appUser.setTransferablePoint(appUser.getTransferablePoint() - orderPoint);
            }
 
            //构建积分流水记录
            if(orderPoint > 0){
                UserPoint userPoint = new UserPoint();
                userPoint.setType(11);
                userPoint.setVariablePoint(orderPoint);
                userPoint.setCreateTime(LocalDateTime.now());
                userPoint.setAppUserId(appUser.getId());
                userPoint.setObjectId(order.getId());
                userPoint.setExtention((tra >= 0 ? orderPoint : transferablePoint) + "");
                userPoint.setChangeDirection(-1);
                userPointClient.saveUserPoint(userPoint);
            }
 
            appUser.setLastShopTime(LocalDateTime.now());
            appUserClient.editAppUserById(appUser);
            //变更等级
            applicationEventPublisher.publishEvent(new PayEvent(JSON.toJSONString(appUser)));
 
            //积分支付不返佣
 
            //如果有运费,需要先扣除账户积分,再进行支付。支付成功后修改订单状态,未支付成功则回退积分,删除的订单
            if(expressFee.compareTo(BigDecimal.ZERO) > 0){
                if(shoppingCartPayment.getFreightPaymentType() == 2){
                    BigDecimal totalRedPacketAmount = appUser.getTotalRedPacketAmount();
                    BigDecimal totalDistributionAmount = appUser.getTotalDistributionAmount();
                    BigDecimal balance = appUser.getBalance();
                    BigDecimal expressFee1 = expressFee;
                    if(expressFee1.compareTo(totalRedPacketAmount) <= 0){
                        totalRedPacketAmount = totalRedPacketAmount.subtract(expressFee1);
                        balance = balance.subtract(expressFee1);
                        appUser.setTotalRedPacketAmount(totalRedPacketAmount);
                        appUser.setBalance(balance);
                        redPacketAmount = expressFee1;
                    }else{
                        expressFee1 = expressFee1.subtract(totalRedPacketAmount);
                        redPacketAmount = totalRedPacketAmount;
                        totalRedPacketAmount = BigDecimal.ZERO;
                        if(expressFee1.compareTo(totalDistributionAmount) <= 0){
                            totalDistributionAmount = totalDistributionAmount.subtract(expressFee1);
                            balance = balance.subtract(expressFee1);
                            appUser.setTotalRedPacketAmount(totalRedPacketAmount);
//                            appUser.setTotalDistributionAmount(totalDistributionAmount);
                            appUser.setBalance(balance);
                            distributionAmount = expressFee1;
                        }else{
                            expressFee1 = expressFee1.subtract(totalDistributionAmount);
                            totalDistributionAmount = BigDecimal.ZERO;
                            balance = balance.subtract(expressFee1);
                            appUser.setTotalRedPacketAmount(totalRedPacketAmount);
//                            appUser.setTotalDistributionAmount(totalDistributionAmount);
                            appUser.setBalance(balance);
                            distributionAmount = totalDistributionAmount;
                        }
                    }
 
                    appUserClient.editAppUserById(appUser);
                    //构建余额明细变动记录
                    BalanceChangeRecord balanceChangeRecord = new BalanceChangeRecord();
                    balanceChangeRecord.setAppUserId(appUser.getId());
                    balanceChangeRecord.setVipId(appUser.getVipId());
                    balanceChangeRecord.setOrderId(order.getId());
                    balanceChangeRecord.setChangeType(5);
                    balanceChangeRecord.setChangeAmount(expressFee);
                    balanceChangeRecord.setDelFlag(0);
                    balanceChangeRecord.setCreateTime(LocalDateTime.now());
                    balanceChangeRecord.setChangeDirection(-1);
                    balanceChangeRecordClient.saveBalanceChangeRecord(balanceChangeRecord);
                    //修改订支付状态
                    order.setPayStatus(2);
                    if(goods.getType() == 2 && null == shoppingCartPayment.getUserAddressId()){
                        order.setOrderStatus(2);
                    }
                    orderService.updateById(order);
                    //删除购物车数据
                    this.removeBatchByIds(ids);
                }
            }else{
                //修改订支付状态
                order.setPayStatus(2);
                if(goods.getType() == 2 && null == shoppingCartPayment.getUserAddressId()){
                    order.setOrderStatus(2);
                }
                orderService.updateById(order);
                //删除购物车数据
                this.removeBatchByIds(ids);
            }
            
        }
 
        //添加账户余额支付明细
        if(redPacketAmount.compareTo(BigDecimal.ZERO) > 0 || distributionAmount.compareTo(BigDecimal.ZERO) > 0){
            OrderBalancePayment orderBalancePayment = new OrderBalancePayment();
            orderBalancePayment.setOrderId(order.getId());
            orderBalancePayment.setRedPacketAmount(redPacketAmount);
            orderBalancePayment.setDistributionAmount(distributionAmount);
            orderBalancePaymentService.save(orderBalancePayment);
        }
        
        commissionService.calculationCommissionUser(order.getId());
        return R.ok(order.getId().toString());
    }
 
 
 
 
 
 
 
 
 
    
    public String getNumber(Integer size){
        String str = "";
        for (Integer i = 0; i < size; i++) {
            str += Double.valueOf(Math.random() * 10).intValue();
        }
        return str;
    }
    
    
    /**
     * 线上支付回调逻辑处理
     * @param uniPayCallbackResult
     * @return
     */
    @Override
    public R shoppingCartPaymentCallback(UniPayCallbackResult uniPayCallbackResult) {
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNumber, uniPayCallbackResult.getR2_OrderNo()));
        if(null == order || order.getPayStatus() == 2){
            return R.ok();
        }
        Integer earnPoint = order.getGetPoint();
        AppUser appUser = appUserClient.getAppUserById(order.getAppUserId());
        Integer lavePoint = appUser.getLavePoint();
        BigDecimal paymentMoney = order.getPaymentAmount();
        //构建积分流水记录
        if(earnPoint > 0){
            PointSetting pointSetting = pointSettingClient.getPointSetting(appUser.getVipId()).getData();
            int earnPoint1 = 0;
            if(null != pointSetting && 1 == pointSetting.getBuyPointOpen()){
                earnPoint1 = new BigDecimal(earnPoint).multiply(pointSetting.getBuyPoint().divide(new BigDecimal(100))).intValue();
            }
            appUser.setShopPoint(appUser.getShopPoint() + earnPoint);
            appUser.setLavePoint(appUser.getLavePoint() + earnPoint);
            appUser.setTotalPoint(appUser.getTotalPoint() + earnPoint);
            appUser.setAvailablePoint(appUser.getAvailablePoint() + earnPoint1);
            appUser.setTotalAvailablePoint(appUser.getTotalAvailablePoint() + earnPoint1);
 
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("shopPoint", earnPoint);
            jsonObject.put("availablePoint", earnPoint1);
            if(null != pointSetting && 1 == pointSetting.getBuyPointGift()){
                appUser.setTransferablePoint(appUser.getTransferablePoint() + earnPoint1);
                jsonObject.put("transferablePoint", earnPoint1);
            }
 
            if(earnPoint > 0){
                UserPoint userPoint = new UserPoint();
                userPoint.setType(1);
                userPoint.setVariablePoint(earnPoint);
                userPoint.setCreateTime(LocalDateTime.now());
                userPoint.setAppUserId(appUser.getId());
                userPoint.setObjectId(order.getId());
                userPoint.setExtention(jsonObject.toJSONString());
                userPoint.setChangeDirection(1);
                userPointClient.saveUserPoint(userPoint);
            }
        }
        appUser.setShopAmount(appUser.getShopAmount().add(paymentMoney).setScale(2, RoundingMode.HALF_EVEN));
        appUser.setLastShopTime(LocalDateTime.now());
        appUserClient.editAppUserById(appUser);
        //变更等级
        applicationEventPublisher.publishEvent(new PayEvent(JSON.toJSONString(appUser)));
        //修改订支付状态
        order.setPayStatus(2);
        //自提
        if(order.getOrderType() == 1 && StringUtils.isEmpty(order.getAddressJson())){
            order.setOrderStatus(2);
        }
 
        String r7TrxNo = uniPayCallbackResult.getR9_BankTrxNo();
        order.setSerialNumber(r7TrxNo);
        orderService.updateById(order);
 
        //处理优惠券
        if(null != order.getUserCouponId()){
            UserCoupon userCoupon = userCouponClient.getUserCoupon(order.getUserCouponId()).getData();
            if(null != userCoupon && null == userCoupon.getUseTime()){
                userCoupon.setStatus(2);
                userCoupon.setUseTime(LocalDateTime.now());
                userCouponClient.editUserCoupon(userCoupon);
            }
        }
 
        //删除购物车数据
        Long userid = order.getAppUserId();
        List<OrderGood> list = orderGoodService.list(new LambdaQueryWrapper<OrderGood>().eq(OrderGood::getOrderId, order.getId()));
        List<Integer> goodsIds = list.stream().map(OrderGood::getGoodsId).collect(Collectors.toList());
        this.remove(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getAppUserId, userid).in(ShoppingCart::getGoodsId, goodsIds));
 
        //商品销量增加
        for (Integer goodsId : goodsIds) {
            goodsClient.editGoodsNum(goodsId, 1);
        }
        
        commissionService.calculationCommissionUser(order.getId());
        return R.ok();
    }
    
    
    /**
     * 订单物流支付回调处理逻辑
     * @param uniPayCallbackResult
     * @return
     */
    @Override
    public R shoppingCartMaterialFlowPaymentCallback(UniPayCallbackResult uniPayCallbackResult) {
        String r2_orderNo = uniPayCallbackResult.getR2_OrderNo();
        r2_orderNo = r2_orderNo.substring(1);
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNumber, r2_orderNo));
        if(null == order || order.getPayStatus() == 2){
            return R.ok();
        }
        Integer orderPoint = order.getPoint();
        AppUser appUser = appUserClient.getAppUserById(order.getAppUserId());
 
        Integer lavePoint = appUser.getLavePoint();
        //扣减订单支付积分
        appUser.setLavePoint(appUser.getLavePoint() - orderPoint);
        appUser.setAvailablePoint(appUser.getAvailablePoint() - orderPoint);
        //可转增积分
        Integer transferablePoint = appUser.getTransferablePoint();
        Integer tra = 0;
        if(transferablePoint > 0){
            tra = transferablePoint - orderPoint;
            appUser.setTransferablePoint(tra >= 0 ? tra : 0);
        }else{
            appUser.setTransferablePoint(appUser.getTransferablePoint() - orderPoint);
        }
 
        //构建积分流水记录
        if(orderPoint > 0){
            UserPoint userPoint = new UserPoint();
            userPoint.setType(11);
            userPoint.setVariablePoint(orderPoint);
            userPoint.setCreateTime(LocalDateTime.now());
            userPoint.setAppUserId(appUser.getId());
            userPoint.setObjectId(order.getId());
            userPoint.setExtention((tra >= 0 ? orderPoint : transferablePoint) + "");
            userPoint.setChangeDirection(-1);
            userPointClient.saveUserPoint(userPoint);
        }
 
        //积分支付不反积分
 
        appUser.setLastShopTime(LocalDateTime.now());
        appUserClient.editAppUserById(appUser);
        //变更等级
        applicationEventPublisher.publishEvent(new PayEvent(JSON.toJSONString(appUser)));
 
        //修改订支付状态
        order.setPayStatus(2);
        //自提
        if(order.getOrderType() == 1 && StringUtils.isEmpty(order.getAddressJson())){
            order.setOrderStatus(2);
        }
        orderService.updateById(order);
        //删除购物车数据
        Long userid = tokenService.getLoginUserApplet().getUserid();
        List<OrderGood> list = orderGoodService.list(new LambdaQueryWrapper<OrderGood>().eq(OrderGood::getOrderId, order.getId()));
        List<Integer> goodsIds = list.stream().map(OrderGood::getGoodsId).collect(Collectors.toList());
        this.remove(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getAppUserId, userid).in(ShoppingCart::getGoodsId, goodsIds));
        return R.ok();
    }
    
    
    /**
     * 定时任务关闭订单
     */
    @Override
    public void closeOrder() {
        //订单支付数据
        long second = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        Set<String> orderPayment = redisTemplate.opsForZSet().rangeByScore("OrderPayment", 0, second);
        if(orderPayment.size() > 0){
            List<Order> list = orderService.list(new LambdaQueryWrapper<Order>().in(Order::getOrderNumber, orderPayment));
            for (Order order : list) {
                if(null == order || order.getPayStatus() != 1){
                    redisTemplate.opsForZSet().remove("OrderPayment", order.getOrderNumber());
                    continue;
                }
                //开始执行关闭订单操作
                CloseOrderResult closeOrderResult = PaymentUtil.closeOrder(order.getOrderNumber());
                if((null == closeOrderResult || !closeOrderResult.getRa_Status().equals("100")) &&
                        Arrays.asList("0", "4", "101", "10080000", "10080002", "10083004", "10083005").contains(closeOrderResult.getRb_Code())){
                    redisTemplate.opsForZSet().add("OrderPayment", order.getOrderNumber(), 0);
                    log.error("关闭订单失败:{}---->{}", order.getOrderNumber(), JSON.toJSONString(closeOrderResult));
                }
                redisTemplate.opsForZSet().remove("OrderPayment", order.getOrderNumber());
            }
        }
        
        //快递支付
        Set<String> materialFlowPayment = redisTemplate.opsForZSet().rangeByScore("MaterialFlowPayment", 0, second);
        if(materialFlowPayment.size() > 0){
            materialFlowPayment.forEach(s->s.substring(1));
            List<Order> list = orderService.list(new LambdaQueryWrapper<Order>().in(Order::getOrderNumber, materialFlowPayment));
            for (Order order : list) {
                if(null == order || order.getPayStatus() != 1){
                    redisTemplate.opsForZSet().remove("MaterialFlowPayment", order.getOrderNumber());
                    continue;
                }
                //开始执行关闭订单操作
                CloseOrderResult closeOrderResult = PaymentUtil.closeOrder("K" + order.getOrderNumber());
                if((null == closeOrderResult || !closeOrderResult.getRa_Status().equals("100")) &&
                        Arrays.asList("0", "4", "101", "10080000", "10080002", "10083004", "10083005").contains(closeOrderResult.getRb_Code())){
                    redisTemplate.opsForZSet().add("MaterialFlowPayment", order.getOrderNumber(), 0);
                    log.error("关闭订单失败:{}---->{}", order.getOrderNumber(), JSON.toJSONString(closeOrderResult));
                }
                redisTemplate.opsForZSet().remove("MaterialFlowPayment", order.getOrderNumber());
            }
        }
    }
}