longz
2026-06-25 d0eb18d339f5baccae5a17719ea2df9607ea5c95
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
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.crossCity.dao.*;
import com.stylefeng.guns.modular.crossCity.model.DriverSelfTrip;
import com.stylefeng.guns.modular.crossCity.model.LineShift;
import com.stylefeng.guns.modular.crossCity.model.LineShiftDriver;
import com.stylefeng.guns.modular.crossCity.model.OrderCrossCity;
import com.stylefeng.guns.modular.crossCity.server.ILineService;
import com.stylefeng.guns.modular.crossCity.server.ILineShiftDriverService;
import com.stylefeng.guns.modular.crossCity.server.IOrderCrossCityService;
import com.stylefeng.guns.modular.crossCity.warpper.*;
import com.stylefeng.guns.modular.system.dao.CarModelMapper;
import com.stylefeng.guns.modular.system.dao.CarServiceMapper;
import com.stylefeng.guns.modular.system.dao.OrderEvaluateMapper;
import com.stylefeng.guns.modular.system.model.Car;
import com.stylefeng.guns.modular.system.model.CarModel;
import com.stylefeng.guns.modular.system.model.CarService;
import com.stylefeng.guns.modular.system.model.Driver;
import com.stylefeng.guns.modular.system.service.ICarService;
import com.stylefeng.guns.modular.system.service.IDriverService;
import com.stylefeng.guns.modular.system.service.IReassignService;
import com.stylefeng.guns.modular.system.util.DateUtil;
import com.stylefeng.guns.modular.system.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
 
 
@Service
public class LineShiftDriverServiceImpl extends ServiceImpl<LineShiftDriverMapper, LineShiftDriver> implements ILineShiftDriverService {
 
    @Resource
    private LineShiftDriverMapper lineShiftDriverMapper;
 
    @Autowired
    private DateUtil dateUtil;
 
    @Autowired
    private ICarService carService;
 
    @Autowired
    private IDriverService driverService;
 
    @Resource
    private CarModelMapper carModelMapper;
 
    @Resource
    private LineShiftMapper lineShiftMapper;
 
    @Resource
    private CarServiceMapper carServiceMapper;
 
    @Resource
    private DriverSelfTripMapper driverSelfTripMapper;
 
    @Resource
    private OrderEvaluateMapper orderEvaluateMapper;
 
    @Autowired
    private IOrderCrossCityService orderCrossCityService;
 
