fix
longz
2026-04-30 83ff381c5c0e62c98cb9e3dd8e1d82771b1dc23f
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
package com.stylefeng.guns.modular.system.controller.specialTrain;
 
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.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.SinataUtil;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.*;
import com.stylefeng.guns.modular.system.dao.LineShiftDriverMapper;
import com.stylefeng.guns.modular.system.service.*;
import com.stylefeng.guns.modular.system.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
 
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;
 
/**
 * 跨城线路管理控制器
 *
 * @author fengshuonan
 * @Date 2020-09-15 16:17:29
 */
@Controller
@RequestMapping("/tLine")
public class TLineController extends BaseController {
 
    private String PREFIX = "/system/tLine/";
 
    @Autowired
    private ITLineService tLineService;
 
    @Autowired
    private ITSiteService itSiteService;
 
    @Autowired
    private ITServerCarmodelService itServerCarmodelService;
 
    @Autowired
    private ITLineSiteService itLineSiteService;
 
    @Autowired
    private ITLinePriceService itLinePriceService;
    
    @Autowired
    private ITLineShiftService itLineShiftService;
 
    @Autowired
    private ITLineDestinationService itLineDestinationService;
    
    @Autowired
    private ITCompanyService itCompanyService;
    
    @Autowired
    private ITLineCompanyService itLineCompanyService;
 
    @Autowired
    private LineShiftDriverMapper lineShiftDriverMapper;
 
    @Autowired
    private ITDriverService tDriverService;
    
    /**
     * 跳转到跨城站点管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "tLine.html";
    }
 
    /**
     * 跳转到行程列表页
     */
    @RequestMapping("/travelListPage")
    public String travelListPage() {
        return PREFIX + "travelList.html";
    }
 
    /**
     * 跳转到行程订单列表页
     */
    @RequestMapping("/travelOrdersPage")
    public String travelOrdersPage(Integer lineShiftDriverId, Integer lineId, Integer driverId, Model model) {
        model.addAttribute("lineShiftDriverId", lineShiftDriverId);
        model.addAttribute("lineId", lineId);
        model.addAttribute("driverId", driverId);
        return PREFIX + "travelOrders.html";
    }
    
    /**
     * 跳转到添加跨城站点管理
     */
    @RequestMapping("/tLine_add")
    public String tLineAdd(Model model) {
        //站点
        Integer companyId = null;
        if(ShiroKit.getUser().getRoleType() != 1){
            companyId = ShiroKit.getUser().getObjectId();
        }
        List<TSite> siteList = itSiteService.selectList(new EntityWrapper<TSite>().eq("state", 1)
                .eq(null != companyId, "companyId", companyId));
        model.addAttribute("siteList",siteList);
        //跨城车型
        List<TServerCarmodel> carmodelList = itServerCarmodelService.selectList(new EntityWrapper<TServerCarmodel>().eq("type", 2).eq("state", 1));
        model.addAttribute("carmodelList",carmodelList);
        return PREFIX + "tLine_add.html";
    }
 
    /**
     * 分配企业页面
     */
    @RequestMapping("/tLine_addCompany/{tLineId}")
    public String tLine_addCompany(@PathVariable Integer tLineId,Model model) {
        TLine tLine = tLineService.selectById(tLineId);
        model.addAttribute("tLine",tLine);
        //查询所有企业
        List<TCompany> companyList = itCompanyService.selectList(new EntityWrapper<TCompany>().last(" where not FIND_IN_SET(state,'1') and not FIND_IN_SET(flag,'3')"));
        model.addAttribute("companyList",companyList);
        //查询已分配企业
        List<Map<String, Object>> lineCompanyList = tLineService.getLineCompanyList(tLineId);
        model.addAttribute("lineCompanyList",lineCompanyList);
        return PREFIX + "tLine_addCompany.html";
    }
 
 
    @RequestMapping("/set/{redict}")
    public String set(Model model,@PathVariable String redict) {
            model.addAttribute("redict",redict);
        return PREFIX + "set.html";
    }
 
