13693261870
2025-07-02 6708810c4de34dfb9513061432d656f91d56ee3a
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
package com.ruoyi.buss.controller;
 
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.buss.domain.DmBerth2;
import com.ruoyi.buss.domain.DsTaskList2;
import com.ruoyi.buss.domain.dto.ShipGroupDTO;
import com.ruoyi.buss.domain.dto.Subdata;
import com.ruoyi.buss.domain.dto.TaskRecordList;
import com.ruoyi.buss.domain.dto.ZdGroupDTO;
import com.ruoyi.buss.service.IDmBerth2Service;
import com.ruoyi.buss.service.IDsTaskList2Service;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
 
/**
 * 支队级舰船泊位分组逻辑Controller
 *
 * @author yl
 * @date 2025-03-20
 */
 
@Tag(name = "支队舰船泊位分组")
@Controller
@RequestMapping("/buss/zd")
public class ZdBerthGroupController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(ZdBerthGroupController.class);
 
    private final static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
    @Autowired
    private IDmBerth2Service dmBerthService;
 
    @Autowired
    private IDsTaskList2Service dsTaskListService;
 
    /**
     * 获取支队码头泊位分组数据结果。
     *
     * @return
     */
    @Operation(description = "获取支队泊位分组结果")
    @Log(title = "支队泊位分组", businessType = BusinessType.INSERT)
    @PostMapping("/berthgroup")
    @ResponseBody
    public AjaxResult getZdBerthGroup(@RequestBody ZdGroupDTO zdGroupDTO) throws IOException {
        String berthIds = zdGroupDTO.getBerthIds();
        String berthRuleStr = zdGroupDTO.getBerthGroupRule();
        String taskIdStr = zdGroupDTO.getTaskId();
        List<DmBerth2> dmBerthList = dmBerthService.getDmBerthListByIds(berthIds);
        log.debug("dmBerthList = " + dmBerthList);
        Integer berthRule = Integer.parseInt(berthRuleStr);
 
        // 根据用户所属部门ID,查询管辖码头分配的舰艇信息
        LoginUser sysUser = getLoginUser();
        Long deptId = sysUser.getDeptId();
        log.debug("deptId = : " + deptId);
        List<DsTaskList2> dsTaskListList = dsTaskListService.getDsTaskListByTaskIdAndDeptId(Long.parseLong(taskIdStr), deptId);
        log.debug("根据任务、部分ID获取码头JT信息DsTaskList = " + dsTaskListList);
        JSONArray jsonArray = null;
        switch (berthRule) {
            case 1:
                // 按JT型号分组
                jsonArray = calcZdBerthGroupByJTModel(berthRuleStr, deptId, dmBerthList, dsTaskListList);
                break;
            case 2:
                // 按DY优先分组
                jsonArray = calcZdBerthGroupByBullet(berthRuleStr, deptId, dmBerthList, dsTaskListList);
                break;
            case 3:
                // 按优先顺序分组
                jsonArray = calcZdBerthGroupByOrder(berthRuleStr, deptId, dmBerthList, dsTaskListList);
                break;
            case 4:
                // 按人工分组
                break;
            default:
                // 默认按JT型号分组
        }
        return AjaxResult.success(jsonArray);
    }
 
    /**
     * 按JT型号分组算法。
     * @param berthList
     * @param dsTaskLists
     * @return
     */
    private JSONArray calcZdBerthGroupByJTModel(String parkingType, Long deptId, List<DmBerth2> berthList, List<DsTaskList2> dsTaskLists) {
        // 定义每个泊位的最大长度
        Long[] berthLengths = new Long[berthList.size()];
        for(int i = 0; i < berthList.size(); i++){
            berthLengths[i] = berthList.get(i).getBerthLen();
        }
 
        // 按型号分组并两两配对
        Map<String, List<DsTaskList2>> typeShipMap = new HashMap<>();
        for (DsTaskList2 ship : dsTaskLists) {
            typeShipMap.computeIfAbsent(ship.getShipType(), k -> new ArrayList<>()).add(ship);
        }
        log.debug("typeShipMap =====: " + typeShipMap);
 
        List<List<DsTaskList2>> shipPairs = new ArrayList<>();
        for (List<DsTaskList2> shipsOfType : typeShipMap.values()) {
            for (int i = 0; i < shipsOfType.size(); i += 2) {
                shipPairs.add(shipsOfType.subList(i, i + 2));
            }
        }
        log.debug("shipPairs =====: " + shipPairs);
 
        // 按每组中两艘船停靠时间总和从小到大排序
        shipPairs.sort(Comparator.comparingDouble(pair -> (pair.get(0).getDockTime() == null ? 0:pair.get(0).getDockTime()) + (pair.get(1).getDockTime()==null ? 0:pair.get(1).getDockTime())));
 
        // 记录每个泊位的当前总停靠时间
        int[] berthTotalTimes = new int[berthLengths.length];
        // 记录每组船分配到的泊位
        int[] pairAssignments = new int[shipPairs.size()];
 
        // 分配船只到泊位
        for (int i = 0; i < shipPairs.size(); i++) {
            List<DsTaskList2> pair = shipPairs.get(i);
            Double totalLength = pair.get(0).getShipLen(); // 双船并靠,取一艘船长度判断是否能停靠
            int minTime = Integer.MAX_VALUE;
            int bestBerth = -1;
            for (int j = 0; j < berthLengths.length; j++) {
                if (totalLength <= berthLengths[j]) {
                    Double dockTimeMax = Math.max(pair.get(0).getDockTime() == null ? 0 : pair.get(0).getDockTime(), pair.get(1).getDockTime() == null ? 0 : pair.get(1).getDockTime());
                    int newTime = berthTotalTimes[j] + dockTimeMax.intValue();
                    if (newTime < minTime) {
                        minTime = newTime;
                        bestBerth = j;
                    }
                }
            }
            pairAssignments[i] = bestBerth;
            berthTotalTimes[bestBerth] = minTime;
        }
 
        // 输出结果
        for (int i = 0; i < shipPairs.size(); i++) {
            List<DsTaskList2> pair = shipPairs.get(i);
            log.debug("舰船 " + pair.get(0).getShipNo() + " 和 " + pair.get(1).getShipNo() + "(型号 " + pair.get(0).getShipType() + ")停靠在泊位 " + (pairAssignments[i] + 1));
        }
        int totalTime = Arrays.stream(berthTotalTimes).max().getAsInt();
        log.debug("所有船停靠到离开泊位的总时间最短为: " + totalTime + " 小时");
 
        log.debug("******** 按泊位号解析依次排列的DsTaskList对象 ********");
        // 按泊位号解析依次排列的DsTaskList对象
        // 按照泊位号顺序,计算每个泊位上停靠舰船的对象DsTaskList
        HashMap<String, List<DsTaskList2>> resultList = new HashMap<>();
        for (int i = 0; i < pairAssignments.length; i++) {
            int berthNumber = pairAssignments[i];
            String berthKey = "" + (berthNumber + 1);
            List<DsTaskList2> shipsOnBerth = resultList.computeIfAbsent(berthKey, k -> new ArrayList<>());
            List<DsTaskList2> pair = shipPairs.get(i);
            shipsOnBerth.addAll(pair);
        }
 
        // 输出结果
        JSONArray rootJSONArray = new JSONArray();
        if (resultList != null) {
            Date firstStartDate = new Date(System.currentTimeMillis());
            Date lastEndDate = new Date(System.currentTimeMillis());
            Long totalAmmoD = 0L;//总导弹数
            Long totalAmmoP = 0L;//总炮弹数
            Long totalAmmoS = 0L;//总鱼水雷数
            Long totalAmmoO = 0L;//总其他弹药数
            Double totalWater = 0.0;//总淡水数
            Double totalWaterP = 0.0;//总纯水数
            Long totalFood = 0L;//总主副食数
            Long totalFoodW = 0L;//总桶装水数
            Long totalFoodO = 0L;//总其他物资数
 
            for (Map.Entry<String, List<DsTaskList2>> entry : resultList.entrySet()) {
                JSONObject rootJSONObj = new JSONObject();
                JSONObject sub1JsonObj = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                log.debug("JT型号分组泊位 " + entry.getKey() + " 上停靠的舰船:");
                sub1JsonObj.put("berthName", entry.getKey());
 
                JSONArray subJSONArray = new JSONArray();
                for (int i = 0; i < dsTaskLists.size(); i++) {
                    DsTaskList2 ship = dsTaskLists.get(i);
                    // 更新DsTaskList数据中的泊位编号、泊位名称、并靠策略和补给顺序字段
                    DsTaskList2 updateDsTaskList = new DsTaskList2();
                    updateDsTaskList.setPKID(ship.getPKID());
                    DmBerth2 berthValue = dmBerthService.selectDmBerthByPKID(Long.parseLong(entry.getKey()));
                    updateDsTaskList.setBerthId(berthValue.getPKID());
                    updateDsTaskList.setBerthName(berthValue.getNAME());
                    updateDsTaskList.setParkingType(parkingType);
                    updateDsTaskList.setSupplySeq(String.valueOf(i+1));
                    updateDsTaskList.setDeptId(deptId);
                    log.debug("Update DsTaskList2 PKID =====: " + ship.getPKID());
                    log.debug("Update DsTaskList2 BerthId =====: " + berthValue.getPKID());
                    log.debug("Update DsTaskList2 BerthName =====: " + berthValue.getNAME());
                    log.debug("Update DsTaskList2 ParkingType =====: " + parkingType);
                    log.debug("Update DsTaskList2 SupplySeq =====: " + (i+1));
                    int result = dsTaskListService.updateDsTaskList(updateDsTaskList);
                    log.debug("==================================: " + result);
 
                    totalAmmoD += ship.getAmmoD() == null ? 0 : ship.getAmmoD();
                    totalAmmoP += ship.getAmmoP() == null ? 0 : ship.getAmmoP();
                    totalAmmoS += ship.getAmmoS() == null ? 0 : ship.getAmmoS();
                    totalAmmoO += ship.getAmmoO() == null ? 0 : ship.getAmmoO();
 
                    totalWater += ship.getWATER() == null ? 0 : ship.getWATER();
                    totalWaterP += ship.getWaterP() == null ? 0 : ship.getWaterP();
                    totalFood += ship.getFOOD() == null ? 0 : ship.getFOOD();
                    totalFoodW += ship.getFoodW() == null ? 0 : ship.getFoodW();
                    totalFoodO += ship.getFoodO() == null ? 0 : ship.getFoodO();
 
                    Date startDate = ship.getpSTime(); //计划抵港时间
                    Date endDate = ship.getpETime(); //计划离港时间
                    if (firstStartDate.after(startDate)) {
                        firstStartDate = startDate;
                    }
                    if (lastEndDate.before(endDate)) {
                        lastEndDate = endDate;
                    }
                    log.debug("  - 船名:" + ship.getShipNo() + ",型号:" + ship.getShipType() + ",停靠时间:" + (ship.getDockTime() == null ? 0 : ship.getDockTime()) + " 分钟");
 
                    // 构建JSON对象
                    JSONObject tmpJsonObject = new JSONObject();
                    tmpJsonObject.put("pkId", ship.getPKID());
                    tmpJsonObject.put("taskId", ship.getTaskId());
                    tmpJsonObject.put("shipNo", ship.getShipNo());
                    tmpJsonObject.put("shipType", ship.getShipType());
                    tmpJsonObject.put("tonnage", ship.getTONNAGE());
                    Long level = ship.getLEVEL() == null ? 1L : ship.getLEVEL();
                    if(level == 2L){//先油后弹
                        tmpJsonObject.put("supplySeq", "先油后弹");
                    }else if(level == 3L){//先弹后油
                        tmpJsonObject.put("supplySeq", "先弹后油");
                    }else{
                        tmpJsonObject.put("supplySeq", "同时作业");
                    }
                    tmpJsonObject.put("level", ship.getLEVEL());
                    tmpJsonObject.put("oilB", ship.getOilB() == null ? 0 : ship.getOilB());
                    tmpJsonObject.put("oilG", ship.getOilG() == null ? 0 : ship.getOilG());
                    tmpJsonObject.put("oilA", ship.getOilA() == null ? 0 : ship.getOilA());
                    tmpJsonObject.put("ammoD", ship.getAmmoD() == null ? 0 : ship.getAmmoD());
                    tmpJsonObject.put("ammoP", ship.getAmmoP() == null ? 0 : ship.getAmmoP());
                    tmpJsonObject.put("ammoS", ship.getAmmoS() == null ? 0 : ship.getAmmoS());
                    tmpJsonObject.put("ammoO", ship.getAmmoO() == null ? 0 : ship.getAmmoO());
                    tmpJsonObject.put("water", ship.getWATER() == null ? 0 : ship.getWATER());
                    tmpJsonObject.put("waterP", ship.getWaterP() == null ? 0 : ship.getWaterP());
                    tmpJsonObject.put("food", ship.getFOOD() == null ? 0 : ship.getFOOD());
                    tmpJsonObject.put("foodW", ship.getFoodW() == null ? 0 : ship.getFoodW());
                    tmpJsonObject.put("foodO", ship.getFoodO() == null ? 0 : ship.getFoodO());
                    tmpJsonObject.put("pSTime", ship.getpSTime() == null ? 0 : ship.getpSTime());
                    tmpJsonObject.put("pETime", ship.getpETime() == null ? 0 : ship.getpETime());
                    subJSONArray.add(tmpJsonObject);
                    sub1JsonObj.put("subData", subJSONArray);
                }
                jsonArray.add(sub1JsonObj);
                rootJSONObj.put("parkingType", parkingType);
                rootJSONObj.put("dsTaskList", jsonArray);
                rootJSONObj.put("totalAmmoD", totalAmmoD);
                rootJSONObj.put("totalAmmoP", totalAmmoP);
                rootJSONObj.put("totalAmmoS", totalAmmoS);
                rootJSONObj.put("totalAmmoO", totalAmmoO);
                rootJSONObj.put("totalWater", totalWater);
                rootJSONObj.put("totalWaterP", totalWaterP);
                rootJSONObj.put("totalFood", totalFood);
                rootJSONObj.put("totalFoodW", totalFoodW);
                rootJSONObj.put("totalFoodO", totalFoodO);
                rootJSONObj.put("firstStartDate", format.format(firstStartDate));
                rootJSONObj.put("lastEndDate", format.format(lastEndDate));
                rootJSONArray.add(rootJSONObj);
            }
        }
        log.debug("************************************************");
        return rootJSONArray;
    }
 
    /**
     * 按DY优先分组算法。
     */
    private JSONArray calcZdBerthGroupByBullet(String parkingType, Long deptId, List<DmBerth2> berthList, List<DsTaskList2> dsTaskLists) {
        // 按加油需求、船类型和抵港时间排序
        dsTaskLists.sort(Comparator.comparing(DsTaskList2::needRefueling).reversed()
                .thenComparing(DsTaskList2::getShipType)
                .thenComparing(DsTaskList2::getpSTime));
 
        // 按同型号 2 艘一组分组
        List<List<DsTaskList2>> shipGroups = new ArrayList<>();
        Map<String, List<DsTaskList2>> typeMap = new HashMap<>();
        for (DsTaskList2 ship : dsTaskLists) {
            String shipType = ship.getShipType();
            typeMap.computeIfAbsent(shipType, k -> new ArrayList<>()).add(ship);
        }
        for (List<DsTaskList2> shipsOfType : typeMap.values()) {
            for (int i = 0; i < shipsOfType.size(); i += 2) {
                if (i + 1 < shipsOfType.size()) {
                    // 确保一组中需要加油的船排在前面
                    if (!shipsOfType.get(i).needRefueling() && shipsOfType.get(i + 1).needRefueling()) {
                        Collections.swap(shipsOfType, i, i + 1);
                    }
                    shipGroups.add(Arrays.asList(shipsOfType.get(i), shipsOfType.get(i + 1)));
                } else {
                    // 处理单艘剩余的情况
                    shipGroups.add(Collections.singletonList(shipsOfType.get(i)));
                }
            }
        }
        log.debug("按弹药优先分组shipGroups =====: " + shipGroups);
 
        Date currentTime = null;
        try {
            currentTime = format.parse("2025-03-01 00:00:00");
        }catch (Exception ex) {
            ex.printStackTrace();
        }
 
        // 对舰船组按停靠结束时间排序
        shipGroups.sort(Comparator.comparing(group -> {
            long maxEndTime = 0;
            for (DsTaskList2 ship : group) {
                maxEndTime = Math.max(maxEndTime, ship.getpETime().getTime());
            }
            return maxEndTime;
        }));
 
        // 模拟停靠过程
        Map<DsTaskList2, DmBerth2> dockingMap = new HashMap<>();
        Map<DmBerth2, Date> berthAvailableTime = new HashMap<>();
        for (DmBerth2 berth : berthList) {
            berthAvailableTime.put(berth, currentTime);
        }
 
        for (List<DsTaskList2> group : shipGroups) {
            DmBerth2 bestBerth = null;
            Date earliestAvailableTime = null;
            for (DmBerth2 berth : berthList) {
                if (canDock(group, berth)) {
                    Date availableTime = berthAvailableTime.get(berth);
                    if (earliestAvailableTime == null || availableTime.before(earliestAvailableTime)) {
                        earliestAvailableTime = availableTime;
                        bestBerth = berth;
                    }
                }
            }
            if (bestBerth != null) {
                for (DsTaskList2 ship : group) {
                    dockingMap.put(ship, bestBerth);
                }
                long startTime = Math.max(group.get(0).getpSTime().getTime(), earliestAvailableTime.getTime());
                long endTime = 0;
                for (DsTaskList2 ship : group) {
                    endTime = Math.max(endTime, ship.getpETime().getTime());
                }
                berthAvailableTime.put(bestBerth, new Date(endTime));
            }
        }
 
        // 整理输出结果
        Map<DmBerth2, List<DsTaskList2>> berthShipMap = new LinkedHashMap<>();
        for (Map.Entry<DsTaskList2, DmBerth2> entry : dockingMap.entrySet()) {
            DmBerth2 berth = entry.getValue();
            DsTaskList2 ship = entry.getKey();
            berthShipMap.computeIfAbsent(berth, k -> new ArrayList<>()).add(ship);
        }
        log.debug("berthShipMap ========: " + berthShipMap);
 
        //****** add BerthShipMap handle ********//
        // 将 LinkedHashMap 的键值对转移到 List 中
        List<Map.Entry<DmBerth2, List<DsTaskList2>>> list = new ArrayList<>(berthShipMap.entrySet());
 
        // 对 List 进行排序
        Collections.sort(list, new Comparator<Map.Entry<DmBerth2, List<DsTaskList2>>>() {
            @Override
            public int compare(Map.Entry<DmBerth2, List<DsTaskList2>> o1, Map.Entry<DmBerth2, List<DsTaskList2>> o2) {
                return (int) (((o1.getKey().getHarborId() * 100) + o1.getKey().getOrderNum()) - ((o2.getKey().getHarborId() * 100) + o2.getKey().getOrderNum()));
            }
        });
 
        // 将排序后的键值对存于新的 LinkedHashMap 中
        LinkedHashMap<DmBerth2, List<DsTaskList2>> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<DmBerth2, List<DsTaskList2>> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        //***************************************//
 
 
        // 按分组输出结果
        /**
         for (Map.Entry<DmBerth, List<DsTaskList>> entry : berthShipMap.entrySet()) {
         DmBerth berth = entry.getKey();
         List<DsTaskList> shipsInBerth = entry.getValue();
         StringBuilder shipNos = new StringBuilder();
         String shipType = shipsInBerth.get(0).getShipType();
         for (int i = 0; i < shipsInBerth.size(); i++) {
         if (i > 0) {
         shipNos.append(" 和 ");
         }
         shipNos.append(shipsInBerth.get(i).getShipNo());
         }
         System.out.println("船 " + shipNos + "(型号 " + shipType + ")停靠在泊位 " + berth.getNAME());
         }
         */
 
        JSONArray jsonObj = getJSONObject(parkingType, deptId, sortedMap);
        return jsonObj;
    }
 
    private static boolean canDock(List<DsTaskList2> group, DmBerth2 berth) {
        for (DsTaskList2 ship : group) {
            if (ship.getShipLen() > berth.getBerthLen()) {
                return false;
            }
        }
        return true;
    }
 
    /**
     * 按优先顺序分组算法。
     */
    private JSONArray calcZdBerthGroupByOrder(String parkingType, Long deptId, List<DmBerth2> berthList, List<DsTaskList2> dsTaskLists) {
        // 按优先级、船类型和抵港时间排序
        dsTaskLists.sort(Comparator.comparing(DsTaskList2::getLEVEL).reversed()
                .thenComparing(DsTaskList2::getShipType)
                .thenComparing(DsTaskList2::getpSTime));
        JSONArray jsonObj = null;
        try {
            jsonObj = handleJtGroup(parkingType, deptId, berthList, dsTaskLists);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObj;
    }
 
    /**
     * 根据泊位上舰船并排停靠数量,对排序后的舰船进行分组操作,返回各泊位的舰船停靠结果。
     *
     * @return
     */
    private JSONArray handleJtGroup(String parkingType, Long deptId, List<DmBerth2> berthList, List<DsTaskList2> dsTaskLists) throws ParseException {
        // 默认按同型号 2 艘一组分组
        List<List<DsTaskList2>> shipGroups = new ArrayList<>();
        Map<String, List<DsTaskList2>> typeMap = new HashMap<>();
        for (DsTaskList2 ship : dsTaskLists) {
            String shipType = ship.getShipType();
            typeMap.computeIfAbsent(shipType, k -> new ArrayList<>()).add(ship);
        }
        for (List<DsTaskList2> shipsOfType : typeMap.values()) {
            for (int i = 0; i < shipsOfType.size(); i += 2) {
                if (i + 1 < shipsOfType.size()) {
                    // 确保一组中需要加油的船排在前面
                    if (!shipsOfType.get(i).needRefueling() && shipsOfType.get(i + 1).needRefueling()) {
                        Collections.swap(shipsOfType, i, i + 1);
                    }
                    shipGroups.add(Arrays.asList(shipsOfType.get(i), shipsOfType.get(i + 1)));
                } else {
                    // 处理单艘剩余的情况
                    shipGroups.add(Collections.singletonList(shipsOfType.get(i)));
                }
            }
        }
        System.out.println("shipGroups =====: " + shipGroups);
 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentTime = sdf.parse("2025-03-23 00:00:00");
 
        // 对舰船组按停靠结束时间排序
        shipGroups.sort(Comparator.comparing(group -> {
            long maxEndTime = 0;
            for (DsTaskList2 ship : group) {
                maxEndTime = Math.max(maxEndTime, ship.getpETime().getTime());
            }
            return maxEndTime;
        }));
 
        // 模拟停靠过程
        Map<DsTaskList2, DmBerth2> dockingMap = new HashMap<>();
        Map<DmBerth2, Date> berthAvailableTime = new HashMap<>();
        for (DmBerth2 berth : berthList) {
            berthAvailableTime.put(berth, currentTime);
        }
 
        for (List<DsTaskList2> group : shipGroups) {
            DmBerth2 bestBerth = null;
            Date earliestAvailableTime = null;
            for (DmBerth2 berth : berthList) {
                if (canDock(group, berth)) {
                    Date availableTime = berthAvailableTime.get(berth);
                    if (earliestAvailableTime == null || availableTime.before(earliestAvailableTime)) {
                        earliestAvailableTime = availableTime;
                        bestBerth = berth;
                    }
                }
            }
            if (bestBerth != null) {
                for (DsTaskList2 ship : group) {
                    dockingMap.put(ship, bestBerth);
                }
                long startTime = Math.max(group.get(0).getpSTime().getTime(), earliestAvailableTime.getTime());
                long endTime = 0;
                for (DsTaskList2 ship : group) {
                    endTime = Math.max(endTime, ship.getpETime().getTime());
                }
                berthAvailableTime.put(bestBerth, new Date(endTime));
            }
        }
 
        // 整理输出结果
        Map<DmBerth2, List<DsTaskList2>> berthShipMap = new HashMap<>();
        for (Map.Entry<DsTaskList2, DmBerth2> entry : dockingMap.entrySet()) {
            DmBerth2 berth = entry.getValue();
            DsTaskList2 ship = entry.getKey();
            berthShipMap.computeIfAbsent(berth, k -> new ArrayList<>()).add(ship);
        }
 
        // 按分组输出结果
//        for (Map.Entry<DmBerth2, List<DsTaskList2>> entry : berthShipMap.entrySet()) {
//            DmBerth2 berth = entry.getKey();
//            List<DsTaskList2> shipsInBerth = entry.getValue();
//            StringBuilder shipNos = new StringBuilder();
//            String shipType = shipsInBerth.get(0).getShipType();
//            for (int i = 0; i < shipsInBerth.size(); i++) {
//                if (i > 0) {
//                    shipNos.append(" 和 ");
//                }
//                shipNos.append(shipsInBerth.get(i).getShipNo());
//            }
//            System.out.println("船 " + shipNos + "(型号 " + shipType + ")停靠在泊位 " + berth.getNAME());
//        }
 
        //****** add BerthShipMap handle ********//
        // 将 LinkedHashMap 的键值对转移到 List 中
        List<Map.Entry<DmBerth2, List<DsTaskList2>>> list = new ArrayList<>(berthShipMap.entrySet());
 
        // 对 List 进行排序
        Collections.sort(list, new Comparator<Map.Entry<DmBerth2, List<DsTaskList2>>>() {
            @Override
            public int compare(Map.Entry<DmBerth2, List<DsTaskList2>> o1, Map.Entry<DmBerth2, List<DsTaskList2>> o2) {
                return o1.getKey().getPKID().compareTo(o2.getKey().getPKID());
            }
        });
 
        // 将排序后的键值对存于新的 LinkedHashMap 中
        LinkedHashMap<DmBerth2, List<DsTaskList2>> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<DmBerth2, List<DsTaskList2>> entry : list) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        //***************************************//
        JSONArray jsonObj = getJSONObject(parkingType, deptId, sortedMap);
        return null;
    }
 
    /**
     * 构建舰船分组的JSON对象。
     * @param berthShipMap
     * @return
     */
    private JSONArray getJSONObject(String parkingType, Long deptId, LinkedHashMap<DmBerth2, List<DsTaskList2>> berthShipMap) {
        JSONArray rootJSONArray = new JSONArray();
        if(berthShipMap != null) {
            Long totalAmmoD = 0L;//总导弹数
            Long totalAmmoP = 0L;//总炮弹数
            Long totalAmmoS = 0L;//总鱼水雷数
            Long totalAmmoO = 0L;//总其他弹药数
            Double totalWater = 0.0;//总淡水数
            Double totalWaterP = 0.0;//总纯水数
            Long totalFood = 0L;//总主副食数
            Long totalFoodW = 0L;//总桶装水数
            Long totalFoodO = 0L;//总其他物资数
            Date firstStartDate = new Date(System.currentTimeMillis());
            Date lastEndDate = new Date(System.currentTimeMillis());
 
            for (Map.Entry<DmBerth2, List<DsTaskList2>> entry : berthShipMap.entrySet()) {
                JSONObject rootJSONObj = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                JSONObject sub1JsonObj = new JSONObject();
                List<DsTaskList2> dsTaskLists = entry.getValue();
                DmBerth2 berthValue = entry.getKey();
                String berthName = berthValue.getNAME();
                Long berthId = berthValue.getPKID();
                Long harborId = berthValue.getHarborId();
                String harborName = berthValue.getHarborName();
                sub1JsonObj.put("harborId", harborId);
                sub1JsonObj.put("harborName", harborName);
                sub1JsonObj.put("berthId", berthId);
                sub1JsonObj.put("berthName", berthName);
 
                // 输出结果
                if (dsTaskLists != null) {
                    JSONArray subJSONArray = new JSONArray();
                    for (int i = 0; i < dsTaskLists.size(); i++) {
                        DsTaskList2 ship = dsTaskLists.get(i);
                        // 更新DsTaskList数据中的泊位编号、泊位名称、并靠策略和补给顺序字段
                        DsTaskList2 updateDsTaskList = new DsTaskList2();
                        updateDsTaskList.setPKID(ship.getPKID());
                        updateDsTaskList.setBerthId(berthValue.getPKID());
                        updateDsTaskList.setBerthName(berthValue.getNAME());
                        updateDsTaskList.setParkingType(parkingType);
                        updateDsTaskList.setSupplySeq(String.valueOf(i+1));
                        updateDsTaskList.setDeptId(deptId);
                        log.debug("Update DsTaskList2 PKID =====: " + ship.getPKID());
                        log.debug("Update DsTaskList2 BerthId =====: " + berthValue.getPKID());
                        log.debug("Update DsTaskList2 BerthName =====: " + berthValue.getNAME());
                        log.debug("Update DsTaskList2 ParkingType =====: " + parkingType);
                        log.debug("Update DsTaskList2 SupplySeq =====: " + (i+1));
                        int result = dsTaskListService.updateDsTaskList(updateDsTaskList);
                        log.debug("==================================: " + result);
 
                        totalAmmoD += ship.getAmmoD() == null ? 0 : ship.getAmmoO();
                        totalAmmoP += ship.getAmmoP() == null ? 0 : ship.getAmmoP();
                        totalAmmoS += ship.getAmmoS() == null ? 0 : ship.getAmmoS();
                        totalAmmoO += ship.getAmmoO() == null ? 0 : ship.getAmmoO();
 
                        totalWater += ship.getWATER() == null ? 0 : ship.getWATER();
                        totalWaterP += ship.getWaterP() == null ? 0 : ship.getWaterP();
                        totalFood += ship.getFOOD() == null ? 0 : ship.getFOOD();
                        totalFoodW += ship.getFoodW() == null ? 0 : ship.getFoodW();
                        totalFoodO += ship.getFoodO() == null ? 0 : ship.getFoodW();
 
                        Date startDate = ship.getpSTime(); //计划抵港时间
                        Date endDate = ship.getpETime(); //计划离港时间
                        if (firstStartDate.after(startDate)) {
                            firstStartDate = startDate;
                        }
                        if (lastEndDate.before(endDate)) {
                            lastEndDate = endDate;
                        }
 
                        // 构建JSON对象
                        JSONObject tmpJsonObject = new JSONObject();
                        tmpJsonObject.put("pkId", ship.getPKID());
                        tmpJsonObject.put("taskId", ship.getTaskId());
                        tmpJsonObject.put("shipNo", ship.getShipNo());
                        tmpJsonObject.put("shipType", ship.getShipType());
                        tmpJsonObject.put("tonnage", ship.getTONNAGE() == null ? 0 : ship.getTONNAGE());
                        Long level = ship.getLEVEL() == null ? 1L : ship.getLEVEL();
                        if(level == 2L){//先油后弹
                            tmpJsonObject.put("supplySeq", "先油后弹");
                        }else if(level == 3L){//先弹后油
                            tmpJsonObject.put("supplySeq", "先弹后油");
                        }else{
                            tmpJsonObject.put("supplySeq", "同时作业");
                        }
                        tmpJsonObject.put("level", ship.getLEVEL());
                        tmpJsonObject.put("oilB", ship.getOilB() == null ? 0 : ship.getOilB());
                        tmpJsonObject.put("oilG", ship.getOilG() == null ? 0 : ship.getOilG());
                        tmpJsonObject.put("oilA", ship.getOilA() == null ? 0 : ship.getOilA());
                        tmpJsonObject.put("ammoD", ship.getAmmoD() == null ? 0 : ship.getAmmoD());
                        tmpJsonObject.put("ammoP", ship.getAmmoP() == null ? 0 : ship.getAmmoP());
                        tmpJsonObject.put("ammoS", ship.getAmmoS() == null ? 0 : ship.getAmmoS());
                        tmpJsonObject.put("ammoO", ship.getAmmoO() == null ? 0 : ship.getAmmoO());
                        tmpJsonObject.put("water", ship.getWATER() == null ? 0 : ship.getWATER());
                        tmpJsonObject.put("waterP", ship.getWaterP() == null ? 0 : ship.getWaterP());
                        tmpJsonObject.put("food", ship.getFOOD() == null ? 0 : ship.getFOOD());
                        tmpJsonObject.put("foodW", ship.getFoodW() == null ? 0 : ship.getFoodW());
                        tmpJsonObject.put("foodO", ship.getFoodO() == null ? 0 : ship.getFoodO());
                        tmpJsonObject.put("pSTime", ship.getpSTime());
                        tmpJsonObject.put("pETime", ship.getpETime());
                        subJSONArray.add(tmpJsonObject);
                        sub1JsonObj.put("subData", subJSONArray);
                    }
                }
                jsonArray.add(sub1JsonObj);
                rootJSONObj.put("parkingType", parkingType);
                rootJSONObj.put("dsTaskList", jsonArray);
                rootJSONObj.put("totalAmmoD", totalAmmoD);
                rootJSONObj.put("totalAmmoP", totalAmmoP);
                rootJSONObj.put("totalAmmoS", totalAmmoS);
                rootJSONObj.put("totalAmmoO", totalAmmoO);
                rootJSONObj.put("totalWater", totalWater);
                rootJSONObj.put("totalWaterP", totalWaterP);
                rootJSONObj.put("totalFood", totalFood);
                rootJSONObj.put("totalFoodW", totalFoodW);
                rootJSONObj.put("totalFoodO", totalFoodO);
                rootJSONObj.put("firstStartDate", format.format(firstStartDate));
                rootJSONObj.put("lastEndDate", format.format(lastEndDate));
                rootJSONArray.add(rootJSONObj);
            }
        }
        log.debug("XXXXXX =====: " + rootJSONArray);
        return rootJSONArray;
    }
 
    /**
     * 按人工分组算法。
     */
    private void calcZdBerthGroupByHandMove(List<DmBerth2> berthList, List<DsTaskList2> dsTaskLists) {
 
    }
 
    /**
     * 获取支队码头泊位分组数据结果。
     *
     * @return
     */
    @Operation(description = "修改舰船补给顺序")
    @Log(title = "修改舰船补给顺序", businessType = BusinessType.INSERT)
    @PostMapping("/updatelevel")
    @ResponseBody
    public AjaxResult updateSupplyLevelBy(Long pkId, Long supplyLevel) {
        DsTaskList2 dsTaskList2 = new DsTaskList2();
        dsTaskList2.setPKID(pkId);
        dsTaskList2.setLEVEL(supplyLevel);
        try {
            int result = dsTaskListService.updateDsTaskList(dsTaskList2);
            if (result > 0) {
                return AjaxResult.success("PKID = [" + String.valueOf(pkId) + "]记录补给顺序更新成功");
            } else {
                return AjaxResult.success("未找到符合条件的记录进行更新");
            }
        } catch (Exception ex) {
            return AjaxResult.error("PKID = [" + String.valueOf(pkId) + "]记录补给顺序更新失败");
        }
    }
 
    @Operation(description = "更新支队分组顺序")
    @Log(title = "更新支队分组顺序", businessType = BusinessType.INSERT)
    @PostMapping("/updategroupseq")
    @ResponseBody
    public AjaxResult updateShipGroupSeq(@RequestBody List<ShipGroupDTO> shipGroupDTOList){
        int flag = 0;
        if(shipGroupDTOList != null && shipGroupDTOList.size() > 0){
            // 获取所有的泊位信息
            List<DmBerth2> berth2List = dmBerthService.selectDmBerthList(new DmBerth2());
 
            for(ShipGroupDTO shipGroupDTO : shipGroupDTOList){
                // String parkingType = shipGroupDTO.getParkingType();
                List<TaskRecordList> taskRecordList = shipGroupDTO.getDsTaskList();
                Long berthId = taskRecordList.get(0).getBerthId();
                Long harborId = taskRecordList.get(0).getHarborId();
                List<Subdata> subDataList = taskRecordList.get(0).getSubData();
                if(subDataList!= null && subDataList.size() > 0){
                    for(int i = 0; i < subDataList.size(); i++){
                        Subdata subdata = subDataList.get(i);
                        Long pkId = subdata.getPkId();
                        String supplySeq = subdata.getSupplySeq();
                        if(supplySeq.equals("同时作业")){
                            supplySeq = "1";
                        }
                        else if(supplySeq.equals("先油后弹")){
                            supplySeq = "2";
                        }if(supplySeq.equals("先弹后油")){
                            supplySeq = "3";
                        }
 
//                        DsTaskList2 dsTaskList = new DsTaskList2();
//                        dsTaskList.setPKID(pkId);
                        DsTaskList2 existDsTaskList = dsTaskListService.selectDsTaskListByPkid(pkId);
                        if(existDsTaskList != null){
//                            Long tempBerthId = existDsTaskList.getBerthId();
//                            Long tempHarborId = existDsTaskList.getHarborId();
//                            String tempSupplySeq = existDsTaskList.getSupplySeq();
                           // if(berthId != tempBerthId || harborId != tempHarborId){
                                DsTaskList2 newDsTaskList = new DsTaskList2();
                                newDsTaskList.setPKID(pkId);
                                newDsTaskList.setHarborId(harborId);
                                newDsTaskList.setBerthId(berthId);
                                newDsTaskList.setSupplySeq(supplySeq);
                                newDsTaskList.setPath(getBerthPathById(berth2List, berthId));
                                int result = dsTaskListService.updateDsTaskList(newDsTaskList);
                                if(result > 0 || result == 0){
                                    flag += 1;
                                }
                           // }
                        }
                    }
                }
            }
            if(flag > 0){
                return AjaxResult.success("支队分组顺序更新成功!");
            }else{
                return AjaxResult.success("分组顺序无调整!");
            }
        }
        return AjaxResult.success("支队分组顺序没有变化,未更新!");
    }
 
    // 根据ID获取泊位路径信息详情
    private String getBerthPathById(List<DmBerth2> list, Long id){
        for(DmBerth2 berth2 : list){
            if(berth2.getPKID() == id){
                return berth2.getPath();
            }
        }
        return "";
    }
}