longz
2026-06-10 14f96ba18b58cda204d10608c1abfe9a1d78a495
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
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
package com.stylefeng.guns.modular.crossCity.server.impl;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.account.unionpay.GetOpenBodySig;
import com.stylefeng.guns.modular.account.unionpay.QrCodeConfiguration;
import com.stylefeng.guns.modular.account.unionpay.Util;
import com.stylefeng.guns.modular.crossCity.dao.*;
import com.stylefeng.guns.modular.crossCity.model.*;
import com.stylefeng.guns.modular.crossCity.server.ILineService;
import com.stylefeng.guns.modular.crossCity.server.ILineSiteService;
import com.stylefeng.guns.modular.crossCity.server.IOrderCrossCityService;
import com.stylefeng.guns.modular.crossCity.warpper.OrderCrossCityOnBehalfWarpper;
import com.stylefeng.guns.modular.crossCity.warpper.OrderCrossCityWarpper;
import com.stylefeng.guns.modular.specialTrain.dao.OrderPrivateCarMapper;
import com.stylefeng.guns.modular.specialTrain.model.OrderPrivateCar;
import com.stylefeng.guns.modular.system.dao.*;
import com.stylefeng.guns.modular.system.model.*;
import com.stylefeng.guns.modular.system.service.*;
import com.stylefeng.guns.modular.system.service.impl.CarServiceImpl;
import com.stylefeng.guns.modular.system.util.*;
import com.stylefeng.guns.modular.system.warpper.BaseWarpper;
import com.stylefeng.guns.modular.system.warpper.MerchantCouponListWarpper;
import com.stylefeng.guns.modular.taxi.dao.OrderTaxiMapper;
import com.stylefeng.guns.modular.taxi.model.OrderTaxi;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
 
 
@Service
@Transactional(isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class OrderCrossCityServiceImpl extends ServiceImpl<OrderCrossCityMapper, OrderCrossCity> implements IOrderCrossCityService {
 
    @Resource
    private OrderCrossCityMapper orderCrossCityMapper;
 
    @Resource
    private LineShiftDriverMapper lineShiftDriverMapper;
 
    @Autowired
    private ILineService lineService;
 
    @Autowired
    private ILineSiteService lineSiteService;
 
    @Autowired
    private ISystemNoticeService systemNoticeService;
 
    @Autowired
    private PushUtil pushUtil;
 
    @Autowired
    private IIncomeService incomeService;
 
    @Autowired
    private IDriverService driverService;
 
    @Resource
    private UserInfoMapper userInfoMapper;
    @Autowired
    private IOpenCityService openCityService;
 
    @Autowired
    private DateUtil dateUtil;
 
    @Resource
    private LineMapper lineMapper;
 
    @Resource
    private DriverSelfTripMapper driverSelfTripMapper;
 
    @Autowired
    private GDMapGeocodingUtil gdMapGeocodingUtil;
 
    @Autowired
    private GDFalconUtil gdFalconUtil;
 
    @Resource
    private RegionMapper regionMapper;
 
    @Autowired
    private ChinaMobileUtil chinaMobileUtil;
 
    @Autowired
    private ITransactionDetailsService transactionDetailsService;
 
    @Autowired
    private GDMapElectricFenceUtil gdMapElectricFenceUtil;
 
    @Autowired
    private IPaymentRecordService paymentRecordService;
 
    @Resource
    private SysIntegralMapper sysIntegralMapper;
 
    @Resource
    private OrderPrivateCarMapper orderPrivateCarMapper;
    
    @Resource
    private OrderTaxiMapper orderTaxiMapper;
    
    @Resource
    private PhoneMapper phoneMapper;
    
    @Autowired
    private IOrderPositionService orderPositionService;
    
    @Resource
    private MongoTemplate mongoTemplate;
    
    @Autowired
    private IOrderCancelService orderCancelService;
    
    @Autowired
    private GeodesyUtil geodesyUtil;
    
    @Autowired
    private PayMoneyUtil payMoneyUtil;
 
    @Autowired
    private CbyzxOrderPayHelper cbyzxOrderPayHelper;
    
    @Autowired
    private IOrderAdditionalFeeService orderAdditionalFeeService;
    
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    
    @Autowired
    private IMerchantActivityService merchantActivityService;
    
    @Autowired
    private IMerchantActivitySlaveService merchantActivitySlaveService;
    
    @Autowired
    private IUserMerchantCouponService userMerchantCouponService;
    
    @Autowired
    private IMerchantCouponService merchantCouponService;
    @Autowired
    private QrCodeConfiguration qrCodeConfiguration;
 
    @Autowired
    private TDriverPromotionActivityService driverPromotionActivityService;
 
    @Value("${pushMinistryOfTransport}")
    private boolean pushMinistryOfTransport;
 
    @Value("${callbackPath}")
    private String callbackPath;
    @Autowired
    private CarModelMapper carModelMapper;
    @Autowired
    private CarServiceImpl carServiceImpl;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private CarServiceMapper carServiceMapper;
    @Autowired
    private WeChatUtil weChatUtil;
 
    @Value("${filePath}")
    private String filePath;
 
    @Value("${qyt.admin_url}")
    private String adminUrl;
 
    /**
     * 获取司机抢单页面的订单详情
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> queryPushOrder(Integer orderId) throws Exception {
        return orderCrossCityMapper.queryPushOrder(orderId);
    }
 
 
 
    /**
     * 获取司机端首页订单列表
     * @param state     1=服务中,2=待服务(30分钟定义预约)
     * @param driverId
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> queryOrderList(Integer state, Integer driverId) throws Exception {
        return orderCrossCityMapper.queryOrderList(state, driverId);
    }
 
    /**
     * 获取我的订单列表数据
     * @param state     1=全部,2=待支付,3=已取消
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> queryMyAllOrder(Integer state, Integer uid) throws Exception {
        return orderCrossCityMapper.queryMyAllOrder(state, uid);
    }
 
 
    /**
     * 获取订单详情页(服务中的页面)
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> queryOrderInfo(Integer orderId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        OrderCrossCity orderCrossCity = this.selectById(orderId);
        List<Map<String, Object>> order = orderCrossCityMapper.queryOrderInfo(orderCrossCity.getOrderNum());
 
        int num = 0;
        Double serverMoney = 0D;
        Double totalMoney = 0D;
        for(Map<String, Object> m : order){
            String phone = String.valueOf(m.get("phone"));
            String s = phone.substring(0, 3) + "****" + phone.substring(7 );
            m.put("realPhone", s);
            if(m.get("telX")!=null){
                System.out.println(111);
                m.put("phone",m.get("telX"));
            }
            System.out.println(m);
            num += Integer.valueOf(m.get("peopleNumber").toString());
            totalMoney += Double.valueOf(m.get("payMoney").toString());
            List<Income> incomes = incomeService.queryData(1, null, 2, Integer.valueOf(m.get("orderId").toString()), 3);
            for (Income income : incomes){
                serverMoney += income.getMoney();
            }
        }
        String dispatchPhone = null;
        if (orderCrossCity.getLineId() <= -1) {
            LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(orderCrossCity.getLineShiftDriverId());
            DriverSelfTrip driverSelfTrip = driverSelfTripMapper.selectById(lineShiftDriver.getCustomerId());
            map.put("line", driverSelfTrip.getStartCityName() + "-" + driverSelfTrip.getEndCityName());
            map.put("lineId", orderCrossCity.getLineId());
        } else {
            Line line = lineService.selectById(orderCrossCity.getLineId());
            map.put("line", line == null ? "" : line.getName());
            map.put("lineId", orderCrossCity.getLineId());
            dispatchPhone = line == null ? null : line.getDispatchPhone();
        }
        map.put("peopleNumber", num);
        map.put("orderNumber", orderCrossCity.getOrderNum());
        map.put("totalMoney", new BigDecimal(totalMoney).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
        map.put("serverMoney", new BigDecimal(serverMoney).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
        OpenCity openCity = openCityService.openCity1(orderCrossCity.getStartLon().toString(), orderCrossCity.getStartLat().toString());
        Phone phone = phoneMapper.queryInfo(openCity == null ? 0 : openCity.getId(), 1, 1);
        map.put("emergencyCall", StringUtils.isNotBlank(dispatchPhone) ? dispatchPhone : (null != phone ? phone.getPhone() : "110"));
        if (!order.isEmpty()){
            map.put("lineShiftDriverId", order.get(0).get("lineShiftDriverId"));
        }
        map.put("orders", JSON.toJSONString(order));
 
        System.out.println("map"+map);
        return map;
    }
 
 
 
    /**
     * 走订单流程操作
     * @param orderId
     * @param state
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil process(Integer orderId, Integer state, Double lon, Double lat, String address) throws Exception {
        OrderCrossCity orderCrossCity = this.selectById(orderId);
        if(10 == orderCrossCity.getState()){
            return ResultUtil.error("订单已被取消,不能继续操作");
        }
        UserInfo userInfo = userInfoMapper.selectById(orderCrossCity.getUserId());
        Driver driver = driverService.selectById(orderCrossCity.getDriverId());
        Company company = companyService.selectById(driver.getCompanyId());
        switch (state){
            case 3://出发前往预约点
                orderCrossCity.setState(3);
                orderCrossCity.setSetOutTime(new Date());
                systemNoticeService.addSystemNotice(1, "司机已出发,请耐心等待", orderCrossCity.getUserId(), 1);
                break;
            case 4://到达预约点,等待客户上车
                orderCrossCity.setState(4);
                orderCrossCity.setArriveTime(new Date());
                systemNoticeService.addSystemNotice(1, "司机已到达您设置的预约地点,请及时上车", orderCrossCity.getUserId(), 1);
                break;
            case 5://开始服务
                orderCrossCity.setBoardingLon(lon);
                orderCrossCity.setBoardingLat(lat);
                orderCrossCity.setBoardingAddress(address);
                orderCrossCity.setBoardingTime(new Date());
                orderCrossCity.setState(5);
                orderCrossCity.setStartServiceTime(new Date());
 
                pushUtil.pushDriverPosition(orderCrossCity.getId(), 3);//主动推送司机定位
                break;
            case 6://结束服务
                orderCrossCity.setGetoffLon(lon);
                orderCrossCity.setGetoffLat(lat);
                orderCrossCity.setGetoffAddress(address);
                orderCrossCity.setGetoffTime(new Date());
                orderCrossCity.setState(8);//跨城直接到待评价
                orderCrossCity.setEndServiceTime(new Date());
                this.updateById(orderCrossCity);
                //添加抽成及收入记录
 
                //非追缴单才需要记录收入
                if(0 == orderCrossCity.getRecoveryOrder()){
                    //添加收入
                    Double orderMoney = (2 == orderCrossCity.getAbnormal() && 2 == orderCrossCity.getAbnormalStatus() ? orderCrossCity.getResponsibilityMoney().doubleValue() : orderCrossCity.getOrderMoney());
                    Map<String, Object> map = incomeService.saveIncome(orderCrossCity.getId(), 3, orderMoney);
                    orderCrossCity.setSplitAllocation(JSON.toJSONString(map));
                }
                //待审核的异常单修改状态为已关闭
                if(2 == orderCrossCity.getAbnormal() && 1 == orderCrossCity.getAbnormalStatus()){
                    orderCrossCity.setAbnormalStatus(3);
                    orderCrossCity.setResponsibilityMoney(new BigDecimal(orderCrossCity.getOrderMoney()));
                    orderCrossCity.setResponsibilityType(3);
                    orderCrossCity.setAbnormalRemark("乘客已支付订单,申诉已自动关闭");
                }
 
                //还原座位数
                LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(orderCrossCity.getLineShiftDriverId());
                if(1 == orderCrossCity.getTravelMode()){
                    lineShiftDriver.setLaveSeat(lineShiftDriver.getLaveSeat() + orderCrossCity.getPeopleNumber());
                }else{
                    Car car = carServiceImpl.selectById(driver.getCarId());
                    CarModel carModel = carModelMapper.selectById(car.getCarModelId());
                    lineShiftDriver.setLaveSeat(carModel.getSeat() - 1);
                }
                lineShiftDriver.setLaveSeatNumber(
                        (ToolUtil.isNotEmpty(lineShiftDriver.getLaveSeatNumber()) ? lineShiftDriver.getLaveSeatNumber() + ","  : "") +
                                orderCrossCity.getSeatNumber()
                );
                lineShiftDriverMapper.updateById(lineShiftDriver);
 
                //修改司机空闲状态
                List<OrderCrossCity> orderCrossCities = orderCrossCityMapper.queryWithin30Minutes(orderCrossCity.getDriverId(), 2, 3, 4, 5, 11);
                if(orderCrossCities.size() <= 1){
                    driver = driverService.selectById(orderCrossCity.getDriverId());
                    driver.setState(2);
                    driverService.updateById(driver);
                }
 
                //存储商家优惠券到redis  {"phone":[{...}]}
                //订单数要加1,因为这里是后修改订单状态
                List<OrderCrossCity> list = orderCrossCityMapper.queryByState(userInfo.getId(), 8, 9);
                List<MerchantActivity> merchantActivities = merchantActivityService.selectList(new EntityWrapper<MerchantActivity>().eq("companyId", orderCrossCity.getCompanyId()).eq("activityType", 1).eq("auditStatus", 2).eq("status", 1)
                        .eq("state", 1).like("orderType", "3").where("((orderAmountFull is not null  and orderAmountFull <= " + orderCrossCity.getOrderMoney() + ") or (orderNumber is not null and orderNumber <= " + (list.size() + 1) + "))")
                        .in("id", merchantActivitySlaveService.selectList(new EntityWrapper<MerchantActivitySlave>().gt("laveNumber", 0)).stream().map(MerchantActivitySlave::getMerchantActivityId).collect(Collectors.toList()))
                        .notIn("id", userMerchantCouponService.selectList(new EntityWrapper<UserMerchantCoupon>().eq("userType", 1).eq("userId", userInfo.getId()).eq("state", 1)).stream().map(UserMerchantCoupon::getMerchantActivityId).collect(Collectors.toList()))
                );
                List<MerchantCouponListWarpper> listWarppers = new ArrayList<>();
                if(merchantActivities.size() > 0){
                    for(MerchantActivity merchantActivity :merchantActivities){
                        List<MerchantActivitySlave> merchantActivitySlaves = merchantActivitySlaveService.selectList(new EntityWrapper<MerchantActivitySlave>().eq("merchantActivityId", merchantActivity.getId()).gt("laveNumber", 0));
 
                        for(MerchantActivitySlave merchantActivitySlave : merchantActivitySlaves){
                            UserMerchantCoupon userMerchantCoupon = new  UserMerchantCoupon();
                            try {
                                userMerchantCoupon.setCode(UUIDUtil.getRandomCode(16));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            userMerchantCoupon.setUserType(1);
                            userMerchantCoupon.setUserId(userInfo.getId());
                            userMerchantCoupon.setMerchantActivityId(merchantActivity.getId());
                            userMerchantCoupon.setMerchantCouponId(merchantActivitySlave.getMerchantCouponId());
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(new Date());
                            calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + merchantActivity.getEffectiveDays());
                            userMerchantCoupon.setEndTime(calendar.getTime());
                            userMerchantCoupon.setStatus(1);
                            userMerchantCoupon.setState(1);
                            userMerchantCoupon.setCreateTime(new Date());
                            userMerchantCouponService.insert(userMerchantCoupon);
 
                            MerchantCoupon merchantCoupon = merchantCouponService.selectById(merchantActivitySlave.getMerchantCouponId());
                            MerchantCouponListWarpper merchantCouponListWarpper = new MerchantCouponListWarpper();
                            merchantCouponListWarpper.setId(merchantActivitySlave.getMerchantCouponId());
                            merchantCouponListWarpper.setName(merchantCoupon.getName());
                            merchantCouponListWarpper.setType(merchantCoupon.getType());
                            merchantCouponListWarpper.setFullAmount(merchantCoupon.getFullAmount());
                            merchantCouponListWarpper.setDiscount(merchantCoupon.getDiscount());
                            listWarppers.add(merchantCouponListWarpper);
 
                            merchantActivitySlave.setLaveNumber(merchantActivitySlave.getLaveNumber() - 1);
                            if(merchantActivitySlave.getLaveNumber() == 0){
                                merchantActivity.setStatus(2);
                            }
                        }
                        if(merchantActivitySlaves.size() > 0){
                            merchantActivitySlaveService.updateBatchById(merchantActivitySlaves);
                        }
                    }
                    merchantActivityService.updateBatchById(merchantActivities);
                }
                String value = (String) redisTemplate.opsForValue().get("merchantVoucher");
                JSONObject jsonObject = JSON.parseObject(value);
                if(null == jsonObject){
                    jsonObject = new JSONObject();
                }
                jsonObject.put(userInfo.getPhone(), listWarppers);
                redisTemplate.opsForValue().set("merchantVoucher", jsonObject.toJSONString());
 
                pushUtil.removeTask(orderId, 3);//删除定时任务,结束推送数据
                systemNoticeService.addSystemNotice(1, "司机已结束本次行程,谢谢使用", orderCrossCity.getUserId(), 1);
                promotion(orderId);
                break;
        }
        this.updateById(orderCrossCity);
 
 
        // TODO: 2020/6/5 推送状态
        new Thread(new Runnable() {
            @Override
            public void run() {
                pushUtil.pushOrderState(1, orderCrossCity.getUserId(), orderCrossCity.getId(), 3, orderCrossCity.getState());
                pushUtil.pushOrderState(2, orderCrossCity.getDriverId(), orderCrossCity.getId(), 3, orderCrossCity.getState());
            }
        }).start();
        return ResultUtil.success();
    }
 
    public void promotion(Integer orderId) {
        OrderCrossCity orderCrossCity = this.baseMapper.selectById(orderId);
        UserInfo userInfo = userInfoMapper.selectById(orderCrossCity.getUserId());
        if(orderCrossCity.getPromotionDriverId()!=null ){
            String registAreaCode = userInfo.getRegistAreaCode();
            TDriverPromotionActivity tDriverPromotionActivity = driverPromotionActivityService.selectOne(new EntityWrapper<TDriverPromotionActivity>().eq("districtCode", registAreaCode).le("startTime", new Date()).ge("endTime", new Date()).last("AND FIND_IN_SET(" + 3 + ", bizType) limit 1"));
            System.out.println("ddddd"+tDriverPromotionActivity);
            if(tDriverPromotionActivity!=null){
                Double payMoney = orderCrossCity.getPayMoney();
                System.out.println(payMoney);
                BigDecimal bigDecimal = tDriverPromotionActivity.getCommissionRatio().divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(payMoney)).setScale(2, RoundingMode.HALF_UP);
                System.out.println(bigDecimal);
                orderCrossCity.setPromotionDriverId(userInfo.getBindDriverId());
                orderCrossCity.setPromotionMoney(bigDecimal);
                orderCrossCity.setPromotionActivityId(tDriverPromotionActivity.getId());
                orderCrossCity.setSuccessTime(new Date());
                this.baseMapper.updateById(orderCrossCity);
            }
        }
 
 
 
    }
    /**
     * 获取订单明细
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> queryOrderCrossCityInfo(Integer orderId) throws Exception {
        return orderCrossCityMapper.queryOrderCrossCityInfo(orderId);
    }
 
 
    /**
     * 修改订单顺序
     * @param orderId
     * @throws Exception
     */
    @Override
    public void setOrderCrossCitySort(Integer orderId) throws Exception {
        OrderCrossCity orderCrossCity = this.selectById(orderId);
        List<OrderCrossCity> orderCrossCities = orderCrossCityMapper.selectList(new EntityWrapper<OrderCrossCity>().eq("orderNum", orderCrossCity.getOrderNum()).ne("state", 10).orderBy("sort"));
        for(int i = 0; i < orderCrossCities.size(); i++){
            if(orderCrossCities.get(i).getId().compareTo(orderId) == 0){
                if(i == 0){
                    break;
                }
                OrderCrossCity orderCrossCity2 = orderCrossCities.get(i);
                Integer sort = orderCrossCity2.getSort();
                OrderCrossCity orderCrossCity1 = orderCrossCities.get(i - 1);
                orderCrossCity2.setSort(orderCrossCity1.getSort());
                orderCrossCity1.setSort(sort);
                orderCrossCityMapper.updateById(orderCrossCity2);
                orderCrossCityMapper.updateById(orderCrossCity1);
                break;
            }
        }
 
    }
 
 
 
 
 
    /**
     * 跨城下单操作
     * @param orderCrossCityWarpper
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public synchronized ResultUtil<BaseWarpper> orderCrossCity(OrderCrossCityWarpper orderCrossCityWarpper, Integer uid) throws Exception {
        /**
         * 先判断司机座位数是否符合出行人数
         */
        LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(orderCrossCityWarpper.getLineShiftDriverId());
        if(orderCrossCityWarpper.getTravelMode() == 1){
            if(lineShiftDriver.getLaveSeat() < orderCrossCityWarpper.getPeopleNumber()){
                return ResultUtil.error("司机剩余座位数小于出行人数");
            }
        }else{
            if(lineShiftDriver.getLaveSeat() != lineShiftDriver.getTotalSeat()){
                return ResultUtil.error("司机车辆上已经有人占座了,不能下包车订单");
            }
            if(lineShiftDriver.getLaveSeat() == 0){
                return ResultUtil.error("司机剩余座位数不足");
            }
        }
        Driver driver = driverService.selectById(orderCrossCityWarpper.getDriverId());
        if(driver.getState() == 1){
            return ResultUtil.error("司机处于离线状态");
        }
        OrderCrossCity orderCrossCity = new OrderCrossCity();
        String phone = orderCrossCityWarpper.getPassengersPhone();
        UserInfo userInfo = userInfoMapper.queryByPhone(phone);
        if(userInfo == null){//添加用户信息
            Integer integer = userInfoMapper.selectCount(null) + 1000001;
            String nickName = ToolUtil.isNotEmpty(orderCrossCityWarpper.getPassengers()) ? orderCrossCityWarpper.getPassengers() : "GRJY" + String.valueOf(integer).substring(1);
            userInfo = new UserInfo();
            userInfo.setNickName(nickName);
            userInfo.setName(orderCrossCityWarpper.getPassengers());
            userInfo.setPhone(orderCrossCityWarpper.getPassengersPhone());
            userInfo.setState(1);
            userInfo.setFlag(1);
            userInfo.setInsertTime(new Date());
            userInfo.setInsertUser(uid);
            userInfoMapper.insert(userInfo);
        }
        orderCrossCity.setUserId(userInfo.getId());
 
        /**
         * 1.出租车、专车、跨城有待支付的订单不能叫车
         * 2.小件物流有未完成的订单可以下跨城、专车、出租车
         * 3.出租车、专车、跨城有预约单可以下即时单
         */
        List<OrderPrivateCar> orderPrivateCars = orderPrivateCarMapper.queryByState(userInfo.getId(), 1, 1, 1, 2, 3, 4, 5, 6, 7, 11, 12);
        if(orderPrivateCars.size() > 0){
            return ResultUtil.error("有未完成的订单");
        }
        List<OrderTaxi> list = orderTaxiMapper.queryByState_(userInfo.getId(), 1, 1, 1, 2, 3, 4, 5, 6, 7, 11, 12);
        if(list.size() > 0){
            return ResultUtil.error("有未完成的订单");
        }
        List<OrderCrossCity> orderCrossCities1 = orderCrossCityMapper.queryByState(userInfo.getId(), 1, 2, 3, 4, 5, 6, 7, 11, 12);
        if(orderCrossCities1.size() > 0){
            return ResultUtil.error("有未完成的订单");
        }
 
 
        List<OrderCrossCity> orderCrossCities2 = orderCrossCityMapper.queryOrders(orderCrossCityWarpper.getDriverId(), orderCrossCityWarpper.getLineShiftDriverId(), Arrays.asList(5));
        if(orderCrossCities2.size() > 0){
            return ResultUtil.error("司机正在服务中");
        }
 
 
        orderCrossCity.setPassengers(orderCrossCityWarpper.getPassengers());
        orderCrossCity.setPassengersPhone(orderCrossCityWarpper.getPassengersPhone());
        orderCrossCity.setServerCarModelId(orderCrossCityWarpper.getServerCarModelId());
        orderCrossCity.setDriverId(orderCrossCityWarpper.getDriverId());
        orderCrossCity.setLineId(orderCrossCityWarpper.getLineId());
        orderCrossCity.setCarId(orderCrossCityWarpper.getCarId());
        orderCrossCity.setOrderNum(this.getOrderNum(orderCrossCityWarpper.getDriverId(), orderCrossCityWarpper.getLineShiftDriverId()));
        orderCrossCity.setPlacementLon(orderCrossCityWarpper.getPlacementLon());
        orderCrossCity.setPlacementLat(orderCrossCityWarpper.getPlacementLat());
        String placementAddress = orderCrossCityWarpper.getPlacementAddress();
        placementAddress = placementAddress.replaceAll("& #40;", "(");
        placementAddress = placementAddress.replaceAll("& #41;", ")");
        orderCrossCity.setPlacementAddress(placementAddress);
        orderCrossCity.setStartLon(orderCrossCityWarpper.getStartLon());
        orderCrossCity.setStartLat(orderCrossCityWarpper.getStartLat());
        String startAddress = orderCrossCityWarpper.getStartAddress();
        startAddress = startAddress.replaceAll("& #40;", "(");
        startAddress = startAddress.replaceAll("& #41;", ")");
        orderCrossCity.setStartAddress(startAddress);
        orderCrossCity.setEndLon(orderCrossCityWarpper.getEndLon());
        orderCrossCity.setEndLat(orderCrossCityWarpper.getEndLat());
        String endAddress = orderCrossCityWarpper.getEndAddress();
        endAddress = endAddress.replaceAll("& #40;", "(");
        endAddress = endAddress.replaceAll("& #41;", ")");
        orderCrossCity.setEndAddress(endAddress);
        orderCrossCity.setMileage(0D);
        ResultUtil<Map<String, Object>> price = this.getPriceV2(orderCrossCityWarpper.getLineId(), null,
                orderCrossCityWarpper.getTotalSeat(), orderCrossCityWarpper.getPeopleNumber(), orderCrossCityWarpper.getEndLon(),
                orderCrossCityWarpper.getEndLat(), orderCrossCityWarpper.getLineShiftDriverId());
        if (price.getCode() != 200) {
            return ResultUtil.error("计算价格失败");
        }
        Double money = Double.valueOf(price.getData().get("price").toString());
        if (money < 0) {
            return ResultUtil.error("计算价格失败");
        }
        orderCrossCity.setOrderMoney(money);
        Integer companyId = driver.getCompanyId();
        orderCrossCity.setCompanyId(companyId);
        orderCrossCity.setPeopleNumber(orderCrossCityWarpper.getPeopleNumber());
        orderCrossCity.setSeatNumber(orderCrossCityWarpper.getSeatNumber());
        List<OrderCrossCity> orderCrossCities = this.selectList(new EntityWrapper<OrderCrossCity>().eq("orderNum", orderCrossCity.getOrderNum()).eq("isDelete", 1));
        orderCrossCity.setSort(orderCrossCities.size() + 1);
        orderCrossCity.setState(7);//待支付
        orderCrossCity.setInsertTime(new Date());
        orderCrossCity.setTravelTime(orderCrossCityWarpper.getTravelTime());
        orderCrossCity.setSnatchOrderTime(new Date());
        orderCrossCity.setTravelMode(orderCrossCityWarpper.getTravelMode());
        orderCrossCity.setIsDelete(1);
        orderCrossCity.setIsReassign(1);
        orderCrossCity.setLineShiftDriverId(orderCrossCityWarpper.getLineShiftDriverId());
        //调用高德创建轨迹
//        String s = gdFalconUtil.selectTerminal(driver.getPhone());
//        String track = gdFalconUtil.createTrack(s);
//        orderCrossCity.setTrackId(track);
 
        //调用移动的小号接口
//        Map<String, String> map = chinaMobileUtil.midAxbBindSend(orderCrossCity.getPassengersPhone(), driver.getPhone(), (System.currentTimeMillis() + 86400000));
//        if(String.valueOf(map.get("code")).equals("200")){
//            orderCrossCity.setTelX(map.get("telX"));
//            orderCrossCity.setBindId(map.get("bindId"));
//        }
        if(orderCrossCityWarpper.getTravelMode() == 2){//包车
//            orderCrossCity.setSeatNumber(lineShiftDriver.getLaveSeatNumber());
//            orderCrossCity.setPeopleNumber(lineShiftDriver.getLaveSeat());
        }
        orderCrossCity.setOrderSource(4);
        this.insert(orderCrossCity);
 
        Double t = 0D;
        if(ToolUtil.isNotEmpty(orderCrossCityWarpper.getAdditionalFee())){//附加费
            JSONArray jsonArray = JSON.parseArray(orderCrossCityWarpper.getAdditionalFee());
            for(int i = 0; i < jsonArray.size(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Integer id = jsonObject.getInteger("id");
                Double amount = jsonObject.getDouble("amount");
                OrderAdditionalFee orderAdditionalFee = new OrderAdditionalFee();
                orderAdditionalFee.setOrderType(3);
                orderAdditionalFee.setOrderId(orderCrossCity.getId());
                orderAdditionalFee.setAdditionalFeeId(id);
                orderAdditionalFee.setAmount(amount);
                orderAdditionalFeeService.insert(orderAdditionalFee);
                t += amount;
            }
        }
        orderCrossCity.setOrderMoney(orderCrossCity.getOrderMoney() + t);
        this.updateById(orderCrossCity);
 
        if(driver.getState() == 2){
            driver.setState(3);
            driverService.updateById(driver);
        }
 
        //修改预约班次的数据
        if(orderCrossCity.getTravelMode() == 2){//包车
            lineShiftDriver.setLaveSeat(0);
            lineShiftDriver.setLaveSeatNumber("");
        }else{//拼车
            lineShiftDriver.setLaveSeat(lineShiftDriver.getLaveSeat() - orderCrossCity.getPeopleNumber());
            String[] split1 = lineShiftDriver.getLaveSeatNumber().split(",");
 
            if (StringUtils.isNotEmpty(orderCrossCity.getSeatNumber())){
                // 用户已选座的情况
                String[] split = orderCrossCity.getSeatNumber().split(",");
                String seatNumber = "";
                //先判断选中座位号和剩余座位号是否匹配
                for(String spl : split){
                    boolean b = true;
                    for(String sp : split1){
                        if(ToolUtil.isNotEmpty(spl) && ToolUtil.isNotEmpty(sp) && sp.equals(spl)){
                            b = false;
                            break;
                        }
                    }
                    if(b){
                        throw new SystemException("您选中的" + spl + "号座位已被占用,请选择其他座位!");
                    }
                }
                for(String sp : split1){
                    boolean b = true;
                    for(String spl : split){
                        if(ToolUtil.isNotEmpty(spl) && ToolUtil.isNotEmpty(sp) && sp.equals(spl)){
                            b = false;
                            break;
                        }
                    }
                    if(b && ToolUtil.isNotEmpty(sp)){
                        seatNumber += (sp + ",");
                    }
                }
                lineShiftDriver.setLaveSeatNumber(ToolUtil.isNotEmpty(seatNumber) ? seatNumber.substring(0, seatNumber.length() - 1) : "");
            } else {
                // 用户未选座的情况,自动分配剩余座位的前peopleNumber个
                StringBuilder assignedSeats = new StringBuilder();
                StringBuilder remainingSeats = new StringBuilder();
 
                for(int i = 0; i < split1.length; i++){
                    if(ToolUtil.isEmpty(split1[i])){
                        continue;
                    }
 
                    if(i < orderCrossCity.getPeopleNumber()){
                        // 分配给当前订单的座位
                        if(assignedSeats.length() > 0){
                            assignedSeats.append(",");
                        }
                        assignedSeats.append(split1[i]);
                    } else {
                        // 剩余的座位
                        if(remainingSeats.length() > 0){
                            remainingSeats.append(",");
                        }
                        remainingSeats.append(split1[i]);
                    }
                }
 
                // 设置订单的座位号
                orderCrossCity.setSeatNumber(assignedSeats.toString());
                this.updateById(orderCrossCity);
 
                // 更新班次的剩余座位号
                lineShiftDriver.setLaveSeatNumber(remainingSeats.toString());
            }
        }
        lineShiftDriverMapper.updateById(lineShiftDriver);
 
        //添加消息
        systemNoticeService.addSystemNotice(1, "您的跨城订单已下单成功!", orderCrossCity.getUserId(), 1);
        BaseWarpper baseWarpper = new BaseWarpper();
        baseWarpper.setId(orderCrossCity.getId());
        baseWarpper.setContent("");
        //生成小程序二维码,用于司机展示让用户跳转到小程序完成订单支付
//        String appletPath = "pages/home/home";
//        InputStream inputStream = weChatUtil.getwxacodeunlimit(appletPath, "driver_places", "release");
//        if (inputStream != null) {
//            File file = FileUtil.writeFromStream(inputStream, new File(filePath + "/" + UUID.randomUUID().toString() + ".png"));
//            HttpRequest post = HttpUtil.createPost(adminUrl + "/upload/image");
//            post.form("file", file);
//            HttpResponse execute = post.execute();
//            int status = execute.getStatus();
//            if(200 != status){
//                throw new RuntimeException("上传图片异常");
//            }
//            JSONObject jsonObject = JSON.parseObject(execute.body());
//            Integer code = jsonObject.getInteger("code");
//            if(200 == code){
//                baseWarpper.setContent(jsonObject.getString("data"));
//                System.err.println(jsonObject.getString("data"));
//            }
//        }
 
        //创建定时任务,取消订单30分钟
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                OrderCrossCity orderCrossCity1 = orderCrossCityMapper.selectById(orderCrossCity.getId());
                if(orderCrossCity1.getState() == 7 && orderCrossCity1.getPayMoney() == null){
                    orderCrossCity1.setState(10);
                    orderCrossCityMapper.updateById(orderCrossCity1);
 
                    OrderCancel orderCancel = new OrderCancel();
                    orderCancel.setOrderId(orderCrossCity.getId());
                    orderCancel.setOrderType(3);
                    orderCancel.setReason("用户未及时付款,系统自动取消订单");
                    orderCancel.setRemark("用户未及时付款,系统自动取消订单");
                    orderCancel.setState(2);
                    orderCancel.setInsertTime(new Date());
                    orderCancel.setUserType(2);
                    orderCancelService.insert(orderCancel);
 
                    //修改司机座位
                    LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(orderCrossCity.getLineShiftDriverId());
                    lineShiftDriver.setLaveSeat(lineShiftDriver.getLaveSeat() + orderCrossCity.getPeopleNumber());
                    lineShiftDriver.setLaveSeatNumber(lineShiftDriver.getLaveSeatNumber() + (orderCrossCity.getTravelMode() == 1 ? "," : "") + orderCrossCity.getSeatNumber());
                    lineShiftDriverMapper.updateById(lineShiftDriver);
 
                    //修改司机为空闲
                    List<OrderCrossCity> orderCrossCities = orderCrossCityMapper.queryByDriverId(orderCrossCity.getDriverId(), 2, 3, 4, 5, 11);
                    if(orderCrossCities.size() == 0){
                        Driver driver = driverService.selectById(orderCrossCity.getDriverId());
                        driver.setState(2);
                        driverService.updateById(driver);
                    }
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask, 30 * 60 * 1000);
 
        return ResultUtil.success(baseWarpper);
    }
 
 
    /**
     * 扫码支付回调处理
     * @param orderId       订单id
     * @param order_id      工行订单号
     * @throws Exception
     */
    @Override
    public void generatePayCallback(Integer orderId, String order_id) throws Exception {
        OrderCrossCity orderCrossCity = orderCrossCityMapper.selectById(orderId);
        orderCrossCity.setPayManner(1);
        orderCrossCity.setPayMoney(orderCrossCity.getOrderMoney());
        orderCrossCity.setState(2);
        orderCrossCity.setPayTime(new Date());
        orderCrossCityMapper.updateById(orderCrossCity);
 
        paymentRecordService.saveData(1, orderCrossCity.getDriverId(), orderCrossCity.getPayType(), orderId, 3, 2, orderCrossCity.getPayMoney(), order_id, 2);//添加预支付数据
 
        //添加交易明细
        transactionDetailsService.saveData(orderCrossCity.getUserId(), "订单完成支付", orderCrossCity.getOrderMoney(), 2, 1, 1, 3, orderId);
 
        //添加已收入明细
//        Line line = lineService.selectById(orderCrossCity.getLineId());
//        Double speMoney = Double.valueOf(line.getRakeRate());
//        BigDecimal d = new BigDecimal(orderCrossCity.getOrderMoney()).multiply(new BigDecimal(speMoney).divide(new BigDecimal(100)), new MathContext(2, RoundingMode.HALF_EVEN));//企业收入
//        BigDecimal c = new BigDecimal(orderCrossCity.getOrderMoney()).subtract(d).setScale(2, BigDecimal.ROUND_HALF_EVEN);//司机收入
//        incomeService.saveData(1, orderCrossCity.getCompanyId(), 2, orderCrossCity.getId(), 1, d.doubleValue());
//        incomeService.saveData(2, orderCrossCity.getDriverId(), 2, orderCrossCity.getId(), 1, c.doubleValue());
//        Driver driver = driverService.selectById(orderCrossCity.getDriverId());
//        driver.setBusinessMoney(new BigDecimal(null != driver.getBusinessMoney() ? driver.getBusinessMoney() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
//        driver.setLaveBusinessMoney(new BigDecimal(null != driver.getLaveBusinessMoney() ? driver.getLaveBusinessMoney() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
//        driver.setBalance(new BigDecimal(null != driver.getBalance() ? driver.getBalance() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
//        driverService.updateById(driver);
 
        // TODO: 2020/5/24 这里需要给司机和用户推送订单状态
        new Thread(new Runnable() {
            @Override
            public void run() {
                pushUtil.pushOrderState(1, orderCrossCity.getUserId(), orderCrossCity.getId(), 3, orderCrossCity.getState());
                pushUtil.pushOrderState(2, orderCrossCity.getDriverId(), orderCrossCity.getId(), 3, orderCrossCity.getState());
                pushUtil.pushDriverPosition(orderCrossCity.getId(), 3);
            }
        }).start();
 
        systemNoticeService.addSystemNotice(1, "您已成功完成出行订单支付,谢谢使用!", orderCrossCity.getUserId(), 1);
    }
 
 
 
 
    /**
     * 计算支付金额
     * @param startLonLat
     * @param endLonLat
     * @param peopleNumber
     * @param travelMode
     * @param lineId
     * @param serverCarModelId
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil queryOrderMoney(String startLonLat, String endLonLat, Integer peopleNumber, Integer travelMode, Integer lineId,
                                      Integer serverCarModelId, Integer totalSeat, String seatNumber) throws Exception {
        Double endLon = null;
        Double endLat = null;
        if (ToolUtil.isNotEmpty(endLonLat) && endLonLat.contains(",")) {
            String[] endArr = endLonLat.split(",");
            if (endArr.length == 2) {
                endLon = Double.valueOf(endArr[0]);
                endLat = Double.valueOf(endArr[1]);
            }
        }
        ResultUtil<Map<String, Object>> result = this.getPriceV2(lineId, null, totalSeat, peopleNumber, endLon, endLat, null);
        if (result.getCode() != 200) {
            return result;
        }
        Double price = Double.valueOf(String.valueOf(result.getData().get("price")));
        if (price < 0) {
            return ResultUtil.error("计算行程距离出错啦!");
        }
        return result;
    }
 
 
 
 
    /**
     * 订单支付
     * @param payType
     * @param orderId
     * @param couponId
     * @param type
     * @return
     * @throws Exception
     */
    @Override
    public ResultUtil payCrossCityOrder(Integer payType, Integer orderId, Integer couponId, Integer type) throws Exception {
        OrderCrossCity orderCrossCity = this.selectById(orderId);
        if(orderCrossCity.getState() != 7){
            return ResultUtil.error("订单已被支付,不允许重复支付");
        }
        Integer uid = orderCrossCity.getUserId();
        Double orderMoney = orderCrossCity.getOrderMoney();
        ResultUtil resultUtil = ResultUtil.success("");
        orderCrossCity.setCouponMoney(0D);//初始化历史数据
        orderCrossCity.setCouponId(null);
 
        if(payType == 1){//微信支付
            String out_trade_no = buildCbyzxCrossCityOutTradeNo(orderId);
            Driver driver = driverService.selectById(orderCrossCity.getDriverId());
            if(null == driver || ToolUtil.isEmpty(driver.getAppletsOpenId())){
                return ResultUtil.errorOpenId("司机未绑定微信小程序openid,无法发起微信支付");
            }
            JSONObject response = cbyzxOrderPayHelper.createOrder(orderCrossCity.getDriverId(), driver.getAppletsOpenId(), out_trade_no, orderMoney);
            if(!cbyzxOrderPayHelper.isCreateSuccess(response)){
                return ResultUtil.error(cbyzxOrderPayHelper.extractMessage(response), response);
            }
            resultUtil = ResultUtil.success(response);
            paymentRecordService.saveData(1, orderCrossCity.getDriverId(), 2, orderId, 3, 1, orderMoney, out_trade_no, 1);//添加预支付数据
        }
        if(payType == 2){//支付宝支付
            String out_trade_no = orderId + "_3_" + UUIDUtil.getRandomCode(5);
            resultUtil = payMoneyUtil.alipay("完成订单", "完成订单", "", out_trade_no, orderMoney.toString(), "/base/aliPayCrossCity");
            paymentRecordService.saveData(1, orderCrossCity.getDriverId(), 2, orderId, 3, 2, orderMoney, "", 1);//添加预支付数据
        }
        if(payType == 4){
            // TODO 司机云闪付 跨城下单调起云闪付
            Double payMoney = orderCrossCity.getOrderMoney();
            paymentRecordService.saveData(1, orderCrossCity.getDriverId(), 2, orderId, 3, 4, orderMoney, "", 1);//添加预支付数据
            resultUtil = placeAnOrder(new BigDecimal(payMoney), 4,3,orderId);
        }
        this.updateAllColumnById(orderCrossCity);
        return resultUtil;
    }
 
    /**
     * 创博优完成订单支付回调单号,增加业务前缀避免与改派支付共用回调地址时串单。
     */
    private String buildCbyzxCrossCityOutTradeNo(Integer orderId) throws Exception {
        return "crossCity_" + orderId + "_3_" + UUIDUtil.getRandomCode(5);
    }
 
 
    private ResultUtil placeAnOrder(BigDecimal amount, Integer type, Integer orderType, Integer orderId) throws Exception {
        JSONObject json = new JSONObject();
        json.put("requestTimestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));    // 报文请求时间
        json.put("merOrderId", Util.getMerOrderId(qrCodeConfiguration.getMsgSrcId())); // 商户订单号
        json.put("mid", qrCodeConfiguration.getMid()); // 商户号
        json.put("tid", qrCodeConfiguration.getTid());    // 终端号
        json.put("instMid", qrCodeConfiguration.getInstMid()); // 业务类型
        json.put("totalAmount", amount.multiply(new BigDecimal("100")).intValue());      // 支付总金额
        json.put("orderDesc", "APP下单"); // 订单描述
        json.put("srcReserve", orderId+"-"+orderType+"-"+type); // 预留字段
        json.put("subAppId", "wxasdasdasdasdads");
        json.put("notifyUrl", "https://zhentonggongsi.com:443/driver/api/placeOrder/notifyUrl");
        json.put("tradeType", "APP");  // 交易类型,微信必传
        //  json.put("divisionFlag", true); // 分账标记
        //  json.put("platformAmount", 0); // 平台商户分账金额
//        ArrayList<JSONObject> subOrders = new ArrayList<>();
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("mid", "988460101800201");
//        jsonObject.put("totalAmount", 1);
//        subOrders.add(jsonObject);
        //    json.put("subOrders", subOrders);
 
        System.err.println("请求报文json:\n" + json);
        String url;
        if(1 == type){
//            url = "https://test-api-open.chinaums.com/v1/netpay/wx/app-pre-order";// 测试
            url = "https://api-mop.chinaums.com/v1/netpay/wx/app-pre-order";
        }else if (2 == type){
//            url = "https://test-api-open.chinaums.com/v1/netpay/trade/precreate";// 测试
            url = "https://api-mop.chinaums.com/v1/netpay/trade/precreate";
        }else {
//            url = "https://test-api-open.chinaums.com/v1/netpay/uac/app-order";// 测试
            url = "https://api-mop.chinaums.com/v1/netpay/uac/app-order";
        }
        //OPEN-BODY-SIG 方式
        String result = GetOpenBodySig.sendOpenBodySig(qrCodeConfiguration.getAppId(),qrCodeConfiguration.getAppKey(),url, json.toString());
        System.err.println("响应报文json:\n" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Object appPayRequest = jsonObject.get("appPayRequest");
        System.out.println(appPayRequest);
        return ResultUtil.success(appPayRequest);
    }
 
 
 
    /**
     * 支付成功后的回调操作
     * @param id            订单=id
     * @param order_id      工行支付单号
     * @param type          1=微信,2=支付宝 3=扫码支付 4=云闪付
     * @throws Exception
     */
    @Override
    public void payOrderCrossCityCallback(Integer id, String order_id, Integer type) throws Exception {
        OrderCrossCity orderCrossCity = this.selectById(id);
        System.out.println("跨城订单========================"+orderCrossCity);
        PaymentRecord query = paymentRecordService.query(1, orderCrossCity.getDriverId(), 2, id, 3, type, 1);
        System.out.println("================================="+query);
        if(null != query && query.getState() == 1){
            System.out.println("================================="+query);
            try {
                //添加交易明细
                transactionDetailsService.saveData(orderCrossCity.getUserId(), "跨城出行订单", query.getAmount(), 2, 1, 1, 3, query.getOrderId());
                orderCrossCity.setState(2);//先支付再服务
                orderCrossCity.setPayType(type);
                orderCrossCity.setPayMoney(query.getAmount());
                this.updateById(orderCrossCity);
                System.out.println("==============orderCrossCity修改完毕==================="+orderCrossCity);
 
 
                UserInfo userInfo = userInfoMapper.selectById(orderCrossCity.getUserId());
                OpenCity openCity = openCityService.openCity1(orderCrossCity.getStartLon().toString(), orderCrossCity.getStartLat().toString());
                SysIntegral query1 = sysIntegralMapper.query(openCity.getId());
                userInfo.setIntegral(userInfo.getIntegral() + (query.getAmount().intValue() * query1.getIntegral()));//积分
                userInfoMapper.updateById(userInfo);
                System.out.println("==============userInfo修改完毕==================="+userInfo);
 
                query.setState(2);
                query.setCode(order_id);
                paymentRecordService.updateById(query);
                System.out.println("==============PaymentRecord修改完毕==================="+query);
 
                //添加已收入明细
                // TODO: 2022/3/19  抽成按照订单金额计算,优先保证司机的收入,用户支付金额不够,则在平台收入中补贴司机收入
                //例如:订单金额10元,优惠3元,司机收入比例80%,平台收入比例20%。
                //司机收入:10 * 0.8 = 8
                //平台收入:7 - 8 = -1
//                Line line = lineService.selectById(orderCrossCity.getLineId());
//                Double speMoney = Double.valueOf(line.getRakeRate());
//                BigDecimal c = new BigDecimal(orderCrossCity.getOrderMoney()).multiply(new BigDecimal(1 - (speMoney / 100))).setScale(2, BigDecimal.ROUND_HALF_EVEN);//司机收入
//                BigDecimal d = new BigDecimal(orderCrossCity.getPayMoney()).subtract(c).setScale(2, BigDecimal.ROUND_HALF_EVEN);//企业收入
//                incomeService.saveData(1, orderCrossCity.getCompanyId(), 2, orderCrossCity.getId(), 3, d.doubleValue());
//                incomeService.saveData(2, orderCrossCity.getDriverId(), 2, orderCrossCity.getId(), 3, c.doubleValue());
//                System.out.println("==============incomeService修改完毕===================");
//                Driver driver = driverService.selectById(orderCrossCity.getDriverId());
//                driver.setBusinessMoney(new BigDecimal(null != driver.getBusinessMoney() ? driver.getBusinessMoney() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
//                driver.setLaveBusinessMoney(new BigDecimal(null != driver.getLaveBusinessMoney() ? driver.getLaveBusinessMoney() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
//                driver.setBalance(new BigDecimal(null != driver.getBalance() ? driver.getBalance() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
//                driverService.updateById(driver);
//                System.out.println("==============driver修改完毕==================="+driver);
 
                // TODO: 2020/5/24 这里需要给司机和用户推送订单状态
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        pushUtil.pushOrderState(1, orderCrossCity.getUserId(), orderCrossCity.getId(), 3, orderCrossCity.getState());
                        pushUtil.pushOrderState(2, orderCrossCity.getDriverId(), orderCrossCity.getId(), 3, orderCrossCity.getState());
                        pushUtil.pushDriverPosition(orderCrossCity.getId(), 3);
                    }
                }).start();
 
 
                systemNoticeService.addSystemNotice(1, "您已使用" + (type == 1 ? "微信" :(type == 2) ?"支付宝":(type == 3)?"扫码支付":"云闪付") + "成功完成出行订单支付,谢谢使用!", orderCrossCity.getUserId(), 1);
                System.out.println("==============跨城订单修改完毕===================");
            }catch (Exception e){
                System.out.println("报错信息==============="+e.getMessage());
                e.printStackTrace();
            }
        }else{
            System.err.println("预支付数据异常(orderId = "  + id + ")");
        }
    }
 
    @Override
    public boolean calculateMileage(OrderPosition orderPosition) throws Exception {
        Integer orderId = orderPosition.getOrderId();
        String lon = orderPosition.getLon();
        String lat = orderPosition.getLat();
        OrderCrossCity order = this.selectById(orderId);
        if(null == order){
            System.err.println("跨城订单数据异常:" + orderId);
            return false;
        }
 
        //跨城记录所有服务完成之前的订单服务距离
        List<OrderCrossCity> orderCrossCities = this.selectList(new EntityWrapper<OrderCrossCity>().eq("orderNum", order.getOrderNum()).eq("isDelete", 1).in("state", Arrays.asList(2, 3, 4, 5)));
        for(OrderCrossCity orderCrossCity : orderCrossCities){
            boolean b = false;
            OrderPosition orderPosition1 = orderPositionService.queryNew(orderCrossCity.getId(), 3);
            if(null != orderPosition1){
                String now = lon + "," + lat;
                String old = orderPosition1.getLon() + "," + orderPosition1.getLat();
                Map<String, Double> distance = geodesyUtil.getDistance(now, old);
                if(null != distance){
                    Double distance1 = distance.get("WGS84");
                    if(Double.valueOf(distance1) > 50 && orderCrossCity.getState() == 5){//大于50米表示在移动
                        orderCrossCity.setMileage(new BigDecimal(orderCrossCity.getMileage()).add(new BigDecimal(distance1)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
                        this.updateById(orderCrossCity);
                        b = true;
                    }
                }else{
                    System.err.println("调用高德计算距离出错");
                }
            }else{
                orderCrossCity.setMileage(0D);
                this.updateById(orderCrossCity);
                b = true;//第一条数据不作处理,直接存储
            }
            if(b){
                //先计算里程,在存储最新位置
                orderPosition.setInsertTime(new Date());
                mongoTemplate.save(orderPosition);
            }
        }
        return false;//上层不需要处理
    }
 
    @Override
    public List<OrderCrossCity> queryListOrder(Integer driverId, Integer lineShiftId, List<Integer> state, String day) throws Exception {
        return orderCrossCityMapper.queryListOrder(driverId, lineShiftId, state, day);
    }
 
    /**
     * 获取所有快到期的预约单(出行时间在30分钟内)
     * @return
     * @throws Exception
     */
    @Override
    public List<OrderCrossCity> queryMaturity() throws Exception {
        return orderCrossCityMapper.queryMaturity();
    }
 
    /**
     * 计算价格
     * @param distance
     * @param peopleNumber
     * @param travelMode
     * @param lineId
     * @param serverCarModelId
     * @param totalSeat
     * @param seatNumber
     * @return
     */
    public ResultUtil<Map<String, Object>> getPrice(Double distance, Integer peopleNumber, Integer travelMode, Integer lineId, Integer serverCarModelId, Integer totalSeat, String seatNumber){
        if(0 >= peopleNumber && peopleNumber > 6){
            return ResultUtil.error("请输入正确的乘车人数");
        }
 
        Map<String, Object> map = new HashMap<>();
        map.put("distance", distance);
        Integer pricePeopleNumber = travelMode != null && travelMode == 2 && totalSeat != null && totalSeat > 0 ? totalSeat : peopleNumber;
        BigDecimal unitPrice = queryDefaultLineDestinationPrice(lineId, totalSeat);
        map.put("price", unitPrice == null ? -1 : multiplyPeopleNumber(unitPrice, pricePeopleNumber).doubleValue());
        return ResultUtil.success(map);
    }
 
    public ResultUtil<Map<String, Object>> getPriceV2(Integer lineId, LineShiftDriver lineShiftDriver, Double endLon, Double endLat, Integer peopleNumber) {
        Map<String, Object> map = new HashMap<>();
        map.put("distance", 0);
        if (lineShiftDriver == null || endLon == null || endLat == null || peopleNumber == null || peopleNumber <= 0) {
            map.put("price", -1);
            return ResultUtil.success(map);
        }
        if (lineId != null && lineId <= -1) {
            BigDecimal price = querySelfTripNearestPrice(lineShiftDriver, endLon, endLat);
            map.put("price", price == null ? -1 : multiplyPeopleNumber(price, peopleNumber).doubleValue());
            return ResultUtil.success(map);
        }
        BigDecimal price = queryLineDestinationPrice(lineId, lineShiftDriver, endLon, endLat);
        map.put("price", price == null ? -1 : multiplyPeopleNumber(price, peopleNumber).doubleValue());
        return ResultUtil.success(map);
    }
 
    public ResultUtil<Map<String, Object>> getPriceV2(Integer lineId, Integer lineDestinationId, Integer totalSeat,
                                                      Integer peopleNumber, Double endLon, Double endLat, Integer lineShiftDriverId) {
        Map<String, Object> map = new HashMap<>();
        map.put("distance", 0);
        if (peopleNumber == null || peopleNumber <= 0 || endLon == null || endLat == null) {
            map.put("price", -1);
            return ResultUtil.success(map);
        }
        if (lineDestinationId != null) {
            Map<String, Object> destination = lineMapper.queryLineDestinationById(lineDestinationId, lineId);
            BigDecimal unitPrice = null;
            if (destination != null) {
                unitPrice = getDestinationPrice(destination, totalSeat);
            }
            map.put("price", unitPrice == null ? -1 : multiplyPeopleNumber(unitPrice, peopleNumber).doubleValue());
            return ResultUtil.success(map);
        }
        if (lineId != null && lineId <= -1) {
            if (lineShiftDriverId == null) {
                map.put("price", -1);
                return ResultUtil.success(map);
            }
            LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(lineShiftDriverId);
            if (lineShiftDriver == null) {
                map.put("price", -1);
                return ResultUtil.success(map);
            }
            return getPriceV2(lineId, lineShiftDriver, endLon, endLat, peopleNumber);
        }
        List<Map<String, Object>> destinations = lineMapper.queryLineDestinations(lineId);
        if (destinations == null || destinations.size() == 0) {
            map.put("price", -1);
            return ResultUtil.success(map);
        }
        BigDecimal defaultPrice = getDestinationPrice(destinations.get(0), totalSeat);
        BigDecimal matchedPrice = null;
        for (Map<String, Object> destination : destinations) {
            if (isPointInDestinationFence(destination, endLon, endLat)) {
                matchedPrice = getDestinationPrice(destination, totalSeat);
                break;
            }
        }
        BigDecimal finalPrice = matchedPrice == null ? defaultPrice : matchedPrice;
        map.put("price", finalPrice == null ? -1 : multiplyPeopleNumber(finalPrice, peopleNumber).doubleValue());
        return ResultUtil.success(map);
    }
 
    private BigDecimal querySelfTripNearestPrice(LineShiftDriver lineShiftDriver, Double endLon, Double endLat) {
        Integer customerId = lineShiftDriverMapper.queryCustomerIdByLineShiftDriverId(lineShiftDriver.getId());
        if (customerId == null) {
            return null;
        }
        DriverSelfTrip selfTrip = driverSelfTripMapper.selectById(customerId);
        if (selfTrip == null || ToolUtil.isEmpty(selfTrip.getDestJson())) {
            return null;
        }
        JSONArray destArray = JSON.parseArray(selfTrip.getDestJson());
        if (destArray == null || destArray.size() == 0) {
            return null;
        }
        BigDecimal bestPrice = null;
        Double minDistance = null;
        String target = endLon + "," + endLat;
        for (int i = 0; i < destArray.size(); i++) {
            JSONObject dest = destArray.getJSONObject(i);
            if (dest == null || dest.getDouble("endLon") == null || dest.getDouble("endLat") == null || dest.getBigDecimal("price") == null) {
                continue;
            }
            String source = dest.getDouble("endLon") + "," + dest.getDouble("endLat");
            Map<String, Double> distanceMap = geodesyUtil.getDistance(source, target);
            Double currentDistance = distanceMap == null ? null : distanceMap.get("WGS84");
            if (currentDistance == null) {
                continue;
            }
            if (minDistance == null || currentDistance < minDistance) {
                minDistance = currentDistance;
                bestPrice = dest.getBigDecimal("price");
            }
        }
        return bestPrice;
    }
 
    private BigDecimal queryLineDestinationPrice(Integer lineId, LineShiftDriver lineShiftDriver, Double endLon, Double endLat) {
        List<Map<String, Object>> destinations = lineMapper.queryLineDestinations(lineId);
        if (destinations == null || destinations.size() == 0) {
            return null;
        }
        BigDecimal defaultPrice = getDestinationPrice(destinations.get(0), lineShiftDriver.getTotalSeat());
        for (Map<String, Object> destination : destinations) {
            if (isPointInDestinationFence(destination, endLon, endLat)) {
                BigDecimal price = getDestinationPrice(destination, lineShiftDriver.getTotalSeat());
                return price == null ? defaultPrice : price;
            }
        }
        return defaultPrice;
    }
 
    private boolean isPointInDestinationFence(Map<String, Object> destination, Double lon, Double lat) {
        if (destination == null || lon == null || lat == null) {
            return false;
        }
        Integer fenceType = destination.get("fenceType") == null ? null : Integer.valueOf(String.valueOf(destination.get("fenceType")));
        String coordinate = destination.get("coordinate") == null ? null : String.valueOf(destination.get("coordinate"));
        if (fenceType == null || ToolUtil.isEmpty(coordinate)) {
            return false;
        }
        if (fenceType == 1) {
            String[] arr = coordinate.split(";");
            if (arr.length != 2) {
                return false;
            }
            String[] center = arr[0].split(",");
            if (center.length != 2) {
                return false;
            }
            Map<String, Double> distanceMap = geodesyUtil.getDistance(center[0] + "," + center[1], lon + "," + lat);
            Double currentDistance = distanceMap == null ? null : distanceMap.get("WGS84");
            return currentDistance != null && currentDistance <= Double.valueOf(arr[1]);
        }
        return isPointInPolygon(coordinate, lon, lat);
    }
 
    private boolean isPointInPolygon(String coordinate, Double lon, Double lat) {
        String[] points = coordinate.split(";");
        if (points.length < 3) {
            return false;
        }
        boolean inside = false;
        for (int i = 0, j = points.length - 1; i < points.length; j = i++) {
            String[] current = points[i].split(",");
            String[] previous = points[j].split(",");
            if (current.length != 2 || previous.length != 2) {
                continue;
            }
            double xi = Double.parseDouble(current[0]);
            double yi = Double.parseDouble(current[1]);
            double xj = Double.parseDouble(previous[0]);
            double yj = Double.parseDouble(previous[1]);
            boolean intersect = ((yi > lat) != (yj > lat))
                    && (lon < (xj - xi) * (lat - yi) / ((yj - yi) == 0 ? 0.0000001D : (yj - yi)) + xi);
            if (intersect) {
                inside = !inside;
            }
        }
        return inside;
    }
 
    private BigDecimal getBigDecimal(Object value) {
        if (value == null || ToolUtil.isEmpty(String.valueOf(value))) {
            return null;
        }
        try {
            return new BigDecimal(String.valueOf(value));
        } catch (Exception e) {
            return null;
        }
    }
 
    private BigDecimal queryDefaultLineDestinationPrice(Integer lineId, Integer totalSeat) {
        List<Map<String, Object>> destinations = lineMapper.queryLineDestinations(lineId);
        if (destinations == null || destinations.size() == 0) {
            return null;
        }
        return getDestinationPrice(destinations.get(0), totalSeat);
    }
 
    private BigDecimal getDestinationPrice(Map<String, Object> destination, Integer totalSeat) {
        if (destination == null) {
            return null;
        }
        BigDecimal price = totalSeat != null && totalSeat == 6
                ? getBigDecimal(destination.get("price7"))
                : getBigDecimal(destination.get("price5"));
        return price == null ? getBigDecimal(destination.get("price5")) : price;
    }
 
    private BigDecimal multiplyPeopleNumber(BigDecimal price, Integer peopleNumber) {
        if (price == null || peopleNumber == null || peopleNumber <= 0) {
            return null;
        }
        return price.multiply(new BigDecimal(peopleNumber)).setScale(2, BigDecimal.ROUND_HALF_UP);
    }
 
    @Override
    public List<OrderCrossCity> taskMidAxbUnBindSend() throws Exception {
        return this.baseMapper.taskMidAxbUnBindSend();
    }
 
    /**
     * 获取订单编号
     * @return
     * @throws Exception
     */
    public synchronized String getOrderNum(Integer driverId, Integer lineShiftDriverId) throws Exception{
        List<OrderCrossCity> orderCrossCities = orderCrossCityMapper.queryOrders(driverId, lineShiftDriverId, Arrays.asList(2, 3, 4, 5, 6, 7));
        if(orderCrossCities.size() > 0){
            return orderCrossCities.get(0).getOrderNum();
        }
        int size = this.selectCount(null);
        while (true){
            String orderNum = "CR" + String.valueOf(1000000 + size + 1).substring(1);
            List<OrderCrossCity> orderNum1 = this.selectList(new EntityWrapper<OrderCrossCity>().eq("orderNum", orderNum));
            if(orderNum1.size() == 0){
                return orderNum;
            }
            size++;
        }
    }
 
 
    @Override
    public ResultUtil cancleOrder(Integer orderId) throws Exception {
        OrderCrossCity orderCrossCity = orderCrossCityMapper.selectById(orderId);
        if(orderCrossCity.getState() == 7 && orderCrossCity.getPayMoney() == null){
            orderCrossCity.setState(10);
            orderCrossCityMapper.updateById(orderCrossCity);
 
            OrderCancel orderCancel = new OrderCancel();
            orderCancel.setOrderId(orderId);
            orderCancel.setOrderType(3);
            orderCancel.setReason("用户未及时付款,系统自动取消订单");
            orderCancel.setRemark("用户未及时付款,系统自动取消订单");
            orderCancel.setState(2);
            orderCancel.setInsertTime(new Date());
            orderCancel.setUserType(2);
            orderCancelService.insert(orderCancel);
 
            //修改司机座位
            LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(orderCrossCity.getLineShiftDriverId());
            lineShiftDriver.setLaveSeat(lineShiftDriver.getLaveSeat() + orderCrossCity.getPeopleNumber());
            lineShiftDriver.setLaveSeatNumber(lineShiftDriver.getLaveSeatNumber() + (orderCrossCity.getTravelMode() == 1 ? "," : "") + orderCrossCity.getSeatNumber());
            lineShiftDriverMapper.updateById(lineShiftDriver);
 
            //修改司机为空闲
            List<OrderCrossCity> orderCrossCities = orderCrossCityMapper.queryByDriverId(orderCrossCity.getDriverId(), 2, 3, 4, 5, 11);
            if(orderCrossCities.size() == 0){
                Driver driver = driverService.selectById(orderCrossCity.getDriverId());
                driver.setState(2);
                driverService.updateById(driver);
            }
        }
        return ResultUtil.success();
    }
 
 
    /**
     * 跨城代客下单操作
     * @param warpper 代客下单参数
     * @param driverId 司机ID
     * @return 订单ID
     * @throws Exception
     */
    @Override
    public synchronized ResultUtil<BaseWarpper> orderCrossCityOnBehalf(OrderCrossCityOnBehalfWarpper warpper, Integer driverId) throws Exception {
        // 1. 参数校验
        if (warpper.getLineShiftDriverId() == null) {
            return ResultUtil.error("班次ID不能为空");
        }
        if (warpper.getPeopleNumber() == null || warpper.getPeopleNumber() < 1 || warpper.getPeopleNumber() > 7) {
            return ResultUtil.error("乘车人数必须在1-7之间");
        }
        if (ToolUtil.isEmpty(warpper.getPassengersPhone())) {
            return ResultUtil.error("乘客手机号不能为空");
        }
        if (warpper.getPlacementLat() == null || warpper.getPlacementLon() == null || ToolUtil.isEmpty(warpper.getPlacementAddress())) {
            return ResultUtil.error("下单地点点信息不完整");
        }
        if (warpper.getStartLon() == null || warpper.getStartLat() == null || ToolUtil.isEmpty(warpper.getStartAddress())) {
            return ResultUtil.error("上车点信息不完整");
        }
        if (warpper.getEndLon() == null || warpper.getEndLat() == null || ToolUtil.isEmpty(warpper.getEndAddress())) {
            return ResultUtil.error("下车点信息不完整");
        }
        if (warpper.getOtherFee() != null && warpper.getOtherFee().compareTo(BigDecimal.ZERO) < 0) {
            return ResultUtil.error("其他费用不能为负数");
        }
        if (warpper.getChangePrice() != null && warpper.getChangePrice().compareTo(BigDecimal.ZERO) < 0) {
            return ResultUtil.error("改价费用不能为负数");
        }
 
        // 2. 校验班次信息
        LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(warpper.getLineShiftDriverId());
        if (lineShiftDriver == null) {
            return ResultUtil.error("班次信息不存在");
        }
        if (!driverId.equals(lineShiftDriver.getDriverId())) {
            return ResultUtil.error("无权操作此班次");
        }
 
        // 3. 校验剩余座位数
        if (lineShiftDriver.getLaveSeat() < warpper.getPeopleNumber()) {
            return ResultUtil.error("座位不足,无法下单");
        }
 
        // 4. 自动分配座位号
        String laveSeatNumber = lineShiftDriver.getLaveSeatNumber();
        if (ToolUtil.isEmpty(laveSeatNumber)) {
            return ResultUtil.error("无可用座位");
        }
        String[] availableSeats = laveSeatNumber.split(",");
        if (availableSeats.length < warpper.getPeopleNumber()) {
            return ResultUtil.error("座位不足,无法下单");
        }
        // 取前 peopleNumber 个座位
        StringBuilder seatNumberBuilder = new StringBuilder();
        for (int i = 0; i < warpper.getPeopleNumber(); i++) {
            if (i > 0) {
                seatNumberBuilder.append(",");
            }
            seatNumberBuilder.append(availableSeats[i]);
        }
        String seatNumber = seatNumberBuilder.toString();
 
        // 5. 获取司机信息
        Driver driver = driverService.selectById(driverId);
        if (driver == null) {
            return ResultUtil.error("司机信息不存在");
        }
        if (driver.getState() == 1) {
            return ResultUtil.error("司机处于离线状态");
        }
 
        // 6. 获取线路班次信息
        LineSite lineSite;
        if (lineShiftDriver.getLineShiftId() <= -1) {
            lineSite = new LineSite();
            lineSite.setLineId(-1);
            if (lineShiftDriver.getCustomerId() != null) {
                DriverSelfTrip selfTrip = driverSelfTripMapper.selectById(lineShiftDriver.getCustomerId());
                if (selfTrip != null) {
                    lineSite.setStartTime(selfTrip.getStartTime());
                }
            }
        } else {
            lineSite = lineSiteService.selectById(lineShiftDriver.getLineShiftId());
            if (lineSite == null) {
                return ResultUtil.error("线路班次信息不存在");
            }
            Line line = lineService.selectById(lineSite.getLineId());
            if (line == null) {
                return ResultUtil.error("线路信息不存在");
            }
        }
 
 
        // 7. 处理用户信息
        String phone = warpper.getPassengersPhone();
        UserInfo userInfo = userInfoMapper.queryByPhone(phone);
        if (userInfo == null) {
 
            Integer integer = userInfoMapper.selectCount(null) + 1000001;
            String nickName = "GRJY" + String.valueOf(integer).substring(1);
 
            // 自动创建用户
            userInfo = new UserInfo();
            userInfo.setNickName(nickName);
            userInfo.setPhone(warpper.getPassengersPhone());
            userInfo.setState(1);
            userInfo.setFlag(1);
            userInfo.setInsertTime(new Date());
            userInfo.setInsertUser(driverId);
            userInfoMapper.insert(userInfo);
        }
 
        // 8. 检查用户是否有未完成订单
        List<OrderPrivateCar> orderPrivateCars = orderPrivateCarMapper.queryByState(userInfo.getId(), 1, 1, 1, 2, 3, 4, 5, 6, 7, 11, 12);
        if (orderPrivateCars.size() > 0) {
            return ResultUtil.error("该乘客有未完成的订单");
        }
        List<OrderTaxi> orderTaxis = orderTaxiMapper.queryByState_(userInfo.getId(), 1, 1, 1, 2, 3, 4, 5, 6, 7, 11, 12);
        if (orderTaxis.size() > 0) {
            return ResultUtil.error("该乘客有未完成的订单");
        }
        List<OrderCrossCity> orderCrossCities1 = orderCrossCityMapper.queryByState(userInfo.getId(), 1, 2, 3, 4, 5, 6, 7, 11, 12);
        if (orderCrossCities1.size() > 0) {
            return ResultUtil.error("该乘客有未完成的订单");
        }
 
//        // 9. 检查司机是否正在服务中
//        List<OrderCrossCity> orderCrossCities2 = orderCrossCityMapper.queryOrders(driverId, warpper.getLineShiftDriverId(), Arrays.asList(5));
//        if (orderCrossCities2.size() > 0) {
//            return ResultUtil.error("司机正在服务中");
//        }
 
//        // 10. 计算价格
//        Map<String, String> distanceMap = gdMapElectricFenceUtil.getDistance(
//                warpper.getStartLon() + "," + warpper.getStartLat(),
//                warpper.getEndLon() + "," + warpper.getEndLat(), 1);
//        if (distanceMap == null) {
//            return ResultUtil.error("计算行程距离出错");
//        }
//        Double distance = Double.valueOf(distanceMap.get("distance"));
 
        // 获取车辆信息
        Car car = carServiceImpl.selectById(driver.getCarId());
        if (car == null) {
            return ResultUtil.error("车辆信息不存在");
        }
        CarModel carModel = carModelMapper.selectById(car.getCarModelId());
        if (carModel == null) {
            return ResultUtil.error("车型信息不存在");
        }
        CarService carService = carServiceMapper.query(3, driver.getCarId());
        if(null == carService){
            return ResultUtil.error("车辆未开通该服务");
        }
        ResultUtil<Map<String, Object>> priceResult = this.getPriceV2(lineSite.getLineId(), lineShiftDriver,
                warpper.getEndLon(), warpper.getEndLat(), warpper.getPeopleNumber());
        if (priceResult.getCode() != 200) {
            return ResultUtil.error("计算价格失败");
        }
        Double ticketPrice = Double.valueOf(priceResult.getData().get("price").toString());
        if (ticketPrice < 0) {
            return ResultUtil.error("计算价格失败");
        }
 
        // 计算合计费用
        Double otherFee = warpper.getOtherFee() != null ? warpper.getOtherFee().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() : 0D;
        Double totalMoney = new BigDecimal(ticketPrice).add(new BigDecimal(otherFee)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
 
        // 11. 创建订单
        OrderCrossCity orderCrossCity = new OrderCrossCity();
        orderCrossCity.setUserId(userInfo.getId());
        orderCrossCity.setPassengers(userInfo.getName());
        orderCrossCity.setPassengersPhone(warpper.getPassengersPhone());
        orderCrossCity.setServerCarModelId(carService.getServerCarModelId());
        orderCrossCity.setDriverId(driverId);
        orderCrossCity.setLineId(lineSite.getLineId());
        orderCrossCity.setCarId(driver.getCarId());
        orderCrossCity.setOrderNum(this.getOrderNum(driverId, warpper.getLineShiftDriverId()));
 
        // 下单地点
        orderCrossCity.setPlacementLat(warpper.getPlacementLat());
        orderCrossCity.setPlacementLon(warpper.getPlacementLon());
        String placementAddress = warpper.getPlacementAddress();
        placementAddress = placementAddress.replaceAll("& #40;", "(");
        placementAddress = placementAddress.replaceAll("& #41;", ")");
        orderCrossCity.setPlacementAddress(placementAddress);
 
        // 上车点
        orderCrossCity.setStartLon(warpper.getStartLon());
        orderCrossCity.setStartLat(warpper.getStartLat());
        String startAddress = warpper.getStartAddress();
        startAddress = startAddress.replaceAll("& #40;", "(");
        startAddress = startAddress.replaceAll("& #41;", ")");
        orderCrossCity.setStartAddress(startAddress);
 
        // 下车点
        orderCrossCity.setEndLon(warpper.getEndLon());
        orderCrossCity.setEndLat(warpper.getEndLat());
        String endAddress = warpper.getEndAddress();
        endAddress = endAddress.replaceAll("& #40;", "(");
        endAddress = endAddress.replaceAll("& #41;", ")");
        orderCrossCity.setEndAddress(endAddress);
 
        orderCrossCity.setMileage(0D);
        if (warpper.getChangePrice() != null) {
            orderCrossCity.setOrderMoney(warpper.getChangePrice().doubleValue());
            orderCrossCity.setHasChangePrice(1);
        } else {
            orderCrossCity.setOrderMoney(totalMoney);
        }
        orderCrossCity.setCompanyId(driver.getCompanyId());
        orderCrossCity.setPeopleNumber(warpper.getPeopleNumber());
        orderCrossCity.setSeatNumber(seatNumber);
 
        List<OrderCrossCity> orderCrossCities = this.selectList(new EntityWrapper<OrderCrossCity>().eq("orderNum", orderCrossCity.getOrderNum()).eq("isDelete", 1));
        orderCrossCity.setSort(orderCrossCities.size() + 1);
        orderCrossCity.setState(7); // 待支付
        orderCrossCity.setInsertTime(new Date());
 
        // 设置出行时间为班次日期+开始时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(lineShiftDriver.getDay());
        String[] startTimeParts = lineSite.getStartTime().split(":");
        calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTimeParts[0]));
        calendar.set(Calendar.MINUTE, Integer.parseInt(startTimeParts[1]));
        calendar.set(Calendar.SECOND, 0);
        orderCrossCity.setTravelTime(calendar.getTime());
 
        orderCrossCity.setSnatchOrderTime(new Date());
        orderCrossCity.setTravelMode(1); // 固定拼车
        orderCrossCity.setIsDelete(1);
        orderCrossCity.setIsReassign(1);
        orderCrossCity.setLineShiftDriverId(warpper.getLineShiftDriverId());
        orderCrossCity.setOrderSource(4); // 司机下单
        orderCrossCity.setOtherFee(warpper.getOtherFee());
        this.insert(orderCrossCity);
 
        // 13. 更新司机状态
        if (driver.getState() == 2) {
            driver.setState(3);
            driverService.updateById(driver);
        }
 
        // 14. 更新班次座位信息
        lineShiftDriver.setLaveSeat(lineShiftDriver.getLaveSeat() - warpper.getPeopleNumber());
        // 更新剩余座位号
        StringBuilder newLaveSeatNumber = new StringBuilder();
        for (int i = warpper.getPeopleNumber(); i < availableSeats.length; i++) {
            if (newLaveSeatNumber.length() > 0) {
                newLaveSeatNumber.append(",");
            }
            newLaveSeatNumber.append(availableSeats[i]);
        }
        lineShiftDriver.setLaveSeatNumber(newLaveSeatNumber.toString());
        lineShiftDriverMapper.updateById(lineShiftDriver);
 
        // 15. 添加系统消息
        systemNoticeService.addSystemNotice(1, "您的跨城订单已下单成功,请尽快完成支付!", orderCrossCity.getUserId(), 1);
 
        // 16. 创建定时任务,30分钟未支付自动取消
        Integer orderId = orderCrossCity.getId();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                OrderCrossCity order = orderCrossCityMapper.selectById(orderId);
                if (order.getState() == 7 && order.getPayMoney() == null) {
                    order.setState(10);
                    orderCrossCityMapper.updateById(order);
 
                    OrderCancel orderCancel = new OrderCancel();
                    orderCancel.setOrderId(orderId);
                    orderCancel.setOrderType(3);
                    orderCancel.setReason("用户未及时付款,系统自动取消订单");
                    orderCancel.setRemark("用户未及时付款,系统自动取消订单");
                    orderCancel.setState(2);
                    orderCancel.setInsertTime(new Date());
                    orderCancel.setUserType(2);
                    orderCancelService.insert(orderCancel);
 
                    // 恢复座位
                    LineShiftDriver lsd = lineShiftDriverMapper.selectById(order.getLineShiftDriverId());
                    lsd.setLaveSeat(lsd.getLaveSeat() + order.getPeopleNumber());
                    lsd.setLaveSeatNumber(
                            (ToolUtil.isNotEmpty(lsd.getLaveSeatNumber()) ? lsd.getLaveSeatNumber() + "," : "") +
                                    order.getSeatNumber()
                    );
                    lineShiftDriverMapper.updateById(lsd);
 
                    // 修改司机为空闲
                    List<OrderCrossCity> orders = orderCrossCityMapper.queryByDriverId(order.getDriverId(), 2, 3, 4, 5, 11);
                    if (orders.size() == 0) {
                        Driver d = driverService.selectById(order.getDriverId());
                        d.setState(2);
                        driverService.updateById(d);
                    }
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask, 30 * 60 * 1000);
 
        // 17. 返回结果
        BaseWarpper baseWarpper = new BaseWarpper();
        baseWarpper.setId(orderCrossCity.getId());
        return ResultUtil.success(baseWarpper);
    }
 
    @Override
    public ResultUtil orderOnBehalfPay(int crossCityOrderId, int type, Integer driverId) throws Exception {
        OrderCrossCity order = orderCrossCityMapper.selectById(crossCityOrderId);
        if (order == null) {
            return ResultUtil.error("订单不存在");
        }
        if (!order.getDriverId().equals(driverId)) {
            return ResultUtil.error("您没有权限支付此订单");
        }
        if (order.getState() != 7) {
            return ResultUtil.error("订单不在待支付,无法完成订单");
        }
        if (type == 1) {
//            UserInfo userInfo = userInfoMapper.selectById(order.getUserId());
            Driver driver = driverService.selectById(driverId);
            if (driver == null) {
                return ResultUtil.error("司机不存在");
            }
            if (ToolUtil.isEmpty(driver.getAppletsOpenId())) {
                return ResultUtil.errorOpenId("司机未绑定微信小程序openid,无法发起微信支付");
            }
            String outTradeNo = buildCbyzxOnBehalfOutTradeNo(crossCityOrderId);
            JSONObject response = cbyzxOrderPayHelper.createOrder(
                    order.getUserId(),
                    driver.getAppletsOpenId(),
                    outTradeNo,
                    order.getOrderMoney()
            );
            if (!cbyzxOrderPayHelper.isCreateSuccess(response)) {
                return ResultUtil.error(cbyzxOrderPayHelper.extractMessage(response), response);
            }
            paymentRecordService.saveData(1, order.getDriverId(), 2, crossCityOrderId, 3, 1, order.getOrderMoney(), outTradeNo, 1);
            return ResultUtil.success(response);
        } else if (type == 3) {
            order.setState(2);
            order.setPayMoney(order.getOrderMoney());
            orderCrossCityMapper.updateById(order);
 
 
            //添加交易明细
            transactionDetailsService.saveData(driverId, "跨城出行订单", order.getOrderMoney(), 2, 1, 2, 3, order.getId());
            return ResultUtil.success();
        } else if (type == 2) {
            String path = "pages/home/home";
            String unlimitQrcode = weChatUtil.getUnlimitQrcode(path, "default");
            return ResultUtil.success(unlimitQrcode);
        }
        return ResultUtil.error("支付失败");
    }
 
    /**
     * 创博优代客支付单号,增加业务前缀便于统一回调路由。
     */
    private String buildCbyzxOnBehalfOutTradeNo(Integer orderId) throws Exception {
        return "onBehalf_" + orderId + "_3_" + UUIDUtil.getRandomCode(5);
    }
}