    @RequestMapping("/set1/{redict}")
    public String set1(Model model,@PathVariable String redict) {
        model.addAttribute("redict",redict);
        return PREFIX + "set1.html";
    }
    /**
     * 跳转到修改跨城站点管理
     */
    @RequestMapping("/tLine_update/{tLineId}")
    public String tLineUpdate(@PathVariable Integer tLineId, Model model) {
        TLine tLine = tLineService.selectById(tLineId);
        model.addAttribute("item",tLine);
        LogObjectHolder.me().set(tLine);
 
        //查找站点起点+终点
        TLineSite start = itLineSiteService.selectOne(new EntityWrapper<TLineSite>().eq("lineId", tLineId).eq("type", 1));
        model.addAttribute("start",start);
        TLineSite end = itLineSiteService.selectOne(new EntityWrapper<TLineSite>().eq("lineId", tLineId).eq("type", 2));
        model.addAttribute("end",end);
        //站点
        Integer companyId = null;
        if(ShiroKit.getUser().getRoleType() != 1){
            companyId = ShiroKit.getUser().getObjectId();
        }
        List<TSite> siteList = itSiteService.selectList(new EntityWrapper<TSite>().eq("state", 1)
                .eq(null != companyId, "companyId", companyId));
        model.addAttribute("siteList",siteList);
        //跨城车型
        List<TServerCarmodel> carmodelList = itServerCarmodelService.selectList(new EntityWrapper<TServerCarmodel>().eq("type", 2).eq("state", 1));
        model.addAttribute("carmodelList",carmodelList);
        //查询所有站点
        List<Map<String, Object>> linePriceList = tLineService.getLinePriceList(tLineId);
        model.addAttribute("linePriceList",linePriceList);
        //查询所有班次
        List<TLineShift> lineShiftList = itLineShiftService.selectList(new EntityWrapper<TLineShift>().eq("lineId", tLineId).last(" and not FIND_IN_SET(state,'3')"));
        model.addAttribute("lineShiftList",lineShiftList);
        //查询线路目的地
        List<TLineDestination> lineDestinationList = itLineDestinationService.selectList(
                new EntityWrapper<TLineDestination>().eq("lineId", tLineId).ne("state", 3).orderBy("isMain", false).orderBy("id", true));
        model.addAttribute("lineDestinationList", lineDestinationList);
        return PREFIX + "tLine_edit.html";
    }
 
    /**
     * 获取跨城站点管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String insertTime,String name,String insertUser,String modelStr,Integer state) {
        String beginTime = null;
        String endTime = null;
        if (SinataUtil.isNotEmpty(insertTime)) {
            String[] timeArray = insertTime.split(" - ");
            beginTime = timeArray[0];
            endTime = timeArray[1];
        }
        Page<Map<String, Object>> page = new PageFactory<Map<String, Object>>().defaultPage();
        Integer companyId = null;
        if(ShiroKit.getUser().getRoleType() != 1){
            companyId = ShiroKit.getUser().getObjectId();
        }
        page.setRecords(tLineService.getLineList(page, beginTime, endTime, name, insertUser, modelStr, state, companyId));
        return super.packForBT(page);
    }
 
    /**
     * 获取行程列表
     */
    @RequestMapping(value = "/travelList")
    @ResponseBody
    public Object travelList(String city, String lineName, String driverKeyword, Integer status) {
        Page<Map<String, Object>> page = new PageFactory<Map<String, Object>>().defaultPage();
        Integer roleType = ShiroKit.getUser().getRoleType();
        Integer companyId = ShiroKit.getUser().getObjectId();
        page.setRecords(tLineService.getTravelList(page, city, lineName, driverKeyword, status, roleType, companyId));
        return super.packForBT(page);
    }
 
    /**
     * 获取行程对应订单列表
     */
    @RequestMapping(value = "/travelOrders")
    @ResponseBody
    public Object travelOrders(Integer lineShiftDriverId, Integer lineId, Integer driverId) {
        Page<Map<String, Object>> page = new PageFactory<Map<String, Object>>().defaultPage();
        Integer roleType = ShiroKit.getUser().getRoleType();
        Integer companyId = ShiroKit.getUser().getObjectId();
        page.setRecords(tLineService.getTravelOrders(page, lineShiftDriverId, lineId, driverId, roleType, companyId));
        return super.packForBT(page);
    }
 