    @Autowired
    private ILineService lineService;
    @Autowired
    private IReassignService reassignService;
    private LineMapper lineMapper;
 
 
    /**
     * 预约班次操作
     * @param lineShiftId
     * @param time
     * @param driverId
     * @return
     * @throws Exception
     */
    @Override
    public synchronized ResultUtil reservation(Integer type, Integer lineShiftId, String time, Integer driverId) throws Exception {
        Map<String, Date> date = dateUtil.getStartAndEndDate(time);
        List<LineShiftDriver> startTime = lineShiftDriverMapper.queryByDriver(lineShiftId, driverId, date.get("startTime"));
        if(type == 1 && startTime.size() > 0){
            return ResultUtil.error("不能重复预约");
        }
        if(type == 2 && startTime.size() == 0){
            return ResultUtil.error("您还没预约呢");
        }
        if(type == 1){//预约操作
            int completedCount = lineShiftDriverMapper.countCompletedShiftOrders(driverId, lineShiftId, date.get("startTime"));
            if (completedCount > 0) {
                return ResultUtil.error("该班次已完成,不能重复领取");
            }
            boolean b = this.judgeTime(driverId, lineShiftId, date.get("startTime"));
            if(b){
                return ResultUtil.error("预约间隔超出给定可预约范围");
            }
            int num = lineShiftDriverMapper.queryByDriver(lineShiftId, null, date.get("startTime")).size();
            LineShift lineShift = lineShiftMapper.selectById(lineShiftId);
            Integer carNum = lineShift.getCarNum();
            if(num >= carNum){
                return ResultUtil.error("该班次已经超出了可预约车次");
            }
            CarService query = carServiceMapper.query(3, driverService.selectById(driverId).getCarId());
            if(null == query){
                return ResultUtil.error("车辆未开通该服务");
            }
            List<Map<String, Object>> destinations = lineMapper.queryLineDestinations(lineShift.getLineId());
            if(destinations == null || destinations.size() == 0){
                return ResultUtil.error("该线路还未设置目的地价格,请联系管理员!");
            }
            CarModel carModel = carModelMapper.selectById(carService.selectById(driverService.selectById(driverId).getCarId()).getCarModelId());
            LineShiftDriver lineShiftDriver = new LineShiftDriver();
            lineShiftDriver.setLineShiftId(lineShiftId);
            lineShiftDriver.setDriverId(driverId);
            lineShiftDriver.setDay(date.get("startTime"));
            lineShiftDriver.setLaveSeat(carModel.getSeat() - 1);
            String seatNumber = "";
            for(int i = 1; i < carModel.getSeat(); i++){
                seatNumber += i + ",";
            }
            lineShiftDriver.setLaveSeatNumber(seatNumber.substring(0, seatNumber.length() - 1));
            lineShiftDriver.setTotalSeat(carModel.getSeat() - 1);
            lineShiftDriver.setInserTime(new Date());
            lineShiftDriver.setAssignType(1);
            lineShiftDriverMapper.insert(lineShiftDriver);
        }
        if(type == 2){//取消预约
            Integer id = startTime.get(0).getId();
            int i = orderCrossCityService.selectCount(
                    new EntityWrapper<OrderCrossCity>()
                            .eq("driverId", driverId)
                            .eq("lineShiftDriverId", id)
                            .eq("isDelete", 1)
                            .in("state", Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9, 11))
            );
            if(i > 0){
                return ResultUtil.error("班次已使用,不允许取消");
            }
 
            lineShiftDriverMapper.deleteById(id);
        }
        return ResultUtil.success();
    }
 
 
 
    /**
     * 判断当前预约的班次时间与之前已经预约的班次时间的间隔是否大于设定的间隔时间
     * @param driverId
     * @param shiftId
     * @param day
     * @return
     */
    public boolean judgeTime(Integer driverId, Integer shiftId, Date day) throws Exception{
        //获取当前预约班次的开始时间
        LineShift lineShift = lineShiftMapper.selectById(shiftId);
        String startTime = lineShift.getStartTime();//需要预约的班次开始时间
        String endTime1 = lineShift.getEndTime();//需要预约的班次结束时间
 
        List<Integer> list = new ArrayList<>();//存储给定天的预约的班次
        List<LineShiftDriver> lineShiftDrivers = lineShiftDriverMapper.queryByDriver(null, driverId, day);
        for(LineShiftDriver lineShiftDriver : lineShiftDrivers){
            list.add(lineShiftDriver.getLineShiftId());
        }
 
        if(list.size() == 0){
            return false;
        }
 
        List<LineShift> lineShifts_ = lineShiftMapper.selectList(new EntityWrapper<LineShift>().eq("lineId", lineShift.getLineId()).eq("state", 1).orderBy("endTime"));
        int index = 0;//需要预约的数据下标
        for(int i = 0; i < lineShifts_.size(); i++){
            if(startTime.equals(lineShifts_.get(i).getStartTime()) && endTime1.equals(lineShifts_.get(i).getEndTime())){
                index = i;
                break;
            }
        }
 
        //找出预约数据最近的预约了的数据
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
        Integer shiftInterval = lineService.selectById(lineShift.getLineId()).getShiftInterval();//获取可预约的间隔(分钟)
        long time = simpleDateFormat.parse("1999-01-01 " + startTime + ":00").getTime();//当前预约的班次的开始时间
        long time1 = simpleDateFormat.parse("1999-01-01 " + endTime1 + ":00").getTime();//当前预约的班次的结束时间
        if(index == 0 && lineShifts_.size() > 1){
            for(LineShift lineShift1 : lineShifts_){
                if(list.contains(lineShift1.getId())){
                    long s = simpleDateFormat.parse("1999-01-01 " + lineShift1.getStartTime() + ":00").getTime();
                    long e = simpleDateFormat.parse("1999-01-01 " + lineShift1.getEndTime() + ":00").getTime();
                    if((s - time1) < (Long.valueOf(shiftInterval) * 60 * 1000)){
                        return true;
                    }
                }
            }
            return false;
        }
        if(index == lineShifts_.size() - 1 && lineShifts_.size() > 1){
            for(LineShift lineShift1 : lineShifts_){
                if(list.contains(lineShift1.getId())){
                    long s = simpleDateFormat.parse("1999-01-01 " + lineShift1.getStartTime() + ":00").getTime();
                    long e = simpleDateFormat.parse("1999-01-01 " + lineShift1.getEndTime() + ":00").getTime();
                    if((time - e) < (Long.valueOf(shiftInterval) * 60 * 1000)){
                        return true;
                    }
                }
            }
            return false;
        }
        if(index > 0 && index < lineShifts_.size() - 1 && lineShifts_.size() > 2){
            for(int i = index + 1; i < lineShifts_.size(); i++){
                if(list.contains(lineShifts_.get(i).getId())){
                    long s = simpleDateFormat.parse("1999-01-01 " + lineShifts_.get(i).getStartTime() + ":00").getTime();
                    long e = simpleDateFormat.parse("1999-01-01 " + lineShifts_.get(i).getEndTime() + ":00").getTime();
                    if((s - time1) < (Long.valueOf(shiftInterval) * 60 * 1000)){
                        return true;
                    }
                }
            }
            for(int i = 0; i < index; i++){
                if(list.contains(lineShifts_.get(i).getId())){
                    long s = simpleDateFormat.parse("1999-01-01 " + lineShifts_.get(i).getStartTime() + ":00").getTime();
                    long e = simpleDateFormat.parse("1999-01-01 " + lineShifts_.get(i).getEndTime() + ":00").getTime();
                    if((time - e) < (Long.valueOf(shiftInterval) * 60 * 1000)){
                        return true;
                    }
                }
            }
            return false;
        }
        return false;
    }
 
    /**
     * 【202601】查询司机排班列表
     * @param driverId 司机id
     * @param date 日期(yyyy-MM-dd),为空则默认当天
     * @return
     * @throws Exception
     */
    @Override
    public DriverShiftListWarpper queryDriverShiftList(Integer driverId, String date) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 
        // 如果日期为空,默认当天
        if (ToolUtil.isEmpty(date)) {
            date = sdf.format(new Date());
        }
 
        DriverShiftListWarpper result = new DriverShiftListWarpper();
 
        // 获取司机的服务车型ID(跨城业务 type=3)
        Integer serverCarModelId = null;
        Integer carId = driverService.selectById(driverId).getCarId();
        if (carId != null) {
            CarService carServiceQuery = carServiceMapper.query(3, carId);
            if (carServiceQuery != null) {
                serverCarModelId = carServiceQuery.getServerCarModelId();
            }
        }
 
        // 查询司机可预约的班次列表(包括已预约和未预约的)
        List<Map<String, Object>> shiftList = lineShiftDriverMapper.queryDriverAvailableShifts(driverId, date);
 
        // 按线路分组
        Map<Integer, List<Map<String, Object>>> lineGroupMap = new LinkedHashMap<>();
        Map<Integer, String> lineNameMap = new HashMap<>();
 
        for (Map<String, Object> shift : shiftList) {
            Integer lineId = Integer.valueOf(shift.get("lineId").toString());
            String lineName = shift.get("lineName").toString();
            lineNameMap.put(lineId, lineName);
 
            if (!lineGroupMap.containsKey(lineId)) {
                lineGroupMap.put(lineId, new ArrayList<>());
            }
            lineGroupMap.get(lineId).add(shift);
        }
 
        // 构建线路列表
        List<DriverShiftListWarpper.LineItemWarpper> lineList = new ArrayList<>();
        Date now = new Date();
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        String currentTime = timeFormat.format(now);
        String today = sdf.format(now);
        CarModel carModel = carModelMapper.selectById(serverCarModelId);
 
        for (Map.Entry<Integer, List<Map<String, Object>>> entry : lineGroupMap.entrySet()) {
            DriverShiftListWarpper.LineItemWarpper lineItem = new DriverShiftListWarpper.LineItemWarpper();
            lineItem.setLineId(entry.getKey());
            lineItem.setLineName(lineNameMap.get(entry.getKey()));
 
            lineItem.setUnitPrice(queryDefaultDestinationPrice(entry.getKey(), carModel == null ? null : carModel.getSeat()));
 
            List<LineShiftItemWarpper> shifts = new ArrayList<>();
            for (Map<String, Object> shiftMap : entry.getValue()) {
                LineShiftItemWarpper shiftItem = new LineShiftItemWarpper();
                shiftItem.setLineShiftId(Integer.valueOf(shiftMap.get("lineShiftId").toString()));
                shiftItem.setStartTime(shiftMap.get("startTime").toString());
                shiftItem.setEndTime(shiftMap.get("endTime").toString());
 
                // 判断是否已预约
                Integer isReserved = Integer.valueOf(shiftMap.get("isReserved").toString());
 
                if (isReserved == 1) {
                    // 已预约的班次
                    shiftItem.setLineShiftDriverId(Integer.valueOf(shiftMap.get("lineShiftDriverId").toString()));
                    shiftItem.setLaveSeat(Integer.valueOf(shiftMap.get("laveSeat").toString()));
                    shiftItem.setTotalSeat(Integer.valueOf(shiftMap.get("totalSeat").toString()));
 
                    // 判断是否过期
                    String endTime = shiftMap.get("endTime").toString();
                    boolean isExpired = false;
 
                    // 如果是今天,比较时间;如果是过去的日期,则已过期
                    if (date.equals(today)) {
                        // 比较当前时间和班次结束时间
                        isExpired = currentTime.compareTo(endTime) >= 0;
                    } else if (date.compareTo(today) < 0) {
                        // 过去的日期
                        isExpired = true;
                    }
 
                    if (isExpired) {
                        // 已过期
                        shiftItem.setStatus(2);
                        shiftItem.setStatusText("已过期");
                        shiftItem.setCanOperate(false);
                    } else {
                        // 已预约可操作
                        shiftItem.setStatus(1);
                        shiftItem.setStatusText("已预约");
                        shiftItem.setCanOperate(true);
                    }
                } else {
                    // 未预约的班次
                    shiftItem.setLineShiftDriverId(null);
                    shiftItem.setLaveSeat(null);
                    shiftItem.setTotalSeat(null);
 
                    // 判断是否可预约(未过期)
                    String endTime = shiftMap.get("endTime").toString();
                    boolean isExpired = false;
 
                    // 如果是今天,比较时间;如果是过去的日期,则已过期
                    if (date.equals(today)) {
                        // 比较当前时间和班次结束时间
                        isExpired = currentTime.compareTo(endTime) >= 0;
                    } else if (date.compareTo(today) < 0) {
                        // 过去的日期
                        isExpired = true;
                    }
 
                    if (isExpired) {
                        // 已过期,不可预约
                        shiftItem.setStatus(2);
                        shiftItem.setStatusText("已过期");
                        shiftItem.setCanOperate(false);
                    } else {
                        // 可预约
                        shiftItem.setStatus(3);
                        shiftItem.setStatusText("可预约");
                        shiftItem.setCanOperate(false);
                    }
                }
 
                shifts.add(shiftItem);
            }
            lineItem.setShifts(shifts);
            lineList.add(lineItem);
        }
 
        result.setLineList(lineList);
        return result;
    }
 
    /**
     * 【202604】查询司机本人已领取/被分配的排班列表(今天及之后)
     */
    @Override
    public List<LineShiftItemWarpper> queryMyDriverShiftList(Integer driverId, String date, Integer pageNum, Integer size) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
 
        String today = sdf.format(new Date());
        String startDate = ToolUtil.isEmpty(date) ? null : date;
        int safePageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        int safeSize = (size == null || size < 1) ? 10 : size;
        int offset = (safePageNum - 1) * safeSize;
 
        List<Map<String, Object>> rows = lineShiftDriverMapper.queryMyDriverShiftList(driverId, startDate, offset, safeSize);
        List<LineShiftItemWarpper> result = new ArrayList<>();
        String currentTime = timeFormat.format(new Date());
 
        for (Map<String, Object> row : rows) {
            LineShiftItemWarpper item = new LineShiftItemWarpper();
            item.setLineShiftId(row.get("lineShiftId") == null ? null : Integer.valueOf(row.get("lineShiftId").toString()));
            item.setLineShiftDriverId(row.get("lineShiftDriverId") == null ? null : Integer.valueOf(row.get("lineShiftDriverId").toString()));
            item.setStartTime(row.get("startTime") == null ? "" : row.get("startTime").toString());
            item.setEndTime(row.get("endTime") == null ? "" : row.get("endTime").toString());
            item.setDay(row.get("day") == null ? "" : row.get("day").toString());
            item.setLaveSeat(row.get("laveSeat") == null ? 0 : Integer.valueOf(row.get("laveSeat").toString()));
            item.setTotalSeat(row.get("totalSeat") == null ? 0 : Integer.valueOf(row.get("totalSeat").toString()));
            item.setLineName(row.get("lineName") == null ? "" : row.get("lineName").toString());
            item.setAssignType(row.get("assignType") == null ? 1 : Integer.valueOf(row.get("assignType").toString()));
            item.setOrderId(row.get("orderId") == null ? null : Integer.valueOf(row.get("orderId").toString()));
            item.setOrderType(row.get("orderType") == null ? null : Integer.valueOf(row.get("orderType").toString()));
 
            String dayStr = row.get("day") == null ? today : row.get("day").toString();
            boolean isExpired = dayStr.equals(today) && currentTime.compareTo(item.getEndTime()) >= 0;
            if (isExpired) {
                item.setStatus(2);
                item.setStatusText("已过期");
                item.setCanOperate(false);
            } else {
                item.setStatus(1);
                item.setStatusText("已预约");
                item.setCanOperate(true);
            }
            result.add(item);
        }
 
        return result;
    }
 
    @Override
    public List<OtherDriverShiftWarpper> queryOtherDriverShiftListWithShiftId(Long driverShiftId, String orderIds) throws Exception {
        if (driverShiftId == null) {
            return new ArrayList<>();
        }
        LineShiftDriver current = lineShiftDriverMapper.selectById(driverShiftId);
        if (current == null || (current.getLineShiftId() != null && current.getLineShiftId() == -1)) {
            return new ArrayList<>();
        }
 
        // 如果提供了订单ID,使用新的改派逻辑(包含needConfirm字段)
        if (ToolUtil.isNotEmpty(orderIds)) {
            try {
                // 使用第一个订单ID来查询(改派场景通常是单个订单,多个订单取第一个)
                String firstOrderId = orderIds.split(",")[0].trim();
                List<Map<String, Object>> drivers = reassignService.queryDriver(firstOrderId);
                return OtherDriverShiftWarpper.fromMaps(drivers);
            } catch (Exception e) {
                e.printStackTrace();
                // 如果新逻辑失败,降级到旧逻辑
            }
        }
 
        // 旧逻辑:只查询同批次司机(兼容没有传orderIds的场景)
        List<Map<String, Object>> rows = lineShiftDriverMapper.queryOtherDriverShiftListWithShiftId(driverShiftId);
        // 旧逻辑默认都是同批次,不需要确认
        for (Map<String, Object> row : rows) {
            row.put("needConfirm", 1);
        }
        return OtherDriverShiftWarpper.fromMaps(rows);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultUtil<Map<String, Object>> addSelfTrip(Integer driverId, AddSelfTripWarpper warpper) throws Exception {
        if (driverId == null) {
            return ResultUtil.tokenErr();
        }
        if (warpper == null) {
            return ResultUtil.paranErr();
        }
        if (!isSelfTripEnabled(driverId)) {
            return ResultUtil.error("未开启自主行程");
        }
        if (ToolUtil.isEmpty(warpper.getDay()) || ToolUtil.isEmpty(warpper.getStartTime())
                || warpper.getSeat() == null
                || ToolUtil.isEmpty(warpper.getStartAddress())
                || warpper.getStartLon() == null
                || warpper.getStartLat() == null
                || ToolUtil.isEmpty(warpper.getDestJson())) {
            return ResultUtil.paranErr();
        }
 
        LocalDate day;
        try {
            day = LocalDate.parse(warpper.getDay(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        } catch (DateTimeParseException e) {
            return ResultUtil.error("出发日期格式错误");
        }
        LocalDate today = LocalDate.now();
        if (day.isBefore(today)) {
            return ResultUtil.error("日期不能早于今天");
        }
        if (day.isAfter(today.plusDays(6))) {
            return ResultUtil.error("只能新增7天内的自主行程");
        }
        if (!warpper.getStartTime().matches("^([01]\\d|2[0-3]):[0-5]\\d$")) {
            return ResultUtil.error("出发时间格式错误");
        }
 
        Integer carSeat = getCurrentCarSeat(driverId);
        if (carSeat == null || carSeat <= 0) {
            return ResultUtil.error("当前车辆车型座位数异常");
        }
        if (warpper.getSeat() < 1 || warpper.getSeat() > carSeat) {
            return ResultUtil.error("座位数超出当前车型可用范围");
        }
 
        String normalizedDestJson = validateAndNormalizeDestJson(warpper.getDestJson());
        if (normalizedDestJson == null) {
            return ResultUtil.error("目的地信息格式不正确");
        }
 
        DriverSelfTrip trip = new DriverSelfTrip();
        trip.setDriverId(driverId);
        trip.setDay(java.sql.Date.valueOf(day));
        trip.setStartTime(warpper.getStartTime());
        trip.setSeat(warpper.getSeat());
        trip.setStartCityCode(warpper.getStartCityCode());
        trip.setStartCityName(warpper.getStartCityName());
        trip.setEndCityCode(warpper.getEndCityCode());
        trip.setEndCityName(warpper.getEndCityName());
        trip.setStartAddress(warpper.getStartAddress());
        trip.setStartLon(warpper.getStartLon());
        trip.setStartLat(warpper.getStartLat());
        trip.setDestJson(normalizedDestJson);
        trip.setState(1);
        trip.setInsertTime(new Date());
        trip.setUpdateTime(new Date());
        driverSelfTripMapper.insert(trip);
 
        LineShiftDriver lineShiftDriver = new LineShiftDriver();
        lineShiftDriver.setLineShiftId(-1);
        lineShiftDriver.setCustomerId(trip.getId());
        lineShiftDriver.setDriverId(driverId);
        lineShiftDriver.setDay(java.sql.Date.valueOf(day));
        lineShiftDriver.setLaveSeat(warpper.getSeat());
        lineShiftDriver.setTotalSeat(warpper.getSeat());
        lineShiftDriver.setLaveSeatNumber(buildSeatNumber(warpper.getSeat()));
        lineShiftDriver.setInserTime(new Date());
        lineShiftDriver.setAssignType(1);
        lineShiftDriverMapper.insert(lineShiftDriver);
 
        Map<String, Object> result = new HashMap<>(2);
        result.put("lineShiftDriverId", lineShiftDriver.getId());
        result.put("customerId", trip.getId());
        return ResultUtil.success(result);
    }
 
    private boolean isSelfTripEnabled(Integer driverId) throws Exception {
        Map<String, Object> info = driverService.queryInfo(driverId);
        Object value = info == null ? null : info.get("isOpenDriverSelfTrip");
        return value != null && "1".equals(String.valueOf(value));
    }
 
    private Integer getCurrentCarSeat(Integer driverId) {
        Driver driver = driverService.selectById(driverId);
        if (driver == null || driver.getCarId() == null) {
            return null;
        }
        Car car = carService.selectById(driver.getCarId());
        if (car == null || car.getCarModelId() == null) {
            return null;
        }
        CarModel carModel = carModelMapper.selectById(car.getCarModelId());
        return carModel == null ? null : carModel.getSeat();
    }
 
    private String validateAndNormalizeDestJson(String destJson) {
        try {
            JSONArray array = JSON.parseArray(destJson);
            if (array == null || array.isEmpty()) {
                return null;
            }
            for (int i = 0; i < array.size(); i++) {
                JSONObject item = array.getJSONObject(i);
                if (item == null) {
                    return null;
                }
                String endAddress = item.getString("endAddress");
                Double endLon = item.getDouble("endLon");
                Double endLat = item.getDouble("endLat");
                Double price = item.getDouble("price");
                if (ToolUtil.isEmpty(endAddress)
                        || endLon == null
                        || endLat == null
                        || price == null
                        || price < 0) {
                    return null;
                }
            }
            return array.toJSONString();
        } catch (Exception e) {
            return null;
        }
    }
 
    private String buildSeatNumber(Integer seat) {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= seat; i++) {
            if (i > 1) {
                sb.append(",");
            }
            sb.append(i);
        }
        return sb.toString();
    }
 
    @Override
    public ResultUtil<ScanOrderDetailWarpper> getDetail(Integer lineShiftDriverId) {
        LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(lineShiftDriverId);
        if (lineShiftDriver == null) {
            return ResultUtil.error("班次信息不存在");
        }
        if (lineShiftDriver.getLineShiftId() != null && lineShiftDriver.getLineShiftId() <= -1) {
            return buildSelfTripDetail(lineShiftDriver);
        }
 
        // 1. 查询基础数据
        Map<String, Object> data = lineShiftDriverMapper.getDetail(lineShiftDriverId);
        if (data == null || data.isEmpty()) {
            return ResultUtil.error("班次信息不存在");
        }
 
        // 2. 构建返回对象
        ScanOrderDetailWarpper result = new ScanOrderDetailWarpper();
 
        // 司机信息
        result.setHeadImgUrl(data.get("headImgUrl") != null ? data.get("headImgUrl").toString() : null);
        result.setDriverName(data.get("driverName") != null ? data.get("driverName").toString() : null);
        result.setSex(data.get("sex") != null ? Integer.parseInt(data.get("sex").toString()) : null);
        result.setCarLicensePlate(data.get("carLicensePlate") != null ? data.get("carLicensePlate").toString() : null);
        result.setCarBrand(data.get("carBrand") != null ? data.get("carBrand").toString() : null);
        result.setCarColor(data.get("carColor") != null ? data.get("carColor").toString() : null);
        result.setScore(data.get("score") != null ? Double.parseDouble(data.get("score").toString()) : 0.0);
        result.setOrderCount(data.get("orderCount") != null ? Integer.parseInt(data.get("orderCount").toString()) : 0);
 
        // 线路信息
        result.setLineId(data.get("lineId") != null ? Integer.parseInt(data.get("lineId").toString()) : null);
        result.setLineName(data.get("lineName") != null ? data.get("lineName").toString() : null);
        result.setDay(data.get("day") != null ? data.get("day").toString() : null);
        result.setStartTime(data.get("startTime") != null ? data.get("startTime").toString() : null);
        result.setEndTime(data.get("endTime") != null ? data.get("endTime").toString() : null);
        result.setTotalSeat(data.get("totalSeat") != null ? Integer.parseInt(data.get("totalSeat").toString()) : null);
        result.setTotalSeatImage(getTotalSeatImage(result.getTotalSeat()));
        result.setLaveSeat(data.get("laveSeat") != null ? Integer.parseInt(data.get("laveSeat").toString()) : null);
        result.setLaveSeatNumber(data.get("laveSeatNumber") != null ? data.get("laveSeatNumber").toString() : null);
 
        result.setUnitPrice(queryDefaultDestinationPrice(result.getLineId(), result.getTotalSeat()));
 
        // 站点信息
        result.setStartSiteId(data.get("startSiteId") != null ? Integer.parseInt(data.get("startSiteId").toString()) : null);
        result.setStartSiteName(data.get("startSiteName") != null ? data.get("startSiteName").toString() : null);
        result.setEndSiteId(data.get("endSiteId") != null ? Integer.parseInt(data.get("endSiteId").toString()) : null);
        result.setEndSiteName(data.get("endSiteName") != null ? data.get("endSiteName").toString() : null);
        // 城市信息
        result.setStartCityName(data.get("startCityName") != null ? data.get("startCityName").toString() : null);
        result.setEndCityName(data.get("endCityName") != null ? data.get("endCityName").toString() : null);
        // 经纬度信息
        result.setStartLonLat(data.get("startLonLat") != null ? data.get("startLonLat").toString() : null);
        result.setEndLonLat(data.get("endLonLat") != null ? data.get("endLonLat").toString() : null);        //
        // 默认点信息(起点和终点)
        // 起点默认点信息
        result.setStartDefaultPointAddress(data.get("startDefaultPointAddress") != null ? data.get("startDefaultPointAddress").toString() : null);
        result.setStartDefaultPointLon(data.get("startDefaultPointLon") != null ? Double.parseDouble(data.get("startDefaultPointLon").toString()) : null);
        result.setStartDefaultPointLat(data.get("startDefaultPointLat") != null ? Double.parseDouble(data.get("startDefaultPointLat").toString()) : null);
 
        // 终点默认点信息
        result.setEndDefaultPointAddress(data.get("endDefaultPointAddress") != null ? data.get("endDefaultPointAddress").toString() : null);
        result.setEndDefaultPointLon(data.get("endDefaultPointLon") != null ? Double.parseDouble(data.get("endDefaultPointLon").toString()) : null);
        result.setEndDefaultPointLat(data.get("endDefaultPointLat") != null ? Double.parseDouble(data.get("endDefaultPointLat").toString()) : null);
        // 其他信息
        result.setServerCarModelId(data.get("serverCarModelId") != null ? Integer.parseInt(data.get("serverCarModelId").toString()) : null);
        result.setDriverId(data.get("driverId") != null ? Integer.parseInt(data.get("driverId").toString()) : null);
        result.setLineShiftDriverId(lineShiftDriverId);
 
        return ResultUtil.success(result);
    }
 
    private ResultUtil<ScanOrderDetailWarpper> buildSelfTripDetail(LineShiftDriver lineShiftDriver) {
        if (lineShiftDriver.getCustomerId() == null) {
            return ResultUtil.error("自主行程信息不存在");
        }
        DriverSelfTrip trip = driverSelfTripMapper.selectById(lineShiftDriver.getCustomerId());
        if (trip == null || trip.getState() == null || trip.getState() != 1) {
            return ResultUtil.error("自主行程信息不存在");
        }
        Driver driver = driverService.selectById(lineShiftDriver.getDriverId());
        if (driver == null) {
            return ResultUtil.error("司机信息不存在");
        }
        Car car = null;
        CarModel carModel = null;
        CarService carServiceData = null;
        if (driver.getCarId() != null) {
            car = carService.selectById(driver.getCarId());
            if (car != null && car.getCarModelId() != null) {
                carModel = carModelMapper.selectById(car.getCarModelId());
            }
            carServiceData = carServiceMapper.query(3, driver.getCarId());
        }
 
        ScanOrderDetailWarpper result = new ScanOrderDetailWarpper();
        result.setHeadImgUrl(driver.getHeadImgUrl());
        String name = driver.getName();
        result.setDriverName(ToolUtil.isEmpty(name) ? "" : name.substring(0, 1) + "师傅");
        result.setSex(driver.getSex());
        result.setCarLicensePlate(car == null ? null : car.getCarLicensePlate());
        result.setCarBrand(carModel == null ? null : carModel.getName());
        result.setCarColor(car == null ? null : car.getCarColor());
        Double score = orderEvaluateMapper.queryCount(driver.getId());
        result.setScore(score == null ? 0D : score);
        int orderCount = orderCrossCityService.selectCount(
                new EntityWrapper<OrderCrossCity>()
                        .eq("driverId", driver.getId())
                        .eq("state", 9)
        );
        result.setOrderCount(orderCount);
 
        result.setLineId(-1);
        result.setLineName(trip.getStartCityName() + "-" + trip.getEndCityName());
        result.setUnitPrice(null);
        if (lineShiftDriver.getDay() != null) {
            result.setDay(new SimpleDateFormat("yyyy-MM-dd").format(lineShiftDriver.getDay()));
        }
        result.setStartTime(trip.getStartTime());
        result.setEndTime(trip.getStartTime());
        result.setTotalSeat(lineShiftDriver.getTotalSeat());
        result.setTotalSeatImage(getTotalSeatImage(result.getTotalSeat()));
        result.setLaveSeat(lineShiftDriver.getLaveSeat());
        result.setLaveSeatNumber(lineShiftDriver.getLaveSeatNumber());
 
        result.setStartSiteId(null);
        result.setStartSiteName(trip.getStartAddress());
        result.setEndSiteId(null);
        result.setEndSiteName(null);
        result.setStartCityName(trip.getStartCityName());
        result.setEndCityName(null);
        result.setStartLonLat(trip.getStartLon() == null || trip.getStartLat() == null ? null : trip.getStartLon() + "," + trip.getStartLat());
        result.setEndLonLat(null);
 
 
        if (ToolUtil.isNotEmpty(trip.getDestJson())) {
            try {
                JSONArray array = JSON.parseArray(trip.getDestJson());
                if (array != null && !array.isEmpty()) {
                    JSONObject first = array.getJSONObject(0);
                    if (first != null) {
                        result.setEndSiteName(first.getString("endAddress"));
                        result.setEndCityName(first.getString("endCityName"));
                        Double endLon = first.getDouble("endLon");
                        Double endLat = first.getDouble("endLat");
                        if (endLon != null && endLat != null) {
                            result.setEndLonLat(endLon + "," + endLat);
                        }
                        Double price = first.getDouble("price");
                        if (price != null) {
                            result.setUnitPrice(price);
                        }
                    }
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);
                        jsonObject.put("range",3000D);
                    }
                    result.setEndDetailList(array);
                }
            } catch (Exception ignored) {
            }
        }
 
        result.setOtherFee(null);
        result.setServerCarModelId(carServiceData == null ? null : carServiceData.getServerCarModelId());
        result.setDriverId(driver.getId());
        result.setLineShiftDriverId(lineShiftDriver.getId());
 
        result.setStartDefaultPointAddress(trip.getStartAddress());
        result.setStartDefaultPointLon(trip.getStartLon());
        result.setStartDefaultPointLat(trip.getStartLat());
        result.setEndDefaultPointAddress(result.getEndSiteName());
        if (ToolUtil.isNotEmpty(result.getEndLonLat()) && result.getEndLonLat().contains(",")) {
            String[] split = result.getEndLonLat().split(",");
            if (split.length == 2) {
                try {
                    result.setEndDefaultPointLon(Double.valueOf(split[0]));
                    result.setEndDefaultPointLat(Double.valueOf(split[1]));
                } catch (Exception ignored) {
                }
            }
        }
        return ResultUtil.success(result);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer autoCancelExpiredNoOrderShifts() throws Exception {
        List<Integer> shiftIds = lineShiftDriverMapper.queryExpiredNoOrderShiftIds();
        System.out.println("自动清除无效车程数量 " + 0);
        if (shiftIds == null || shiftIds.isEmpty()) {
            return 0;
        }
        int cancelCount = 0;
        for (Integer shiftId : shiftIds) {
            if (shiftId == null) {
                continue;
            }
            LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(shiftId);
            if (lineShiftDriver == null) {
                continue;
            }
            if (lineShiftDriver.getLineShiftId() != null
                    && lineShiftDriver.getLineShiftId() <= -1
                    && lineShiftDriver.getCustomerId() != null) {
                DriverSelfTrip trip = driverSelfTripMapper.selectById(lineShiftDriver.getCustomerId());
                if (trip != null && trip.getState() != null && trip.getState() == 1) {
                    trip.setState(2);
                    trip.setUpdateTime(new Date());
                    driverSelfTripMapper.updateById(trip);
                }
            }
            lineShiftDriverMapper.deleteById(shiftId);
            cancelCount++;
        }
        System.out.println("自动清除无效车程数量 " + cancelCount);
        return cancelCount;
    }
 
    private Double queryDefaultDestinationPrice(Integer lineId, Integer totalSeat) {
        List<Map<String, Object>> destinations = lineMapper.queryLineDestinations(lineId);
        if (destinations == null || destinations.size() == 0) {
            return 0.0D;
        }
        Map<String, Object> destination = destinations.get(0);
        BigDecimal price = totalSeat != null && totalSeat == 6
                ? getBigDecimal(destination.get("price7"))
                : getBigDecimal(destination.get("price5"));
        if (price == null) {
            price = getBigDecimal(destination.get("price5"));
        }
        return price == null ? 0.0D : price.doubleValue();
    }
 
    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 String getTotalSeatImage(Integer totalSeat) {
        if (totalSeat == null) {
            return null;
        }
        String fileName;
        if (totalSeat == 4) {
            fileName = "seat/seat_five.png";
        } else if (totalSeat == 5) {
            fileName = "seat/seat_six.png";
        } else if (totalSeat == 6) {
            fileName = "seat/seat_seven.png";
        } else {
            return null;
        }
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName)) {
            if (inputStream == null) {
                return null;
            }
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            return "data:image/png;base64," + Base64.getEncoder().encodeToString(outputStream.toByteArray());
        } catch (Exception e) {
            return null;
        }
    }
}