puzhibing
2023-06-12 d4f8078c2a062864dab885d6bd54fbe1195f85e2
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
package com.stylefeng.guns.modular.system.service.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.shiro.ShiroKit;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.controller.resp.DataStatisticsOrderYearResp;
import com.stylefeng.guns.modular.system.controller.resp.PerformanceTableResp;
import com.stylefeng.guns.modular.system.controller.resp.TOrderResp;
import com.stylefeng.guns.modular.system.controller.resp.TOrderServerResp;
import com.stylefeng.guns.modular.system.controller.util.UUIDUtil;
import com.stylefeng.guns.modular.system.dao.TAppUserMapper;
import com.stylefeng.guns.modular.system.dao.TBranchOfficeMapper;
import com.stylefeng.guns.modular.system.dao.TDriverMapper;
import com.stylefeng.guns.modular.system.dao.TOrderMapper;
import com.stylefeng.guns.modular.system.enums.OrderStateEnum;
import com.stylefeng.guns.modular.system.model.*;
import com.stylefeng.guns.modular.system.service.*;
import com.stylefeng.guns.modular.system.util.*;
import com.stylefeng.guns.modular.system.util.GaoDe.MapUtil;
import com.stylefeng.guns.modular.system.util.GaoDe.model.District;
import com.stylefeng.guns.modular.system.util.juhe.WeatherUtil;
import com.stylefeng.guns.modular.system.util.mongodb.model.Location;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author stylefeng
 * @since 2023-02-15
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements ITOrderService {
 
    @Resource
    private TOrderMapper tOrderMapper;
 
    @Resource
    private TAppUserMapper tAppUserMapper;
 
    @Resource
    private TDriverMapper tDriverMapper;
 
    @Resource
    private TBranchOfficeMapper tBranchOfficeMapper;
 
    @Autowired
    private ITAppUserService appUserService;
 
    @Autowired
    private RedisUtil redisUtil;
 
    @Autowired
    private ITSystemConfigService systemConfigService;
 
    @Autowired
    private ITYouTuiDriverService youTuiDriverService;
 
    @Resource
    private MongoTemplate mongoTemplate;
 
    @Autowired
    private IWeatherCityService weatherCityService;
 
    @Autowired
    private PushUtil pushUtil;
 
    @Autowired
    private ITDriverWorkService driverWorkService;
 
    @Autowired
    private ITDriverService driverService;
 
 
 
 
    @Override
    public List<TOrderResp> getOrderList(String createTime, String code, Integer source, String userName, String userPhone, Integer state, String driverName,Integer isException) {
        String startTime = null;
        String endTime = null;
        // 开始,结束时间
        if(StringUtils.hasLength(createTime)){
            String[] split = createTime.split(" - ");
            startTime = split[0] + " 00:00:00";
            endTime = split[1] + " 23:59:59";
        }
        Integer roleType = Objects.requireNonNull(ShiroKit.getUser()).getRoleType();
        Integer objectId = Objects.requireNonNull(ShiroKit.getUser()).getObjectId();
        return tOrderMapper.getOrderList(startTime,endTime,code,source,userName,userPhone,state,driverName,isException,roleType,objectId);
    }
 
    @Override
    public void orderDetail(Integer orderId, Model model) {
        // 订单信息
        TOrder tOrder = tOrderMapper.selectById(orderId);
        model.addAttribute("id",orderId);
        model.addAttribute("createTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tOrder.getCreateTime()));//下单时间
        model.addAttribute("code",tOrder.getCode());//订单编号
        model.addAttribute("source",tOrder.getSource());//订单来源
        model.addAttribute("startAddress",tOrder.getStartAddress());//起点
        model.addAttribute("startLng",tOrder.getStartLng());// 起点经度
        model.addAttribute("startLat",tOrder.getStartLat());// 起点纬度
        model.addAttribute("endAddress",tOrder.getEndAddress());//终点
        model.addAttribute("endLng",tOrder.getEndLng());// 终点经度
        model.addAttribute("endLat",tOrder.getEndLat());// 终点纬度
 
        if(Objects.nonNull(tOrder.getStartTime())){
            model.addAttribute("startTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tOrder.getStartTime()));//乘车时间
        }else {
            model.addAttribute("startTime","");//乘车时间
        }
        if(Objects.nonNull(tOrder.getBoardingTime())){
            model.addAttribute("boardingTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tOrder.getBoardingTime()));//乘车时间
        }else {
            model.addAttribute("boardingTime","");//乘车时间
        }
        if(Objects.nonNull(tOrder.getGetoffTime())){
            model.addAttribute("getoffTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tOrder.getGetoffTime()));//乘车时间
        }else {
            model.addAttribute("getoffTime","");//乘车时间
        }
        model.addAttribute("startPrice",tOrder.getStartPrice());//起步价
        model.addAttribute("overDrivePrice",tOrder.getOverDrivePrice());//里程费
        model.addAttribute("waitTimePrice",tOrder.getWaitTimePrice());//等待费
        model.addAttribute("badWeatherPrice",tOrder.getBadWeatherPrice());//恶劣天气费用
        model.addAttribute("orderMoney",tOrder.getOrderMoney());//实际费用
        model.addAttribute("payMoney",tOrder.getPayMoney());//实际支付费用
        model.addAttribute("discountedPrice",tOrder.getDiscountedPrice());//优惠券抵扣费用
        model.addAttribute("payType",tOrder.getPayType());//支付方式
        model.addAttribute("discountAmount",tOrder.getDiscountAmount());//折扣金额
        model.addAttribute("userId",tOrder.getUserId());//用户id
        model.addAttribute("routeRecord",tOrder.getRouteRecord());//行程录音
 
        // 查询用户
        TAppUser tAppUser = tAppUserMapper.selectById(tOrder.getUserId());
        if(null != tAppUser){
            model.addAttribute("userName",tAppUser.getNickname());
            model.addAttribute("userPhone",tAppUser.getPhone());
            model.addAttribute("havDiscount",tAppUser.getHavDiscount());
            if(1 == tAppUser.getHavDiscount()){
                // 计算9折优惠金额
                BigDecimal multiply = tOrder.getOrderMoney().multiply(new BigDecimal("0.1")).setScale(2);
                model.addAttribute("multiply",multiply);
            }
        }else{
            model.addAttribute("userName",tOrder.getUserName());
            model.addAttribute("userPhone",tOrder.getUserPhone());
            model.addAttribute("havDiscount", 0);
            model.addAttribute("multiply",0D);
        }
 
        // 查询司机
        TDriver tDriver = tDriverMapper.selectById(tOrder.getDriverId());
        if(Objects.nonNull(tDriver)){
            model.addAttribute("driverName",tDriver.getName());
            model.addAttribute("driverPhone",tDriver.getPhone());
            // 查询司机所属分公司
            TBranchOffice tBranchOffice = tBranchOfficeMapper.selectById(tDriver.getBranchOfficeId());
            if(Objects.nonNull(tBranchOffice)){
                model.addAttribute("branchOfficeName",tBranchOffice.getPrincipal());
            }else {
                model.addAttribute("branchOfficeName","");
            }
        }else {
            model.addAttribute("branchOfficeName","");
            model.addAttribute("driverName","");
            model.addAttribute("driverPhone","");
        }
 
    }
 
    @Override
    public void orderExceptionDetail(Integer orderId, Model model) {
        this.orderDetail(orderId,model);
        model.addAttribute("orderId",orderId);
    }
 
    @Override
    public void getDataStatisticsByYear(Integer agentId,String yearDate, Model model,Map<String, Object> map) {
 
        List<DataStatisticsOrderYearResp> data = tOrderMapper.getDataStatisticsByYear(agentId,yearDate);
        List<DataStatisticsOrderYearResp> resps =new ArrayList<>();
        for (int i = 1; i < 13; i++) {
            DataStatisticsOrderYearResp dataStatisticsOrderYearResp = new DataStatisticsOrderYearResp();
            if(i < 10){
                dataStatisticsOrderYearResp.setMonth("0" + i);
            }else {
                dataStatisticsOrderYearResp.setMonth(String.valueOf(i));
            }
            dataStatisticsOrderYearResp.setOrderCount(0);
            resps.add(dataStatisticsOrderYearResp);
        }
        if(!CollectionUtils.isEmpty(data)){
            for (DataStatisticsOrderYearResp datum : data) {
                for (DataStatisticsOrderYearResp resp : resps) {
                    if(resp.getMonth().equals(datum.getMonth())){
                        resp.setOrderCount(datum.getOrderCount());
                        break;
                    }
                }
            }
        }
        model.addAttribute("yearResp",resps);
        map.put("yearResp",resps);
    }
 
    @Override
    public void getDataStatisticsOrderCount(Integer agentId, String monthDate, Model model,Map<String, Object> map) {
        List<PerformanceTableResp> list = tOrderMapper.getDataStatisticsOrderCount(agentId,monthDate);
        model.addAttribute("performanceResp",list);
        map.put("performanceResp",list);
    }
 
    @Override
    public void getDataStatisticsCount(Integer agentId, Model model) {
        Integer pendingOrderCount = tOrderMapper.getDataStatisticsCount(agentId, OrderStateEnum.PENDING_ORDER.getCode(), LocalDate.now());
        Integer finishCount = tOrderMapper.getDataStatisticsCount(agentId, OrderStateEnum.FINISH.getCode(),LocalDate.now());
        Integer cancelCount = tOrderMapper.getDataStatisticsCount(agentId, OrderStateEnum.CANCELED.getCode(),LocalDate.now());
 
        Integer serverCount = tOrderMapper.getDataStatisticsServerCount(agentId, LocalDate.now());
 
        model.addAttribute("pendingOrderCount",pendingOrderCount);
        model.addAttribute("finishCount",finishCount);
        model.addAttribute("cancelCount",cancelCount);
        model.addAttribute("serverCount",serverCount);
    }
 
    @Override
    public List<TOrderServerResp> getDataStatisticsServerList(Integer agentId) {
        return tOrderMapper.getDataStatisticsServerList(agentId,LocalDate.now());
    }
 
    @Override
    public List<TOrder> getDataStatisticsAllList(Integer agentId,Integer type) {
        return tOrderMapper.getDataStatisticsAllList(agentId,type,LocalDate.now());
    }
 
    @Override
    public void getDataStatisticsCountByIds(List<Integer> ids, Model model) {
        Integer pendingOrderCount = tOrderMapper.getDataStatisticsCountByIds(ids, 1, LocalDate.now());
        Integer finishCount = tOrderMapper.getDataStatisticsCountByIds(ids, 2,LocalDate.now());
        Integer cancelCount = tOrderMapper.getDataStatisticsCountByIds(ids, 3,LocalDate.now());
        Integer serverCount = tOrderMapper.getDataStatisticsServerCountByIds(ids, LocalDate.now());
 
        model.addAttribute("pendingOrderCount",pendingOrderCount);
        model.addAttribute("finishCount",finishCount);
        model.addAttribute("cancelCount",cancelCount);
        model.addAttribute("serverCount",serverCount);
    }
 
    @Override
    public List<TOrderServerResp> getDataStatisticsServerListByIds(List<Integer> ids) {
        return tOrderMapper.getDataStatisticsServerListByIds(ids,LocalDate.now());
    }
 
    @Override
    public List<TOrder> getDataStatisticsAllListByIds(List<Integer> ids,Integer type) {
        return tOrderMapper.getDataStatisticsAllListByIds(ids,type,LocalDate.now());
    }
 
    @Override
    public void getDataStatisticsCountGetMap(Integer agentId, HashMap<String, Object> map) {
        Integer pendingOrderCount = tOrderMapper.getDataStatisticsCount(agentId, OrderStateEnum.PENDING_ORDER.getCode(), LocalDate.now());
        Integer finishCount = tOrderMapper.getDataStatisticsCount(agentId, OrderStateEnum.FINISH.getCode(),LocalDate.now());
        Integer cancelCount = tOrderMapper.getDataStatisticsCount(agentId, OrderStateEnum.CANCELED.getCode(),LocalDate.now());
 
        Integer serverCount = tOrderMapper.getDataStatisticsServerCount(agentId, LocalDate.now());
 
        map.put("pendingOrderCount",pendingOrderCount);
        map.put("finishCount",finishCount);
        map.put("cancelCount",cancelCount);
        map.put("serverCount",serverCount);
    }
 
    @Override
    public void getDataStatisticsCountByIdsGetMap(List<Integer> ids, HashMap<String, Object> map) {
        Integer pendingOrderCount = tOrderMapper.getDataStatisticsCountByIds(ids, 1, LocalDate.now());
        Integer finishCount = tOrderMapper.getDataStatisticsCountByIds(ids, 2,LocalDate.now());
        Integer cancelCount = tOrderMapper.getDataStatisticsCountByIds(ids, 3,LocalDate.now());
        Integer serverCount = tOrderMapper.getDataStatisticsServerCountByIds(ids, LocalDate.now());
 
        map.put("pendingOrderCount",pendingOrderCount);
        map.put("finishCount",finishCount);
        map.put("cancelCount",cancelCount);
        map.put("serverCount",serverCount);
    }
 
    @Override
    public void getDataStatisticsByYearByIds(List<Integer> ids, String yearDate, Model model, Map<String, Object> map) {
 
        List<DataStatisticsOrderYearResp> data = tOrderMapper.getDataStatisticsByYearByIds(ids,yearDate);
        List<DataStatisticsOrderYearResp> resps =new ArrayList<>();
        for (int i = 1; i < 13; i++) {
            DataStatisticsOrderYearResp dataStatisticsOrderYearResp = new DataStatisticsOrderYearResp();
            if(i < 10){
                dataStatisticsOrderYearResp.setMonth("0" + i);
            }else {
                dataStatisticsOrderYearResp.setMonth(String.valueOf(i));
            }
            dataStatisticsOrderYearResp.setOrderCount(0);
            resps.add(dataStatisticsOrderYearResp);
        }
        if(!CollectionUtils.isEmpty(data)){
            for (DataStatisticsOrderYearResp datum : data) {
                for (DataStatisticsOrderYearResp resp : resps) {
                    if(resp.getMonth().equals(datum.getMonth())){
                        resp.setOrderCount(datum.getOrderCount());
                        break;
                    }
                }
            }
        }
        model.addAttribute("yearResp",resps);
        map.put("yearResp",resps);
    }
 
    @Override
    public void getDataStatisticsOrderCountByIds(List<Integer> ids, String monthDate, Model model, Map<String, Object> map) {
        List<PerformanceTableResp> list = tOrderMapper.getDataStatisticsOrderCountByIds(ids,monthDate);
        model.addAttribute("performanceResp",list);
        map.put("performanceResp",list);
    }
 
    @Override
    public void getStatisticsOrderByMonth(Integer agentId, String dayDate, Model model, Map<String, Object> map) {
        List<DataStatisticsOrderYearResp> data = tOrderMapper.getStatisticsOrderByMonth(agentId,dayDate);
        List<DataStatisticsOrderYearResp> resps =new ArrayList<>();
        int month = DateUtil.getDaysOfMonth(new Date());
        for (int i = 1; i <= month; i++) {
            DataStatisticsOrderYearResp dataStatisticsOrderYearResp = new DataStatisticsOrderYearResp();
            if(i < 10){
                dataStatisticsOrderYearResp.setMonth("0" + i);
            }else {
                dataStatisticsOrderYearResp.setMonth(String.valueOf(i));
            }
            dataStatisticsOrderYearResp.setOrderCount(0);
            resps.add(dataStatisticsOrderYearResp);
        }
        if(!CollectionUtils.isEmpty(data)){
            for (DataStatisticsOrderYearResp datum : data) {
                for (DataStatisticsOrderYearResp resp : resps) {
                    if(resp.getMonth().equals(datum.getMonth())){
                        resp.setOrderCount(datum.getOrderCount());
                        break;
                    }
                }
            }
        }
        model.addAttribute("monthResp",resps);
        map.put("monthResp",resps);
    }
 
    @Override
    public void getStatisticsOrderByMonthIds(List<Integer> ids, String dayDate, Model model, Map<String, Object> map) {
        List<DataStatisticsOrderYearResp> data = tOrderMapper.getStatisticsOrderByMonthIds(ids,dayDate);
        List<DataStatisticsOrderYearResp> resps =new ArrayList<>();
        int month = DateUtil.getDaysOfMonth(new Date());
        for (int i = 1; i <= month; i++) {
            DataStatisticsOrderYearResp dataStatisticsOrderYearResp = new DataStatisticsOrderYearResp();
            if(i < 10){
                dataStatisticsOrderYearResp.setMonth("0" + i);
            }else {
                dataStatisticsOrderYearResp.setMonth(String.valueOf(i));
            }
            dataStatisticsOrderYearResp.setOrderCount(0);
            resps.add(dataStatisticsOrderYearResp);
        }
        if(!CollectionUtils.isEmpty(data)){
            for (DataStatisticsOrderYearResp datum : data) {
                for (DataStatisticsOrderYearResp resp : resps) {
                    if(resp.getMonth().equals(datum.getMonth())){
                        resp.setOrderCount(datum.getOrderCount());
                        break;
                    }
                }
            }
        }
        model.addAttribute("monthResp",resps);
        map.put("monthResp",resps);
    }
 
 
    @Override
    public Integer getValidOrderCount(Integer driverId, BigDecimal orderMoney, String month) {
        // 查询司机当月有效订单数量
        return tOrderMapper.getValidOrderCount(driverId,orderMoney,month);
    }
 
 
    @Override
    public ResultUtil add(TOrder tOrder) {
        String startAddress = tOrder.getStartAddress();
        String endAddress = tOrder.getEndAddress();
        String userPhone = tOrder.getUserPhone();
        int count = this.selectCount(new EntityWrapper<TOrder>().eq("userPhone", userPhone).eq("status", 1).in("state", Arrays.asList(101, 102, 103, 104, 105, 106, 201)));
        if(count > 0){
            return ResultUtil.error("该用户还有未完成的订单", "");
        }
        TAppUser tAppUser = appUserService.selectOne(new EntityWrapper<TAppUser>().eq("phone", userPhone).eq("status", 1));
        if(null != tAppUser){
            tOrder.setUserId(tAppUser.getId());
        }
        JSONObject jsonObject = JSON.parseObject(startAddress);
        String address = jsonObject.getString("address");
        address = address.replaceAll("& #40;", "(");
        address = address.replaceAll("& #41;", ")");
        tOrder.setStartAddress(address);
        tOrder.setStartLat(jsonObject.getString("lat"));
        tOrder.setStartLng(jsonObject.getString("lon"));
        tOrder.setSource(3);
        if(ToolUtil.isNotEmpty(endAddress)){
            jsonObject = JSON.parseObject(endAddress);
            String address1 = jsonObject.getString("address");
            address1 = address1.replaceAll("& #40;", "(");
            address1 = address1.replaceAll("& #41;", ")");
            tOrder.setEndAddress(address1);
            tOrder.setEndLat(jsonObject.getString("lat"));
            tOrder.setEndLng(jsonObject.getString("lon"));
        }
        if(ToolUtil.isEmpty(tOrder.getStartLng()) || ToolUtil.isEmpty(tOrder.getStartLat())){
            return ResultUtil.error("请输入有效的起点");
        }
 
        tOrder.setCode(UUIDUtil.getTimeStr() + UUIDUtil.getNumberRandom(3));
        Double d = 0D;
        if(ToolUtil.isNotEmpty(endAddress)){
            if(ToolUtil.isEmpty(tOrder.getEndLng()) || ToolUtil.isEmpty(tOrder.getEndLat())){
                return ResultUtil.error("请输入有效的终点");
            }
            Map<String, String> distance = MapUtil.getDistance(tOrder.getStartLng() + "," + tOrder.getStartLat(), tOrder.getEndLng() + "," + tOrder.getEndLat(), 1);
            if(null == distance){
                return ResultUtil.error("获取预估距离出错", "");
            }
            d = Double.valueOf(distance.get("distance")) / 1000;
            tOrder.setEstimatedMileage(d);
            tOrder.setEstimatedTime(Integer.valueOf(distance.get("duration")) / 60);
        }
        String city = "";
        District geocode = MapUtil.geocode(tOrder.getStartLng(), tOrder.getStartLat());
        if(null != geocode){
            WeatherCity weatherCity = weatherCityService.selectOne(new EntityWrapper<WeatherCity>()
                    .where("'" + geocode.getCity() + "' like CONCAT('%', city, '%') and '" + geocode.getDistrict() + "' like CONCAT('%', district, '%') "));
            city = null != weatherCity ? weatherCity.getId().toString() : "";
        }
        tOrder.setCreateTime(new Date());
        tOrder = getOrderPrice(1, d, 0, tOrder, city);
        tOrder.setState(101);
        tOrder.setStatus(1);
        this.insert(tOrder);
        //推送状态
        pushOrder(tOrder);
        return ResultUtil.success();
    }
 
 
 
    /**
     * 获取订单价格
     * @param type          计算类型(1=预估价,2=订单费)
     * @param distance      行驶公里
     * @param waitTime      等待时长
     * @param order         订单数据
     * @param city          查询天气的城市
     * @return
     */
    public TOrder getOrderPrice(Integer type, Double distance, Integer waitTime, TOrder order, String city){
        order = getOrderInitialPrice(order);
        TSystemConfig systemConfig = systemConfigService.selectOne(new EntityWrapper<TSystemConfig>().eq("type", 5));
        if(null == systemConfig){
            if(type == 1){//预估金额
                order.setEstimatedPrice(new BigDecimal(0));
            }
            if(type == 2){//订单金额
                order.setOrderMoney(new BigDecimal(0));
            }
            return order;
        }
        JSONObject jsonObject = JSON.parseObject(systemConfig.getContent());
        JSONArray chargeStandard = jsonObject.getJSONArray("ChargeStandard");
        JSONObject extraCost = jsonObject.getJSONObject("ExtraCost");
        Date date = order.getCreateTime();
 
        boolean b = true;
        for (int i = 1; i < chargeStandard.size(); i++) {//各种时间段
            JSONObject jsonObject1 = chargeStandard.getJSONObject(i);
            String num1 = jsonObject1.getString("num1");
            String num2 = jsonObject1.getString("num2");
            JSONArray num3 = jsonObject1.getJSONArray("num3");//起步里程
            Double num4 = jsonObject1.getDouble("num4");//长途里程
            Double num5 = jsonObject1.getDouble("num5");//长途里程
            Double num6 = jsonObject1.getDouble("num6");//长途费
            Double num7 = jsonObject1.getDouble("num7");//超出长途里程每num10公里
            Double num8 = jsonObject1.getDouble("num8");//超过num8每num10公里收取num11
 
            String[] split = num1.split(":");
            Integer hour1 = Integer.valueOf(split[0]);
            Calendar s = Calendar.getInstance();
            s.setTime(date);
            s.set(Calendar.HOUR_OF_DAY, hour1);
            s.set(Calendar.MINUTE, Integer.valueOf(split[1]));
            s.set(Calendar.SECOND, 0);
 
            split = num2.split(":");
            Integer hour2 = Integer.valueOf(split[0]);
            Calendar e = Calendar.getInstance();
            e.setTime(date);
            e.set(Calendar.HOUR_OF_DAY, hour2);
            e.set(Calendar.MINUTE, Integer.valueOf(split[1]));
            e.set(Calendar.SECOND, 0);
 
            if(hour1 > hour2){
                if(s.getTimeInMillis() > date.getTime()){
                    s.set(Calendar.DAY_OF_YEAR, s.get(Calendar.DAY_OF_YEAR) - 1);
                }else{
                    e.set(Calendar.DAY_OF_YEAR, e.get(Calendar.DAY_OF_YEAR) + 1);
                }
            }
 
            if(date.getTime() >= s.getTimeInMillis() && date.getTime() < e.getTimeInMillis()){
                b = false;
                Double dd = 0d;
                for (int j = 0; j < num3.size(); j++) {
                    JSONObject jsonObject2 = num3.getJSONObject(j);
                    Double num1_1 = jsonObject2.getDouble("num1");
                    Double num2_1 = jsonObject2.getDouble("num2");
                    Double num3_1 = jsonObject2.getDouble("num3");
                    if(num1_1.compareTo(distance) <= 0 && num2_1.compareTo(distance) > 0){
                        order.setStartDistance(distance);//起步里程
                        order.setStartPrice(new BigDecimal(num3_1));//起步价
                    }
                    if(j == num3.size() - 1 && order.getStartPrice().doubleValue() == 0){
                        order.setStartDistance(num2_1);//起步里程
                        order.setStartPrice(new BigDecimal(num3_1));//起步价
                        dd = distance - num2_1;
                    }
                }
                if(dd != 0){
                    //计算长途费
                    if(distance.compareTo(num4) > 0){
                        order.setLongDistance(num4 + "-" + num5);//长途里程
                        order.setLongDistancePrice(new BigDecimal(num6));//长途费
                    }
                    //计算长途里程超出的部分
                    if(distance.compareTo(num5) > 0){
                        BigDecimal subtract1 = new BigDecimal(distance).subtract(new BigDecimal(num5));
                        BigDecimal divide1 = subtract1.divide(new BigDecimal(num7), new MathContext(2, RoundingMode.HALF_EVEN));
                        BigDecimal multiply1 = divide1.multiply(new BigDecimal(num8));
                        order.setOverLongDistance(subtract1.doubleValue());//超出长途里程
                        order.setOverLongDistancePrice(multiply1);//超出长途里程费
                    }
                }
                break;
            }
        }
 
        if(b){//默认配置
            JSONObject jsonObject1 = chargeStandard.getJSONObject(0);
            JSONArray num3 = jsonObject1.getJSONArray("num3");//起步里程
            Double num4 = jsonObject1.getDouble("num4");//长途里程
            Double num5 = jsonObject1.getDouble("num5");//长途里程
            Double num6 = jsonObject1.getDouble("num6");//长途费
            Double num7 = jsonObject1.getDouble("num7");//超出长途里程每num10公里
            Double num8 = jsonObject1.getDouble("num8");//超过num8每num10公里收取num11
 
            Double dd = 0d;
            for (int j = 0; j < num3.size(); j++) {
                JSONObject jsonObject2 = num3.getJSONObject(j);
                Double num1_1 = jsonObject2.getDouble("num1");
                Double num2_1 = jsonObject2.getDouble("num2");
                Double num3_1 = jsonObject2.getDouble("num3");
                if(num1_1.compareTo(distance) <= 0 && num2_1.compareTo(distance) > 0){
                    order.setStartDistance(distance);//起步里程
                    order.setStartPrice(new BigDecimal(num3_1));//起步价
                }
                if(j == num3.size() - 1 && order.getStartPrice().doubleValue() == 0){
                    order.setStartDistance(num2_1);//起步里程
                    order.setStartPrice(new BigDecimal(num3_1));//起步价
                    dd = distance - num2_1;
                }
            }
            if(dd != 0){
                //计算长途费
                if(distance.compareTo(num4) > 0){
                    order.setLongDistance(num4 + "-" + num5);//长途里程
                    order.setLongDistancePrice(new BigDecimal(num6));//长途费
                }
                //计算长途里程超出的部分
                if(distance.compareTo(num5) > 0){
                    BigDecimal subtract1 = new BigDecimal(distance).subtract(new BigDecimal(num5));
                    BigDecimal divide1 = subtract1.divide(new BigDecimal(num7), new MathContext(2, RoundingMode.HALF_EVEN));
                    BigDecimal multiply1 = divide1.multiply(new BigDecimal(num8));
                    order.setOverLongDistance(subtract1.doubleValue());//超出长途里程
                    order.setOverLongDistancePrice(multiply1);//超出长途里程费
                }
            }
        }
 
        //计算额外费用
        Integer num1 = extraCost.getInteger("num1");//等待时长
        Double num2 = extraCost.getDouble("num2");//等待费
        Integer num3 = extraCost.getInteger("num3");//等待超出时长
        Double num4 = extraCost.getDouble("num4");//等到超出时长费用单价 X/分钟
        Double num5 = extraCost.getDouble("num5");//恶劣天气公里
        Double num6 = extraCost.getDouble("num6");//恶劣天气费
        Double num7 = extraCost.getDouble("num7");//恶劣天气超出公里
        Double num8 = extraCost.getDouble("num8");//恶劣天气超出公里单价 X/公里
        Double num9 = extraCost.getDouble("num9");//恶劣天气最高收取金额
 
        //等待费用
        if(waitTime.compareTo(num1) >= 0){
            order.setWaitTime(num1);//等待时长
            order.setWaitTimePrice(new BigDecimal(num2));//等待费用
 
            Integer w = waitTime - num3;
            BigDecimal multiply = new BigDecimal(w).multiply(new BigDecimal(num4));
            order.setOutWaitTime(w);//等待时长超出分钟
            order.setOutWaitTimePrice(multiply);//等待时长超出费用
        }
 
        //恶劣天气
        systemConfig = systemConfigService.selectOne(new EntityWrapper<TSystemConfig>().eq("type", 8));
        if(null != systemConfig){
            JSONObject jsonObject1 = JSON.parseObject(systemConfig.getContent());
            Integer num11 = jsonObject1.getInteger("num1");//开启恶劣天气计价
            if(1 == num11){
                boolean badWeather = WeatherUtil.isBadWeather(city);
                if(badWeather){
                    order.setBadWeatherDistance(new BigDecimal(num5));//恶劣天气公里
                    order.setBadWeatherPrice(new BigDecimal(num6));//恶劣天气费
                    if(distance.compareTo(num7) > 0){
                        BigDecimal subtract = new BigDecimal(distance).subtract(new BigDecimal(num7));
                        BigDecimal multiply = subtract.multiply(new BigDecimal(num8));
                        order.setOverBadWeatherDistance(subtract.doubleValue());//恶劣天气超出公里
                        order.setOverBadWeatherPrice(multiply);//恶劣天气超出公里费
                    }
 
                    double add = order.getOverBadWeatherPrice().add(order.getBadWeatherPrice()).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue();
                    if(num9.compareTo(add) < 0){//超出最高金额(重新调整金额)
                        if(num9.compareTo(num6) < 0){//如果恶劣天气费大于最高金额
                            order.setBadWeatherPrice(new BigDecimal(num9));//恶劣天气费
                            order.setOverBadWeatherPrice(new BigDecimal(0));//恶劣天气超出公里费
                        }else{
                            BigDecimal subtract = new BigDecimal(num9).subtract(new BigDecimal(add));
                            order.setOverBadWeatherPrice(subtract);//恶劣天气超出公里费
                        }
                    }
                }
            }
        }
 
 
        //计算总金额
        BigDecimal bigDecimal = order.getStartPrice().add(order.getOverDrivePrice()).add(order.getLongDistancePrice()).add(order.getOverLongDistancePrice())
                .add(order.getWaitTimePrice()).add(order.getOutWaitTimePrice()).add(order.getBadWeatherPrice()).add(order.getOverBadWeatherPrice()).subtract(order.getDiscountAmount()).setScale(2, BigDecimal.ROUND_HALF_EVEN);
 
        if(type == 1){//预估价
            order.setEstimatedPrice(bigDecimal);
        }
        if(type == 2){//订单金额
            order.setOrderMoney(bigDecimal);
        }
        return order;
    }
 
 
    /**
     * 初始订单费用
     * @param order
     * @return
     */
    public TOrder getOrderInitialPrice(TOrder order){
        order.setStartDistance(0D);//起步里程
        order.setStartPrice(new BigDecimal(0));//起步价
        order.setOverDriveDistance(0D);//超出起步里程
        order.setOverDrivePrice(new BigDecimal(0));//超出起步里程费
        order.setLongDistance("");//长途里程
        order.setLongDistancePrice(new BigDecimal(0));//长途里程费
        order.setOverLongDistance(0D);//超出长途里程
        order.setOverLongDistancePrice(new BigDecimal(0));//超出长途里程费
        order.setWaitTime(0);//等待时长
        order.setWaitTimePrice(new BigDecimal(0));//等待费
        order.setOutWaitTime(0);//超出等待时长
        order.setOutWaitTimePrice(new BigDecimal(0));//超出等待时长费
        order.setBadWeatherDistance(new BigDecimal(0));//恶劣天气里程
        order.setBadWeatherPrice(new BigDecimal(0));//恶劣天气里程费
        order.setOverBadWeatherDistance(0D);//恶劣天气超出里程
        order.setOverBadWeatherPrice(new BigDecimal(0));//恶劣天气超出里程费
        order.setDiscountedPrice(new BigDecimal(0));//优惠金额
        order.setCouponId(null);//优惠券
        order.setDiscountAmount(new BigDecimal(0));//折扣优惠金额
        order.setDiscount(0D);//折扣
        return order;
    }
 
 
 
 
    /**
     * 订单推送逻辑
     * @param order
     */
    public void pushOrder(TOrder order){
        /**
         * 1.先找最大推单范围内的优推司机 -》 距离最近
         * 没有1 - 》
         *      2.按照后台推送配置在范围内查找合适司机
         *        合适司:积分 > 评分 > 距离
         *      3.司机没有接单直接将订单置入大厅
         */
        TSystemConfig systemConfig = systemConfigService.selectOne(new EntityWrapper<TSystemConfig>().eq("type", 1));
        if(null == systemConfig){
            return;
        }
        JSONObject jsonObject = JSON.parseObject(systemConfig.getContent());
        Double num3 = jsonObject.getDouble("num3");//推单最大范围
        Integer num4 = jsonObject.getInteger("num4");//接单时间
        String startLat = order.getStartLat();
        String startLng = order.getStartLng();
 
        //1
        //找到中心点
        GeoJsonPoint geoJsonPoint = new GeoJsonPoint(Double.valueOf(startLng), Double.valueOf(startLat));
        Double num = num3 / 1000;//范围公里
        //构造半径
        Distance distanceR = new Distance(num, Metrics.KILOMETERS);
        //画圆
        Circle circle = new Circle(geoJsonPoint, distanceR);
        // 构造query对象
        Query query = Query.query(Criteria.where("location").withinSphere(circle));
        List<Location> locations = mongoTemplate.find(query, Location.class);
        List<Integer> driverIds = locations.stream().map(Location::getDriverId).collect(Collectors.toList());
        Integer driver = null;
        TYouTuiDriver youTuiDriver1 = null;
        if(driverIds.size() > 0){
            List<TYouTuiDriver> youTuiDrivers = youTuiDriverService.selectList(new EntityWrapper<TYouTuiDriver>().in("driverId", driverIds)
                    .eq("state", 2).last(" and (surplusQuantity > 0 or now() < endTime) and now() < failureTime"));
            Double d = null;
            for (TYouTuiDriver youTuiDriver : youTuiDrivers) {
                String value = redisUtil.getValue("DRIVER" + youTuiDriver.getDriverId());
                if(ToolUtil.isEmpty(value)){
                    continue;
                }
                TDriver driver1 = driverService.selectById(youTuiDriver.getDriverId());
                if(driver1.getServerStatus() == 2 || driver1.getOpenOrderQRCode() == 1){
                    continue;
                }
                TDriverWork driverWork = driverWorkService.selectOne(new EntityWrapper<TDriverWork>().eq("driverId", driver1.getId()).eq("status", 1));
                if(null == driverWork){
                    continue;
                }
                Map<String, Double> distance = GeodesyUtil.getDistance(value, order.getStartLng() + "," + order.getStartLat());
                Double wgs84 = distance.get("WGS84");
                if(d == null || d.compareTo(wgs84) > 0){
                    d = wgs84;
                    driver = youTuiDriver.getDriverId();
                    youTuiDriver1 = youTuiDriver;
                }
            }
        }
 
        if(null != youTuiDriver1 && youTuiDriver1.getType() == 1){
            youTuiDriver1.setSurplusQuantity(youTuiDriver1.getSurplusQuantity() - 1);
            youTuiDriverService.updateById(youTuiDriver1);
        }
 
        //开始范围查找
        if(null == driver){
            for (int i = 1; i < 4; i++) {
                if(null != driver){
                    break;
                }
                num = jsonObject.getDouble("num" + i) / 1000;//范围公里
                //构造半径
                distanceR = new Distance(num, Metrics.KILOMETERS);
                //画圆
                circle = new Circle(geoJsonPoint, distanceR);
                // 构造query对象
                query = Query.query(Criteria.where("location").withinSphere(circle));
                locations = mongoTemplate.find(query, Location.class);
 
                driverIds = locations.stream().map(Location::getDriverId).collect(Collectors.toList());
                if(driverIds.size() > 0){
                    List<TDriver> drivers = driverService.selectList(new EntityWrapper<TDriver>().eq("approvalStatus", 2)
                            .eq("serverStatus", 1).eq("openOrderQRCode", 0).eq("status", 1).in("id", driverIds));
                    if(drivers.size() == 0){
                        continue;
                    }
 
                    Integer integral = null;
                    Double score = null;
                    Double d = null;
                    for (TDriver driver1 : drivers) {
                        String value = redisUtil.getValue("DRIVER" + driver1.getId());
                        if(ToolUtil.isEmpty(value)){
                            continue;
                        }
                        TDriverWork driverWork = driverWorkService.selectOne(new EntityWrapper<TDriverWork>().eq("driverId", driver1.getId()).eq("status", 1));
                        if(null == driverWork){
                            continue;
                        }
 
                        if(integral == null || integral.compareTo(driver1.getIntegral()) < 0){//积分大
                            integral = driver1.getIntegral();
                            score = driver1.getScore();
                            driver = driver1.getId();
                            Map<String, Double> distance = GeodesyUtil.getDistance(value, order.getStartLng() + "," + order.getStartLat());
                            Double wgs84 = distance.get("WGS84");
                            d = wgs84;
                            continue;
                        }
                        if(integral.compareTo(driver1.getIntegral()) == 0 && score.compareTo(driver1.getScore()) < 0){//积分相同对比评分
                            integral = driver1.getIntegral();
                            score = driver1.getScore();
                            driver = driver1.getId();
                            Map<String, Double> distance = GeodesyUtil.getDistance(value, order.getStartLng() + "," + order.getStartLat());
                            Double wgs84 = distance.get("WGS84");
                            d = wgs84;
                            continue;
                        }
                        if(integral.compareTo(driver1.getIntegral()) == 0 && score.compareTo(driver1.getScore()) == 0){//积分相同/评分相同对比距离
                            Map<String, Double> distance = GeodesyUtil.getDistance(value, order.getStartLng() + "," + order.getStartLat());
                            Double wgs84 = distance.get("WGS84");
                            if(d.compareTo(wgs84) > 0){
                                d = wgs84;
                                integral = driver1.getIntegral();
                                score = driver1.getScore();
                                driver = driver1.getId();
                                continue;
                            }
                        }
                    }
 
                }
            }
        }
 
        if(null != driver){
            pushUtil.pushGrabOrder(driver, 2, order.getId(), num4);
            //创建定时任务处理订单到大厅
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    TOrder order1 = TOrderServiceImpl.this.selectById(order.getId());
                    if(order1.getState() == 101 || order1.getState() == 201){
                        order1.setHallOrder(1);
                        TOrderServiceImpl.this.updateById(order1);
 
                        ExtraPushOrder(order1);
                    }
                }
            }, num4 * 1000);
        }else{
            order.setHallOrder(1);
            this.updateById(order);
            ExtraPushOrder(order);
        }
    }
 
    public void ExtraPushOrder(TOrder order){
        String startLat = order.getStartLat();
        String startLng = order.getStartLng();
 
        //找到中心点
        GeoJsonPoint geoJsonPoint = new GeoJsonPoint(Double.valueOf(startLng), Double.valueOf(startLat));
        Double num = 5D;//范围公里
        //构造半径
        Distance distanceR = new Distance(num, Metrics.KILOMETERS);
        //画圆
        Circle circle = new Circle(geoJsonPoint, distanceR);
        // 构造query对象
        Query query = Query.query(Criteria.where("location").withinSphere(circle));
        List<Location> locations = mongoTemplate.find(query, Location.class);
        List<Integer> driverIds = locations.stream().map(Location::getDriverId).collect(Collectors.toList());
        if(driverIds.size() == 0){
            return;
        }
        List<TDriverWork> tDriverWorks = driverWorkService.selectList(new EntityWrapper<TDriverWork>().in("driverId", driverIds).eq("status", 1));
        driverIds = tDriverWorks.stream().map(TDriverWork::getDriverId).collect(Collectors.toList());
        List<TDriver> drivers = tDriverMapper.selectList(new EntityWrapper<TDriver>().eq("approvalStatus", 2)
                .eq("serverStatus", 1).eq("openOrderQRCode", 0).eq("status", 1).in("id", driverIds));
        if(drivers.size() == 0){
            return;
        }
        for (TDriver driver1 : drivers) {
            String value = redisUtil.getValue("DRIVER" + driver1.getId());
            if (ToolUtil.isEmpty(value)) {
                return;
            }
            pushUtil.pushGrabOrderExtras(driver1.getId(), 2);
        }
    }
 
}