    /**
     * 新增跨城站点管理
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public ResultUtil add(TLine tLine,Integer startSiteId,Integer endSiteId,@RequestParam String subArr,
                          @RequestParam String shuArr, @RequestParam(required = false) String destArr) {
        JSONArray jsonArray1 = JSON.parseArray(shuArr);
        int size1 = jsonArray1.size();
        for (int i = 0; i < size1; i++) {
            JSONObject jsonObject = jsonArray1.getJSONObject(i);
            String shiftTime = jsonObject.getString("shiftTime");
            if (SinataUtil.isNotEmpty(shiftTime)){
                String[] timeArray = shiftTime.split(" - ");
                String startTime = timeArray[0].split(":")[0];
                String endTime = timeArray[1].split(":")[0];
                if(Integer.valueOf(startTime) >= Integer.valueOf(endTime)){
                    return ResultUtil.error("班次结束时间不能小于开始时间");
                }
            }
        }
        String name = tLine.getName();
        name = name.replaceAll("& lt;", "<");
        name = name.replaceAll("& gt;", ">");
        name = name.replaceAll("& #40;", "(");
        name = name.replaceAll("& #41;", ")");
        tLine.setName(name);
        tLine.setState(1);
        tLine.setInsertTime(new Date());
        tLine.setInsertUserId(ShiroKit.getUser().getId());
        tLine.setCompanyId(ShiroKit.getUser().getObjectId());
        tLineService.insert(tLine);
    
        //添加线路站点起点+终点
        TLineSite start = new TLineSite();
        start.setLineId(tLine.getId());
        start.setSiteId(startSiteId);
        start.setType(1);
        itLineSiteService.insert(start);
        TLineSite end = new TLineSite();
        end.setLineId(tLine.getId());
        end.setSiteId(endSiteId);
        end.setType(2);
        itLineSiteService.insert(end);
 
        //添加价格设置
        addPrice(tLine.getId(), subArr);
 
        //添加班次设置
        ResultUtil shiftResult = addShift(tLine.getId(), shuArr);
        if(200 != shiftResult.getStatus()){
            return shiftResult;
        }
        //添加目的地设置
        ResultUtil destinationResult = addDestination(tLine.getId(), destArr);
        if(200 != destinationResult.getStatus()){
            return destinationResult;
        }
        return ResultUtil.success();
    }
 
    /**
     * 添加线路班次
     * @param lineId
     * @param shuArr
     */
    private ResultUtil addShift(Integer lineId, @RequestParam String shuArr) {
        try {
            JSONArray jsonArray1 = JSON.parseArray(shuArr);
            int size1 = jsonArray1.size();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<String> list = new ArrayList<>();
            for (int i = 0; i < size1; i++) {
                List<TLineShift> tLineShifts = itLineShiftService.selectList(new EntityWrapper<TLineShift>().eq("lineId", lineId).ne("state", 3).orderBy("startTime"));
                JSONObject jsonObject = jsonArray1.getJSONObject(i);
                TLineShift shift = new TLineShift();
                shift.setLineId(lineId);
                String shiftTime = jsonObject.getString("shiftTime");
                String startTime = null;
                String endTime = null;
                if (SinataUtil.isNotEmpty(shiftTime)){
                    String[] timeArray = shiftTime.split(" - ");
                    startTime = timeArray[0];
                    endTime = timeArray[1];
                }
                Date s1 = sdf.parse("2020-11-11 " + startTime + ":00");
                Date e1 = sdf.parse("2020-11-11 " + endTime + ":00");
                if(s1.getTime() >= e1.getTime()){
                    return ResultUtil.error("【" + startTime + " - " + endTime + "】时间段无效,添加失败!");
                }
                boolean b = false;
                for(TLineShift lineShift : tLineShifts){
                    Date s2 = sdf.parse("2020-11-11 " + lineShift.getStartTime() + ":00");
                    Date e2 = sdf.parse("2020-11-11 " + lineShift.getEndTime() + ":00");
                    if(s2.getTime() < s1.getTime() && e1.getTime() < e2.getTime()){
                        list.add(startTime + " - " + endTime);
                        b = true;
                        break;
                    }
                    if(s1.getTime() < s2.getTime() && s1.getTime() < e2.getTime() && e1.getTime() > s2.getTime()){
                        list.add(startTime + " - " + endTime);
                        b = true;
                        break;
                    }
                    if(s1.getTime() > s2.getTime() && s1.getTime() < e2.getTime() && e1.getTime() > e2.getTime()){
                        list.add(startTime + " - " + endTime);
                        b = true;
                        break;
                    }
                }
                if(b){
                    continue;
                }
                shift.setStartTime(startTime);
                shift.setEndTime(endTime);
                shift.setCarNum(jsonObject.getInteger("carNum"));
                shift.setInsertTime(new Date());
                shift.setAddTime(jsonObject.getString("time2"));
                shift.setState(1);
                itLineShiftService.insert(shift);
            }
            if(list.size() > 0){
                return ResultUtil.error("【" + JSON.toJSONString(list) + "】时间段与现存时间段重合,添加失败!");
            }
            return ResultUtil.success();
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
    /**
     * 添加线路价格
     * @param lineId
     * @param subArr
     */
    private void addPrice(Integer lineId, @RequestParam String subArr) {
        JSONArray jsonArray = JSON.parseArray(subArr);
        int size = jsonArray.size();
        for (int i = 0; i < size; i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            TLinePrice price = new TLinePrice();
            price.setLineId(lineId);
            price.setServerCarModelId(jsonObject.getInteger("serverModelId"));
            price.setType(jsonObject.getInteger("type"));
            price.setContent(jsonObject.getString("content"));
            price.setContentStr(jsonObject.getString("contentStr"));
            price.setState(1);
            price.setInsertTime(new Date());
            price.setAddTime(jsonObject.getString("time"));
            itLinePriceService.insert(price);
        }
    }
 
    /**
     * 操作跨城站点管理
     * optType 1=删除 2=冻结 3=解冻
     */
    @RequestMapping(value = "/opt")
    @ResponseBody
    public Object opt(@RequestParam Integer tLineId,@RequestParam Integer optType) {
        TLine tLine = tLineService.selectById(tLineId);
        if (1 == optType){
            tLine.setState(3);
        }else if (2 == optType){
            tLine.setState(2);
        }else if (3 == optType){
            tLine.setState(1);
        }
        tLineService.updateById(tLine);
        return SUCCESS_TIP;
    }
 
    /**
     * 分配企业操作
     */
    @RequestMapping(value = "/addCompany")
    @ResponseBody
    public Object addCompany(Integer lineId,@RequestParam String comArr) {
        //删除分配企业
        itLineCompanyService.delete(new EntityWrapper<TLineCompany>().eq("lineId",lineId));
        //添加企业
        if (SinataUtil.isNotEmpty(comArr)){
            JSONArray jsonArray = JSON.parseArray(comArr);
            int size = jsonArray.size();
            for (int i = 0; i < size; i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                TLineCompany lineCompany = new TLineCompany();
                lineCompany.setLineId(lineId);
                lineCompany.setCompanyId(jsonObject.getInteger("companyId"));
                lineCompany.setInsertTime(new Date());
                lineCompany.setInsertUserId(ShiroKit.getUser().getId());
                lineCompany.setAutoPlan(2);
                itLineCompanyService.insert(lineCompany);
            }
        }
        return SUCCESS_TIP;
    }
 
    /**
     * 查询线路已分配企业
     */
    @RequestMapping(value = "/lineCompanyList")
    @ResponseBody
    public Object lineCompanyList(Integer lineId) {
        if (lineId == null) {
            return ResultUtil.error("线路ID不能为空");
        }
        return ResultUtil.success(tLineService.getLineCompanyList(lineId));
    }
 
    /**
     * 排班管理页面
     */
    @RequestMapping(value = "/schedulePage")
    public String schedulePage(Integer lineId, Integer companyId, Model model) {
        TLine line = tLineService.selectById(lineId);
        List<TLineCompany> lineCompanies = getLineCompanies(lineId);
        TLineCompany currentLineCompany = null;
        if (companyId != null) {
            currentLineCompany = checkLineCompany(lineId, companyId);
        }
        if (currentLineCompany == null && lineCompanies.size() > 0) {
            currentLineCompany = lineCompanies.get(0);
            companyId = currentLineCompany.getCompanyId();
        }
        model.addAttribute("lineId", lineId);
        model.addAttribute("companyId", companyId);
        model.addAttribute("lineName", line == null ? "" : line.getName());
        model.addAttribute("companyName", getLineCompanyNames(lineCompanies));
        model.addAttribute("autoPlan", currentLineCompany == null || currentLineCompany.getAutoPlan() == null ? 2 : currentLineCompany.getAutoPlan());
        return PREFIX + "tLine_schedule.html";
    }
 
    /**
     * 排班管理-月份数据
     */
    @RequestMapping(value = "/schedule/month")
    @ResponseBody
    public Object scheduleMonth(Integer lineId, Integer companyId, String month) {
        try {
            if (!hasLineCompanies(lineId)) {
                return ResultUtil.error("线路未关联企业");
            }
            if (SinataUtil.isEmpty(month)) {
                month = new SimpleDateFormat("yyyy-MM").format(new Date());
            }
            SimpleDateFormat monthSdf = new SimpleDateFormat("yyyy-MM");
            Date monthDate = monthSdf.parse(month);
            Calendar cal = Calendar.getInstance();
            cal.setTime(monthDate);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            String monthStart = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
            int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.DAY_OF_MONTH, maxDay);
            String monthEnd = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
 
            List<Map<String, Object>> stats = lineShiftDriverMapper.getMonthScheduleStats(lineId, monthStart, monthEnd, companyId, null);
            Map<String, Integer> dayAssignMap = new HashMap<>();
            for (Map<String, Object> stat : stats) {
                dayAssignMap.put(String.valueOf(stat.get("dayStr")), Integer.parseInt(String.valueOf(stat.get("assignNum"))));
            }
            List<TLineShift> shifts = itLineShiftService.selectList(new EntityWrapper<TLineShift>().eq("lineId", lineId).ne("state", 3));
            int totalNeed = 0;
            for (TLineShift shift : shifts) {
                totalNeed += (shift.getCarNum() == null ? 0 : shift.getCarNum());
            }
 
            List<Map<String, Object>> dayList = new ArrayList<>();
            cal.setTime(monthDate);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            for (int i = 1; i <= maxDay; i++) {
                cal.set(Calendar.DAY_OF_MONTH, i);
                String dayStr = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
                int assignNum = dayAssignMap.get(dayStr) == null ? 0 : dayAssignMap.get(dayStr);
                Map<String, Object> obj = new HashMap<>();
                obj.put("day", dayStr);
                obj.put("assignNum", assignNum);
                obj.put("totalNeed", totalNeed);
                if (totalNeed <= 0) {
                    obj.put("status", 0);
                    obj.put("statusText", "无班次");
                } else if (assignNum >= totalNeed) {
                    obj.put("status", 1);
                    obj.put("statusText", "已排班");
                } else {
                    obj.put("status", 2);
                    obj.put("statusText", "未排满");
                }
                dayList.add(obj);
            }
            Map<String, Object> result = new HashMap<>();
            result.put("month", month);
            result.put("totalNeed", totalNeed);
            result.put("days", dayList);
            return ResultUtil.success(result);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
    /**
     * 排班管理-某天班次详情
     */
    @RequestMapping(value = "/schedule/dayDetail")
    @ResponseBody
    public Object scheduleDayDetail(Integer lineId, Integer companyId, String day) {
        try {
            if (!hasLineCompanies(lineId)) {
                return ResultUtil.error("线路未关联企业");
            }
            List<Map<String, Object>> shiftList = lineShiftDriverMapper.getDayShiftSchedule(lineId, day, companyId, null);
            for (Map<String, Object> shift : shiftList) {
                Integer lineShiftId = Integer.valueOf(String.valueOf(shift.get("lineShiftId")));
                List<Map<String, Object>> drivers = lineShiftDriverMapper.getDayShiftDrivers(lineShiftId, day, companyId, null);
                int carNum = shift.get("carNum") == null ? 0 : Integer.parseInt(String.valueOf(shift.get("carNum")));
                int assignNum = shift.get("assignNum") == null ? 0 : Integer.parseInt(String.valueOf(shift.get("assignNum")));
                shift.put("drivers", drivers);
                shift.put("remainNum", Math.max(carNum - assignNum, 0));
                shift.put("canAdd", assignNum < carNum ? 1 : 0);
            }
            return ResultUtil.success(shiftList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
    /**
     * 排班管理-可添加司机
     */
    @RequestMapping(value = "/schedule/drivers")
    @ResponseBody
    public Object scheduleDrivers(Integer lineId, Integer companyId, Integer lineShiftId, String day) {
        try {
            if (!hasLineCompanies(lineId)) {
                return ResultUtil.error("线路未关联企业");
            }
            return ResultUtil.success(lineShiftDriverMapper.getAvailableDrivers(lineId, lineShiftId, day, companyId, null));
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
    /**
     * 排班管理-新增排班
     */
    @RequestMapping(value = "/schedule/add")
    @ResponseBody
    public Object scheduleAdd(Integer lineId, Integer companyId, Integer lineShiftId, String day, @RequestParam String driverIds) {
        try {
            if (!hasLineCompanies(lineId)) {
                return ResultUtil.error("线路未关联企业");
            }
            TLineShift shift = itLineShiftService.selectById(lineShiftId);
            if (shift == null || shift.getState() == 3 || !shift.getLineId().equals(lineId)) {
                return ResultUtil.error("班次不存在");
            }
            Date dayDate = parseDay(day);
            List<Map<String, Object>> currentDrivers = lineShiftDriverMapper.getDayShiftDrivers(lineShiftId, day, companyId, null);
            int currentAssignNum = currentDrivers == null ? 0 : currentDrivers.size();
            int carNum = shift.getCarNum() == null ? 0 : shift.getCarNum();
            if (currentAssignNum >= carNum) {
                return ResultUtil.error("当前班次已排满");
            }
 
            List<Integer> driverIdList = parseIdList(driverIds);
            if (driverIdList.size() <= 0) {
                return ResultUtil.error("请选择司机");
            }
            List<Map<String, Object>> availableDrivers = lineShiftDriverMapper.getAvailableDrivers(lineId, lineShiftId, day, companyId, null);
            Map<Integer, Integer> seatMap = new HashMap<>();
            for (Map<String, Object> driver : availableDrivers) {
                Integer driverId = Integer.valueOf(String.valueOf(driver.get("driverId")));
                Integer seatNum = driver.get("seatNum") == null ? 5 : Integer.valueOf(String.valueOf(driver.get("seatNum")));
                seatMap.put(driverId, seatNum);
            }
            List<Integer> validDriverIds = new ArrayList<>();
            for (Integer driverId : driverIdList) {
                if (seatMap.containsKey(driverId)) {
                    validDriverIds.add(driverId);
                }
            }
            if (validDriverIds.size() <= 0) {
                return ResultUtil.error("没有可添加的司机");
            }
            if (currentAssignNum + validDriverIds.size() > carNum) {
                return ResultUtil.error("可排班人数不足,当前班次最多还能添加" + (carNum - currentAssignNum) + "名司机");
            }
 
            for (Integer driverId : validDriverIds) {
                Integer count = lineShiftDriverMapper.countExistsSchedule(lineShiftId, driverId, day);
                if (count != null && count > 0) {
                    continue;
                }
                int seatNum = seatMap.get(driverId) == null ? 5 : seatMap.get(driverId);
                if (seatNum <= 0) {
                    seatNum = 5;
                }
                LineShiftDriver record = new LineShiftDriver();
                record.setLineShiftId(lineShiftId);
                record.setDriverId(driverId);
                record.setDay(dayDate);
                record.setTotalSeat(seatNum);
                record.setLaveSeat(seatNum);
                record.setLaveSeatNumber(buildSeatNoStr(seatNum));
                record.setInserTime(new Date());
                record.setAssignType(2);
                lineShiftDriverMapper.insert(record);
            }
            return ResultUtil.success();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
    /**
     * 排班管理-删除手动排班
     */
    @RequestMapping(value = "/schedule/delete")
    @ResponseBody
    public Object scheduleDelete(Integer scheduleId, Integer lineId, Integer companyId) {
        try {
            if (!hasLineCompanies(lineId)) {
                return ResultUtil.error("线路未关联企业");
            }
            LineShiftDriver record = lineShiftDriverMapper.selectById(scheduleId);
            if (record == null) {
                return ResultUtil.error("排班记录不存在");
            }
            if (record.getAssignType() == null || record.getAssignType() != 2) {
                return ResultUtil.error("仅支持删除手动排班记录");
            }
            TLineShift shift = itLineShiftService.selectById(record.getLineShiftId());
            if (shift == null || !shift.getLineId().equals(lineId)) {
                return ResultUtil.error("排班记录线路不匹配");
            }
            TDriver driver = tDriverService.selectById(record.getDriverId());
            if (driver == null || !checkDriverBelongLineCompanies(driver, lineId)) {
                return ResultUtil.error("司机企业信息不匹配");
            }
            lineShiftDriverMapper.deleteById(scheduleId);
            return ResultUtil.success();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
    /**
     * 排班管理-复制排班
     */
    @RequestMapping(value = "/schedule/copy")
    @ResponseBody
    public Object scheduleCopy(Integer lineId, Integer companyId, String sourceStart, String sourceEnd, String targetStart) {
        try {
            if (!hasLineCompanies(lineId)) {
                return ResultUtil.error("线路未关联企业");
            }
            Date sourceStartDate = parseDay(sourceStart);
            Date sourceEndDate = parseDay(sourceEnd);
            Date targetStartDate = parseDay(targetStart);
            if (sourceEndDate.before(sourceStartDate)) {
                return ResultUtil.error("复制结束日期不能早于开始日期");
            }
            List<LineShiftDriver> sourceList = lineShiftDriverMapper.getManualSchedulesForCopy(lineId, sourceStart, sourceEnd, companyId, null);
            int addNum = 0;
            int skipNum = 0;
            for (LineShiftDriver source : sourceList) {
                int diff = getDayDiff(sourceStartDate, source.getDay());
                Date targetDay = addDays(targetStartDate, diff);
                String targetDayStr = formatDay(targetDay);
                Integer count = lineShiftDriverMapper.countExistsSchedule(source.getLineShiftId(), source.getDriverId(), targetDayStr);
                if (count != null && count > 0) {
                    skipNum++;
                    continue;
                }
                LineShiftDriver target = new LineShiftDriver();
                target.setLineShiftId(source.getLineShiftId());
                target.setDriverId(source.getDriverId());
                target.setDay(targetDay);
                target.setLaveSeat(source.getLaveSeat());
                target.setLaveSeatNumber(source.getLaveSeatNumber());
                target.setTotalSeat(source.getTotalSeat());
                target.setInserTime(new Date());
                target.setAssignType(2);
                lineShiftDriverMapper.insert(target);
                addNum++;
            }
            Map<String, Object> result = new HashMap<>();
            result.put("addNum", addNum);
            result.put("skipNum", skipNum);
            return ResultUtil.success(result);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultUtil.runErr();
        }
    }
 
    /**
     * 排班管理-保存智能排班开关
     */
    @RequestMapping(value = "/schedule/autoPlan")
    @ResponseBody
    public Object scheduleAutoPlan(Integer lineId, Integer companyId, Integer autoPlan) {
        if (autoPlan == null || (autoPlan != 1 && autoPlan != 2)) {
            return ResultUtil.error("智能排班参数错误");
        }
        if (companyId == null) {
            companyId = getDefaultLineCompanyId(lineId);
        }
        TLineCompany lineCompany = checkLineCompany(lineId, companyId);
        if (lineCompany == null) {
            return ResultUtil.error("线路未关联该企业");
        }
        lineCompany.setAutoPlan(autoPlan);
        itLineCompanyService.updateById(lineCompany);
        return ResultUtil.success();
    }
    /**
     * 修改跨城站点管理
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public ResultUtil update(TLine tLine,Integer startSiteId,Integer endSiteId,@RequestParam String subArr,
                             @RequestParam String shuArr, @RequestParam(required = false) String destArr) {
        JSONArray jsonArray1 = JSON.parseArray(shuArr);
        int size1 = jsonArray1.size();
        for (int i = 0; i < size1; i++) {
            JSONObject jsonObject = jsonArray1.getJSONObject(i);
            String shiftTime = jsonObject.getString("shiftTime");
            if (SinataUtil.isNotEmpty(shiftTime)){
                String[] timeArray = shiftTime.split(" - ");
                String startTime = timeArray[0].split(":")[0];
                String endTime = timeArray[1].split(":")[0];
                if(Integer.valueOf(startTime) >= Integer.valueOf(endTime)){
                    return ResultUtil.error("班次结束时间不能小于开始时间");
                }
            }
        }
        String name = tLine.getName();
        name = name.replaceAll("& lt;", "<");
        name = name.replaceAll("& gt;", ">");
        name = name.replaceAll("& #40;", "(");
        name = name.replaceAll("& #41;", ")");
        tLine.setName(name);
        tLineService.updateById(tLine);
 
        //修改站点起点
        TLineSite start = itLineSiteService.selectOne(new EntityWrapper<TLineSite>().eq("lineId", tLine.getId()).eq("type", 1));
        if (SinataUtil.isNotEmpty(start)){
            if (start.getSiteId().intValue() != startSiteId.intValue()){
                start.setSiteId(startSiteId);
                itLineSiteService.updateById(start);
            }
        }else{
            start = new TLineSite();
            start.setLineId(tLine.getId());
            start.setSiteId(startSiteId);
            start.setType(1);
            itLineSiteService.insert(start);
        }
        //修改站点终点
        TLineSite end = itLineSiteService.selectOne(new EntityWrapper<TLineSite>().eq("lineId", tLine.getId()).eq("type", 2));
        if (SinataUtil.isNotEmpty(end)){
            if (end.getSiteId().intValue() != endSiteId.intValue()){
                end.setSiteId(endSiteId);
                itLineSiteService.updateById(end);
            }
        }else{
            end = new TLineSite();
            end.setLineId(tLine.getId());
            end.setSiteId(endSiteId);
            end.setType(2);
            itLineSiteService.insert(end);
        }
 
        //删除线路价格
        itLinePriceService.delete(new EntityWrapper<TLinePrice>().eq("lineId",tLine.getId()));
        //添加价格设置
        addPrice(tLine.getId(), subArr);
        //删除线路班次
        itLineShiftService.delete(new EntityWrapper<TLineShift>().eq("lineId",tLine.getId()));
        //添加班次设置
        ResultUtil shiftResult = addShift(tLine.getId(), shuArr);
        if(200 != shiftResult.getStatus()){
            return shiftResult;
        }
        //删除线路目的地并重建
        itLineDestinationService.delete(new EntityWrapper<TLineDestination>().eq("lineId", tLine.getId()));
        ResultUtil destinationResult = addDestination(tLine.getId(), destArr);
        if(200 != destinationResult.getStatus()){
            return destinationResult;
        }
        return ResultUtil.success();
 
    }
 
    /**
     * 添加线路目的地配置
     */
    private ResultUtil addDestination(Integer lineId, String destArr) {
        if (SinataUtil.isEmpty(destArr)) {
            return ResultUtil.success();
        }
        JSONArray jsonArray = JSON.parseArray(destArr);
        int size = jsonArray.size();
        if(size <= 0){
            return ResultUtil.success();
        }
        if(size > 3){
            return ResultUtil.error("最多只能添加3个目的地");
        }
        int mainCount = 0;
        for (int i = 0; i < size; i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name = ToolUtil.formatting(jsonObject.getString("name"));
            if (SinataUtil.isEmpty(name)) {
                return ResultUtil.error("目的地名称不能为空");
            }
            Integer fenceType = jsonObject.getInteger("fenceType");
            if (fenceType == null || (fenceType != 1 && fenceType != 2)) {
                return ResultUtil.error("围栏类型错误");
            }
            String coordinate = jsonObject.getString("coordinate");
            if (SinataUtil.isEmpty(coordinate)) {
                return ResultUtil.error("目的地围栏不能为空");
            }
 
            BigDecimal price5;
            BigDecimal price7;
            try {
                price5 = new BigDecimal(jsonObject.getString("price5"));
                price7 = new BigDecimal(jsonObject.getString("price7"));
            } catch (Exception ex) {
                return ResultUtil.error("目的地价格格式不正确");
            }
            if (price5.compareTo(BigDecimal.ZERO) < 0 || price7.compareTo(BigDecimal.ZERO) < 0) {
                return ResultUtil.error("目的地价格不能小于0");
            }
 
            Integer isMain = jsonObject.getInteger("isMain");
            if (isMain != null && isMain == 1) {
                mainCount++;
            }
            if(mainCount > 1){
                return ResultUtil.error("最多只能设置一个主要目的地");
            }
 
            Double defaultPointLon = jsonObject.getDouble("defaultPointLon");
            Double defaultPointLat = jsonObject.getDouble("defaultPointLat");
            if (fenceType == 1) {
                String[] arr = coordinate.split(";");
                if (arr.length != 2) {
                    return ResultUtil.error("圆形围栏坐标格式错误");
                }
                String[] center = arr[0].split(",");
                if (center.length != 2) {
                    return ResultUtil.error("圆形围栏中心点格式错误");
                }
                try {
                    defaultPointLon = Double.valueOf(center[0]);
                    defaultPointLat = Double.valueOf(center[1]);
                    double radius = Double.valueOf(arr[1]);
                    if(radius <= 0 || radius > 5000){
                        return ResultUtil.error("圆形围栏半径必须在(0,5000]米");
                    }
                } catch (Exception ex) {
                    return ResultUtil.error("圆形围栏坐标格式错误");
                }
            } else {
                if(defaultPointLon == null || defaultPointLat == null){
                    return ResultUtil.error("多边形围栏需要设置默认点");
                }
            }
 
            TLineDestination destination = new TLineDestination();
            destination.setLineId(lineId);
            destination.setName(name);
            destination.setFenceType(fenceType);
            destination.setCoordinate(coordinate);
            destination.setDefaultPointLon(defaultPointLon);
            destination.setDefaultPointLat(defaultPointLat);
            destination.setPrice5(price5);
            destination.setPrice7(price7);
            Integer state = jsonObject.getInteger("state");
            destination.setState(state == null ? 1 : state);
            destination.setIsMain(isMain == null ? 0 : isMain);
            destination.setAddTime(jsonObject.getString("time"));
            destination.setInsertTime(new Date());
            itLineDestinationService.insert(destination);
        }
        return ResultUtil.success();
    }
 
    private TLineCompany checkLineCompany(Integer lineId, Integer companyId) {
        if (lineId == null || companyId == null) {
            return null;
        }
        return itLineCompanyService.selectOne(new EntityWrapper<TLineCompany>().eq("lineId", lineId).eq("companyId", companyId));
    }
 
    private List<TLineCompany> getLineCompanies(Integer lineId) {
        if (lineId == null) {
            return new ArrayList<>();
        }
        return itLineCompanyService.selectList(new EntityWrapper<TLineCompany>().eq("lineId", lineId).orderBy("id", true));
    }
 
    private boolean hasLineCompanies(Integer lineId) {
        return getLineCompanies(lineId).size() > 0;
    }
 
    private Integer getDefaultLineCompanyId(Integer lineId) {
        List<TLineCompany> lineCompanies = getLineCompanies(lineId);
        if (lineCompanies.size() <= 0) {
            return null;
        }
        return lineCompanies.get(0).getCompanyId();
    }
 
    private String getLineCompanyNames(List<TLineCompany> lineCompanies) {
        if (lineCompanies == null || lineCompanies.size() <= 0) {
            return "";
        }
        List<String> names = new ArrayList<>();
        for (TLineCompany lineCompany : lineCompanies) {
            if (lineCompany == null || lineCompany.getCompanyId() == null) {
                continue;
            }
            TCompany company = itCompanyService.selectById(lineCompany.getCompanyId());
            if (company != null && SinataUtil.isNotEmpty(company.getName())) {
                names.add(company.getName());
            }
        }
        return String.join("、", names);
    }
 
    private Integer getCompanyType(Integer companyId) {
        TCompany company = itCompanyService.selectById(companyId);
        return company == null ? null : company.getType();
    }
 
    private boolean checkDriverBelongCompany(TDriver driver, Integer companyId) {
        if (driver == null || companyId == null) {
            return false;
        }
        Integer companyType = getCompanyType(companyId);
        if (companyType == null) {
            return false;
        }
        if (companyType == 2) {
            return driver.getCompanyId() != null && driver.getCompanyId().intValue() == companyId.intValue();
        }
        if (companyType == 3) {
            return driver.getFranchiseeId() != null && driver.getFranchiseeId().intValue() == companyId.intValue();
        }
        return false;
    }
 
    private boolean checkDriverBelongLineCompanies(TDriver driver, Integer lineId) {
        if (driver == null || lineId == null) {
            return false;
        }
        List<TLineCompany> lineCompanies = getLineCompanies(lineId);
        for (TLineCompany lineCompany : lineCompanies) {
            if (checkDriverBelongCompany(driver, lineCompany.getCompanyId())) {
                return true;
            }
        }
        return false;
    }
 
    private Date parseDay(String day) throws Exception {
        return new SimpleDateFormat("yyyy-MM-dd").parse(day);
    }
 
    private String formatDay(Date day) {
        return new SimpleDateFormat("yyyy-MM-dd").format(day);
    }
 
    private int getDayDiff(Date start, Date end) {
        long oneDay = 24L * 60L * 60L * 1000L;
        long startTime = start.getTime() / oneDay;
        long endTime = end.getTime() / oneDay;
        return (int) (endTime - startTime);
    }
 
    private Date addDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH, days);
        return cal.getTime();
    }
 
    private String buildSeatNoStr(int seatNum) {
        StringBuilder builder = new StringBuilder();
        for (int i = 1; i <= seatNum; i++) {
            if (i > 1) {
                builder.append(",");
            }
            builder.append(i);
        }
        return builder.toString();
    }
 
    private List<Integer> parseIdList(String ids) {
        List<Integer> list = new ArrayList<>();
        if (SinataUtil.isEmpty(ids)) {
            return list;
        }
        try {
            if (ids.startsWith("[")) {
                JSONArray array = JSON.parseArray(ids);
                for (int i = 0; i < array.size(); i++) {
                    Integer id = array.getInteger(i);
                    if (id != null && !list.contains(id)) {
                        list.add(id);
                    }
                }
            } else {
                String[] arr = ids.split(",");
                for (String s : arr) {
                    if (SinataUtil.isNotEmpty(s)) {
                        Integer id = Integer.valueOf(s.trim());
                        if (!list.contains(id)) {
                            list.add(id);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return list;
    }
 
}