sfd
2025-05-21 da8559d4b6abaefabf394d1d2174b3bf4a545a89
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
package com.aps.core.service.impl;
 
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aps.common.core.utils.DateUtils;
import com.aps.common.core.utils.uuid.IdUtils;
import com.aps.common.security.utils.SecurityUtils;
import com.aps.core.domain.*;
import com.aps.core.mapper.ApsGasPipelineCapacityPlanMapper;
import com.aps.core.mapper.ApsGasPipingPlanMapper;
import com.aps.core.mapper.ApsGasPipingRouteStatMapper;
import com.aps.core.service.IApsGasMaterialUsageService;
import com.aps.core.service.IApsGasPipingRouteStatService;
import com.aps.core.service.IApsStandardProcessService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
 
import static java.util.stream.Collectors.groupingBy;
 
/**
 * 气体管路产能负载统计Service业务层处理
 * 
 * @author hjy
 * @date 2025-04-24
 */
@Slf4j
@Service
public class ApsGasPipingRouteStatServiceImpl implements IApsGasPipingRouteStatService 
{
    @Autowired
    private ApsGasPipingRouteStatMapper apsGasPipingRouteStatMapper;
 
    @Autowired
    private ApsGasPipingPlanMapper apsGasPipingPlanMapper;
 
    @Autowired
    private ApsGasPipelineCapacityPlanMapper apsGasPipelineCapacityPlanMapper;
 
    @Autowired
    private IApsGasMaterialUsageService apsGasMaterialUsageService;
 
    @Autowired
    private IApsStandardProcessService apsStandardProcessService;
 
    /**
     * 查询气体管路产能负载统计
     * 
     * @param id 气体管路产能负载统计主键
     * @return 气体管路产能负载统计
     */
    @Override
    public ApsGasPipingRouteStat selectApsGasPipingRouteStatById(String id)
    {
        return apsGasPipingRouteStatMapper.selectApsGasPipingRouteStatById(id);
    }
 
    /**
     * 查询气体管路产能负载统计列表
     * 
     * @param apsGasPipingRouteStat 气体管路产能负载统计
     * @return 气体管路产能负载统计
     */
    @Override
    public List<ApsGasPipingRouteStat> selectApsGasPipingRouteStatList(ApsGasPipingRouteStat apsGasPipingRouteStat)
    {
        return apsGasPipingRouteStatMapper.selectApsGasPipingRouteStatList(apsGasPipingRouteStat);
    }
 
    /**
     * 新增气体管路产能负载统计
     * 
     * @param apsGasPipingRouteStat 气体管路产能负载统计
     * @return 结果
     */
    @Override
    public int insertApsGasPipingRouteStat(ApsGasPipingRouteStat apsGasPipingRouteStat)
    {
        apsGasPipingRouteStat.setCreateTime(DateUtils.getNowDate());
        apsGasPipingRouteStat.setCreateBy(SecurityUtils.getUsername());
        return apsGasPipingRouteStatMapper.insertApsGasPipingRouteStat(apsGasPipingRouteStat);
    }
 
    /**
     * 修改气体管路产能负载统计
     * 
     * @param apsGasPipingRouteStat 气体管路产能负载统计
     * @return 结果
     */
    @Override
    public int updateApsGasPipingRouteStat(ApsGasPipingRouteStat apsGasPipingRouteStat)
    {
        apsGasPipingRouteStat.setUpdateBy(SecurityUtils.getUsername());
        apsGasPipingRouteStat.setUpdateTime(DateUtils.getNowDate());
        return apsGasPipingRouteStatMapper.updateApsGasPipingRouteStat(apsGasPipingRouteStat);
    }
 
    /**
     * 批量删除气体管路产能负载统计
     * 
     * @param ids 需要删除的气体管路产能负载统计主键
     * @return 结果
     */
    @Override
    public int deleteApsGasPipingRouteStatByIds(String[] ids)
    {
        return apsGasPipingRouteStatMapper.deleteApsGasPipingRouteStatByIds(ids);
    }
 
    /**
     * 删除气体管路产能负载统计信息
     * 
     * @param id 气体管路产能负载统计主键
     * @return 结果
     */
    @Override
    public int deleteApsGasPipingRouteStatById(String id)
    {
        return apsGasPipingRouteStatMapper.deleteApsGasPipingRouteStatById(id);
    }
 
    @Override
    public boolean computeCapacity() {
//        PageHelper.startPage(1, 500);
        List<ApsGasPipingPlan> apsGasPipingPlans = apsGasPipingPlanMapper.selectApsGasPipingPlanWithProcess(new ApsGasPipingPlan());
        List<ApsGasPipingRouteStat> apsGasPipingRouteStatList = new ArrayList<>();
        /*本次计算批次号*/
        String batchNum = IdUtils.fastSimpleUUID();
        try {
            apsGasPipingPlans.forEach(apsGasPipingPlan -> {
                List<ApsProcessRoute> apsProcessRoutes = apsGasPipingPlan.getApsProcessRoutes();
                //按照工序序号升序排序
                apsProcessRoutes.sort((a, b)->b.getProcessNumber().compareTo(a.getProcessNumber()));
                //是否找到当前工序
                boolean isCurrentProcess = false;
                boolean lastProcessStartTimeIsBeforeNow = false;
                ApsGasPipingRouteStat preApsProcessRoute = null;
                for (int i=0;i<apsProcessRoutes.size();i++){
                    ApsProcessRoute apsProcessRoute = apsProcessRoutes.get(i);
                    ApsGasPipingRouteStat apsGasPipingRouteStat = new ApsGasPipingRouteStat();
                    //工单号
                    apsGasPipingRouteStat.setWorkOrderNo(apsGasPipingPlan.getDocumentNumber());
                    //料号
                    apsGasPipingRouteStat.setItemNumber(apsGasPipingPlan.getItemNumber());
                    //当前工序号
                    apsGasPipingRouteStat.setCurrentProcessNumber(new BigDecimal(apsGasPipingPlan.getProcessNumber()));
                    //生产数量
                    apsGasPipingRouteStat.setProductionQuantity(apsGasPipingPlan.getProductionQuantity());
                    //工序名称
                    apsGasPipingRouteStat.setProcessName(apsProcessRoute.getProcessName());
                    //工序号
                    apsGasPipingRouteStat.setRoadProcessNumber( new BigDecimal(apsProcessRoute.getProcessNumber()) );
                    //标准工时
                    apsGasPipingRouteStat.setStandardTime(apsProcessRoute.getStandardTime());
                    //专业
                    apsGasPipingRouteStat.setMajor(apsGasPipingPlan.getPlanType());
                    //工序总工时 等于 标准工时*生产数量
                    apsGasPipingRouteStat.setProcessTotalTime(apsProcessRoute.getStandardTime().multiply(apsGasPipingPlan.getProductionQuantity()));
                    //计划开工日 如果是当前序
                    if(apsGasPipingPlan.getProcessNumber().equals(apsProcessRoute.getProcessNumber())) {
                        isCurrentProcess = true;
                    }
                    // 上一道工序的结束时间 = 上一道工序的开始时间 + 上一道工序的总工时
                    if(i==0){
                        LocalDate endLocalDate = LocalDate.ofInstant(apsGasPipingPlan.getPlanEndDay().toInstant(), ZoneId.systemDefault());
                        LocalDate nowLocalDate = LocalDate.now();
                        LocalDateTime planEndDay;
                        if(endLocalDate.isBefore(nowLocalDate)){
                            planEndDay = LocalDateTime.now();
                        }else{
                            planEndDay = apsGasPipingPlan.getPlanEndDay().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                        }
                        apsGasPipingRouteStat.setProcessPlanEndDay(Date.from(planEndDay.atZone(ZoneId.systemDefault()).toInstant()));
                        long seconds = apsProcessRoute.getStandardTime().multiply(apsGasPipingPlan.getProductionQuantity()).multiply(new BigDecimal(60)).multiply(new BigDecimal(60)).longValue();
                        LocalDateTime planStartDay = planEndDay.plusSeconds(-seconds);
                        apsGasPipingRouteStat.setProcessPlanStartDay(Date.from(planStartDay.atZone(ZoneId.systemDefault()).toInstant()));
                        if(planStartDay.isBefore(LocalDateTime.now())){
                            lastProcessStartTimeIsBeforeNow = true;
                        }
                    }else{
                        if(lastProcessStartTimeIsBeforeNow){
                            Date now = new Date();
                            apsGasPipingRouteStat.setProcessPlanStartDay(now);
                            apsGasPipingRouteStat.setProcessPlanEndDay(now);
                        }else{
                            apsGasPipingRouteStat.setProcessPlanEndDay(preApsProcessRoute.getProcessPlanStartDay());
                            LocalDateTime planEndDay = preApsProcessRoute.getProcessPlanStartDay().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                            long seconds = apsProcessRoute.getStandardTime().multiply(apsGasPipingPlan.getProductionQuantity()).multiply(new BigDecimal(60)).multiply(new BigDecimal(60)).longValue();
                            LocalDateTime planStartDay = planEndDay.plusSeconds(-seconds);
                            apsGasPipingRouteStat.setProcessPlanStartDay(Date.from(planStartDay.atZone(ZoneId.systemDefault()).toInstant()));
                        }
                    }
                    //插入 年 月 日
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String formattedDate = sdf.format(apsGasPipingRouteStat.getProcessPlanStartDay());
                    String[] dateParts = formattedDate.split("-");
                    apsGasPipingRouteStat.setPlanStartYear(String.valueOf(Integer.parseInt(dateParts[0])));
                    apsGasPipingRouteStat.setPlanStartMonth(String.valueOf(Integer.parseInt(dateParts[1])));
                    apsGasPipingRouteStat.setPlanStartDay(String.valueOf(Integer.parseInt(dateParts[2])));
                    //标准用量 查询物料用量表
//                    ApsGasMaterialUsage apsGasMaterialUsage = new ApsGasMaterialUsage();
//                    apsGasMaterialUsage.setItemNumber(apsGasPipingPlan.getItemNumber());
//                    apsGasMaterialUsage.setProcessName(apsProcessRoute.getProcessName());
//                    List<ApsGasMaterialUsage> apsGasMaterialUsageList = apsGasMaterialUsageService.selectApsGasMaterialUsageList(apsGasMaterialUsage);
//                    apsGasPipingRouteStat.setStandardDosage(apsProcessRoute.getStandardTime().multiply(apsGasPipingPlan.getProductionQuantity()));
                    //工序总用量 = 标准用量*生产数量
//                    apsGasPipingRouteStat.setProcessTotalDosage(apsGasPipingRouteStat.getStandardDosage().multiply(apsGasPipingPlan.getProductionQuantity()));
                    apsGasPipingRouteStat.setCreateTime(DateUtils.getNowDate());
                    apsGasPipingRouteStat.setCreateBy("auto");
                    apsGasPipingRouteStat.setBatchNumber(batchNum);
                    apsGasPipingRouteStat.setId(IdUtils.fastSimpleUUID());
                    apsGasPipingRouteStatList.add(apsGasPipingRouteStat);
                    preApsProcessRoute = apsGasPipingRouteStat;
                    if(isCurrentProcess){
                        break;
                    }
                }
            });
            List<ApsGasPipingRouteStat> tempInsertList = new ArrayList<>();
            for (int i = 0; i < apsGasPipingRouteStatList.size(); i++) {
                tempInsertList.add(apsGasPipingRouteStatList.get(i));
                if(tempInsertList.size()==500){
                    apsGasPipingRouteStatMapper.insertApsGasPipingRouteStatBatch(tempInsertList);
                    tempInsertList = new ArrayList<>();
                }else if(i==apsGasPipingRouteStatList.size()-1){
                    apsGasPipingRouteStatMapper.insertApsGasPipingRouteStatBatch(tempInsertList);
                }
            }
            apsGasPipingRouteStatMapper.deleteApsGasPipingRouteStatByBatchNum(batchNum);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
 
    public JSONObject getCapacityPlanDataBackup(ApsGasPipingRouteStat apsGasPipingRouteStat) {
        JSONObject result = new JSONObject();
        YearMonth yearMonth = YearMonth.parse(apsGasPipingRouteStat.getSearchEndDate());
        int daysInMonth = yearMonth.lengthOfMonth();
        LinkedHashSet<String> startPlanTimeSet = new LinkedHashSet<>();
        //工序分组统计
        LinkedHashMap<String, List<ApsResourceDateStat>> processMap = new LinkedHashMap<>();
        List<HashMap<String, List<ApsResourceDateStat>>> processList = new ArrayList<>();
        try {
            //获取标准工序名称
            ApsStandardProcess apsStandardProcess = new ApsStandardProcess();
            apsStandardProcess.setMajor(apsGasPipingRouteStat.getMajor().equals("gas")?"气柜":"管路");
            List<ApsStandardProcess> apsStandardProcessList = apsStandardProcessService.selectApsStandardProcessList(apsStandardProcess);
            apsStandardProcessList.sort((a, b)->a.getProcessName().compareTo(b.getProcessName()));
            for(ApsStandardProcess temp:apsStandardProcessList){
                processMap.put(temp.getProcessName(), new ArrayList<ApsResourceDateStat>());
            }
            //获取工序计划产能数据
            HashMap<String, ApsGasPipelineCapacityPlan> apsGasPipingPlanMap = new HashMap<>();
            ApsGasPipelineCapacityPlan searchCapacityPlan = new ApsGasPipelineCapacityPlan();
            searchCapacityPlan.setMajor(apsGasPipingRouteStat.getMajor().equals("gas")?"气柜":"管路");
            if("day".equals(apsGasPipingRouteStat.getSearchType())){
                searchCapacityPlan.setYear(yearMonth.getYear()+"");
                searchCapacityPlan.setMonth(yearMonth.getMonthValue()+"");
                for(int i=1;i<=daysInMonth;i++){
                    startPlanTimeSet.add(yearMonth +"-"+ (i<10?"0"+i:i));
                }
            }else if("month".equals(apsGasPipingRouteStat.getSearchType())){
                searchCapacityPlan.setYear(yearMonth.getYear()+"");
                YearMonth start = YearMonth.of(Integer.parseInt(apsGasPipingRouteStat.getSearchStartDate().split("-")[0]), Integer.parseInt(apsGasPipingRouteStat.getSearchStartDate().split("-")[1]));
                YearMonth end = YearMonth.of(Integer.parseInt(apsGasPipingRouteStat.getSearchEndDate().split("-")[0]), Integer.parseInt(apsGasPipingRouteStat.getSearchEndDate().split("-")[1]));
                List<String> yearMonths = getYearMonthsInRange(start, end);
                startPlanTimeSet.addAll(yearMonths);
            }
            List<ApsGasPipelineCapacityPlan> apsGasPipelineCapacityPlanList = apsGasPipelineCapacityPlanMapper.selectApsGasPipelineCapacityPlanList(searchCapacityPlan);
            apsGasPipelineCapacityPlanList.forEach(apsGasPipelineCapacityPlan -> {
                apsGasPipingPlanMap.put(apsGasPipelineCapacityPlan.getProcessName()+"-"+apsGasPipelineCapacityPlan.getYear()+"-"+(Integer.parseInt(apsGasPipelineCapacityPlan.getMonth())<10?"0"+apsGasPipelineCapacityPlan.getMonth():apsGasPipelineCapacityPlan.getMonth()),apsGasPipelineCapacityPlan);
            });
            //计算日产能数据
            DateTimeFormatter formatter = null;
            List<ApsGasPipingRouteStat> apsGasPipingRouteStats;
            SimpleDateFormat simpleDateFormat = null;
            apsGasPipingRouteStat.setSearchStartDate(apsGasPipingRouteStat.getSearchStartDate()+"-01 00:00:00");
            apsGasPipingRouteStat.setSearchEndDate(apsGasPipingRouteStat.getSearchEndDate()+"-"+ daysInMonth +" 23:59:59");
            if("day".equals(apsGasPipingRouteStat.getSearchType())){
                formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            }else if("month".equals(apsGasPipingRouteStat.getSearchType())){
                formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            }
            ApsGasPipingRouteStat queryStatParam = new ApsGasPipingRouteStat();
            BeanUtils.copyProperties(apsGasPipingRouteStat,queryStatParam);
            queryStatParam.setMajor("");
            apsGasPipingRouteStats = apsGasPipingRouteStatMapper.selectApsGasPipingRouteStatList(queryStatParam);
            //根据开工日进行升序排序
            apsGasPipingRouteStats.sort((a, b)->a.getProcessPlanStartDay().compareTo(b.getProcessPlanStartDay()));
            //工序开工日期
            String planStartDate = "";
            //统计所有工序对应的开工时间
            for (ApsGasPipingRouteStat apsGasPipingRouteStatTemp : apsGasPipingRouteStats) {
                if(processMap.containsKey(apsGasPipingRouteStatTemp.getProcessName())){
                    planStartDate = simpleDateFormat.format(apsGasPipingRouteStatTemp.getProcessPlanStartDay());
                    if("month".equals(apsGasPipingRouteStat.getSearchType())){
                        planStartDate = planStartDate+"-01";
                    }
                    ApsResourceDateStat apsResourceDateStat = new ApsResourceDateStat();
                    apsResourceDateStat.setPlanDay(LocalDate.parse(planStartDate, formatter));
                    apsResourceDateStat.setResourceName(apsGasPipingRouteStatTemp.getProcessName());
                    //查询气柜管路产能规划表
                    apsResourceDateStat.setDesignTimes(apsGasPipingPlanMap.get(apsGasPipingRouteStatTemp.getProcessName()+"-"+planStartDate.substring(0, 7))!=null?apsGasPipingPlanMap.get(apsGasPipingRouteStatTemp.getProcessName()+"-"+planStartDate.substring(0, 7)).getDayProduceAllNum():new BigDecimal(0));
                    //查询料号工序产能表
                    apsResourceDateStat.setRequireTimes(apsGasPipingRouteStatTemp.getProcessTotalTime());
                    if(apsResourceDateStat.getDesignTimes().compareTo(BigDecimal.ZERO)>0){
                        apsResourceDateStat.setCapacityLoad(apsResourceDateStat.getRequireTimes()
                                .divide(apsResourceDateStat.getDesignTimes(), 2, RoundingMode.HALF_UP)
                                .multiply(new BigDecimal(100)));
                    }else{
                        apsResourceDateStat.setCapacityLoad(BigDecimal.valueOf(0));
                    }
                   // apsResourceDateStatList = new ArrayList<>();
 
                    List<ApsResourceDateStat>   apsResourceDateStatList = processMap.get(apsGasPipingRouteStatTemp.getProcessName());
                    apsResourceDateStatList.add(apsResourceDateStat);
                    processMap.put(apsGasPipingRouteStatTemp.getProcessName(), apsResourceDateStatList);
                }
 
            }
            //聚合每道工序的开工时间和产能
            processMap.forEach((processName, apsResourceDateStatList) -> {
                LinkedHashMap<String, ApsResourceDateStat> dayMap = new LinkedHashMap<>();
                apsResourceDateStatList.forEach(apsResourceDateStat -> {
//                    startPlanTimeSet.add(apsResourceDateStat.getPlanDay().toString());
                    if(dayMap.containsKey(apsResourceDateStat.getPlanDay().toString())){
                        ApsResourceDateStat apsResourceDateStatTemp = dayMap.get(apsResourceDateStat.getPlanDay().toString());
                        if("month".equals(apsGasPipingRouteStat.getSearchType())){
                            apsResourceDateStatTemp.setDesignTimes(apsGasPipingPlanMap.get(processName+"-"+apsResourceDateStat.getPlanDay().toString().substring(0,7))!=null?apsGasPipingPlanMap.get(processName+"-"+apsResourceDateStat.getPlanDay().toString().substring(0,7)).getMonthProduceAllNum():new BigDecimal(0));
                        }else{
                            apsResourceDateStatTemp.setDesignTimes(apsGasPipingPlanMap.get(processName+"-"+apsResourceDateStat.getPlanDay().toString().substring(0,7))!=null?apsGasPipingPlanMap.get(processName+"-"+apsResourceDateStat.getPlanDay().toString().substring(0,7)).getDayProduceAllNum():new BigDecimal(0));
                        }
                        apsResourceDateStatTemp.setRequireTimes(apsResourceDateStatTemp.getRequireTimes().add(apsResourceDateStat.getRequireTimes()));
                        if(apsResourceDateStatTemp.getDesignTimes().compareTo(BigDecimal.ZERO) > 0){
                            apsResourceDateStatTemp.setCapacityLoad(apsResourceDateStatTemp.getRequireTimes()
                                    .divide(apsResourceDateStatTemp.getDesignTimes(), 2, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal(100)));
                        }else{
                            apsResourceDateStatTemp.setCapacityLoad(new BigDecimal(0));
                        }
                        apsResourceDateStatTemp.setResourceGroupName(processName);
                        apsResourceDateStatTemp.setPlanDay(apsResourceDateStat.getPlanDay());
                        dayMap.put(apsResourceDateStat.getPlanDay().toString(), apsResourceDateStatTemp);
                    }else{
                        dayMap.put(apsResourceDateStat.getPlanDay().toString(), apsResourceDateStat);
                    }
                });
                List<ApsResourceDateStat> tempList = new ArrayList<>();
                dayMap.forEach((key, value) -> {
                    tempList.add(value);
                });
                HashMap<String, List<ApsResourceDateStat>> temp = new HashMap<>();
                temp.put(processName, tempList);
                processList.add(temp);
            });
            //排序时间标题
            List<String> sortedStartPlanTimeList = new ArrayList<>(startPlanTimeSet);
            Collections.sort(sortedStartPlanTimeList);
            for (int i=0;i<processList.size();i++){
                HashMap<String, List<ApsResourceDateStat>> temp = processList.get(i);
                for (Map.Entry<String, List<ApsResourceDateStat>> entry : temp.entrySet()){
                    List<ApsResourceDateStat> apsResourceDateStatList = entry.getValue();
                    String key = entry.getKey();
                    List<ApsResourceDateStat> crtList = new ArrayList<>();
                    for(String tempTime:sortedStartPlanTimeList) {
                        if("month".equals(apsGasPipingRouteStat.getSearchType())){
                            tempTime += "-01";
                        }
                        LocalDate crtDate = LocalDate.parse(tempTime, formatter);
                        Optional<ApsResourceDateStat> first = apsResourceDateStatList.stream().filter(x -> x.getPlanDay().equals(crtDate)).findFirst();
                        if (first.isPresent()) {
                            ApsResourceDateStat apsResourceDateStat = first.get();
                            crtList.add(apsResourceDateStat);
                        } else {
                            ApsResourceDateStat apsResourceDateStat = new ApsResourceDateStat();
                            apsResourceDateStat.setPlanDay(LocalDate.parse(tempTime, formatter));
                            if ("month".equals(apsGasPipingRouteStat.getSearchType())) {
                                apsResourceDateStat.setDesignTimes(apsGasPipingPlanMap.get(entry.getKey()+"-"+tempTime.substring(0,7)) != null ? apsGasPipingPlanMap.get(entry.getKey()+"-"+tempTime.substring(0,7)).getMonthProduceAllNum() : new BigDecimal(0));
                            } else {
                                apsResourceDateStat.setDesignTimes(apsGasPipingPlanMap.get(entry.getKey()+"-"+tempTime.substring(0,7)) != null ? apsGasPipingPlanMap.get(entry.getKey()+"-"+tempTime.substring(0,7)).getDayProduceAllNum() : new BigDecimal(0));
                            }
                            apsResourceDateStat.setRequireTimes(new BigDecimal(0));
                            apsResourceDateStat.setCapacityLoad(new BigDecimal(0));
                            apsResourceDateStat.setResourceName(entry.getKey());
                            apsResourceDateStat.setResourceGroupName(entry.getKey());
                            apsResourceDateStatList.add(apsResourceDateStat);
                            crtList.add(apsResourceDateStat);
                        }
                        temp.put(entry.getKey(), crtList);
                        processList.set(i, temp);
                    }
                }
            }
            result.put("planTable", processList);
            result.put("planTitle", sortedStartPlanTimeList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
 
    @Override
    public JSONObject getCapacityPlanData(ApsGasPipingRouteStat apsGasPipingRouteStat) {
        JSONObject result = new JSONObject();
        YearMonth yearMonth = YearMonth.parse(apsGasPipingRouteStat.getSearchEndDate());
        int daysInMonth = yearMonth.lengthOfMonth();
        LinkedHashSet<String> startPlanTimeSet = new LinkedHashSet<>();
        //工序分组统计
        LinkedHashMap<String, List<ApsResourceDateStat>> processMap = new LinkedHashMap<>();
        List<HashMap<String, List<ApsResourceDateStat>>> processList = new ArrayList<>();
        try {
            //获取标准工序名称
            ApsStandardProcess apsStandardProcess = new ApsStandardProcess();
            apsStandardProcess.setMajor(apsGasPipingRouteStat.getMajor().equals("gas")?"气柜":"管路");
            List<ApsStandardProcess> apsStandardProcessList = apsStandardProcessService.selectApsStandardProcessList(apsStandardProcess);
            apsStandardProcessList.sort((a, b)->a.getProcessName().compareTo(b.getProcessName()));
            for(ApsStandardProcess temp:apsStandardProcessList){
                processMap.put(temp.getProcessName(), new ArrayList<ApsResourceDateStat>());
            }
            //获取工序计划产能数据
            HashMap<String, ApsGasPipelineCapacityPlan> apsGasPipingPlanMap = new HashMap<>();
            ApsGasPipelineCapacityPlan searchCapacityPlan = new ApsGasPipelineCapacityPlan();
            searchCapacityPlan.setMajor(apsGasPipingRouteStat.getMajor().equals("gas")?"气柜":"管路");
            if("day".equals(apsGasPipingRouteStat.getSearchType())){
                searchCapacityPlan.setYear(yearMonth.getYear()+"");
                searchCapacityPlan.setMonth(yearMonth.getMonthValue()+"");
                for(int i=1;i<=daysInMonth;i++){
                    startPlanTimeSet.add(yearMonth +"-"+ (i<10?"0"+i:i));
                }
            }else if("month".equals(apsGasPipingRouteStat.getSearchType())){
                searchCapacityPlan.setYear(yearMonth.getYear()+"");
                YearMonth start = YearMonth.of(Integer.parseInt(apsGasPipingRouteStat.getSearchStartDate().split("-")[0]), Integer.parseInt(apsGasPipingRouteStat.getSearchStartDate().split("-")[1]));
                YearMonth end = YearMonth.of(Integer.parseInt(apsGasPipingRouteStat.getSearchEndDate().split("-")[0]), Integer.parseInt(apsGasPipingRouteStat.getSearchEndDate().split("-")[1]));
                List<String> yearMonths = getYearMonthsInRange(start, end);
                startPlanTimeSet.addAll(yearMonths);
            }
            List<ApsGasPipelineCapacityPlan> apsGasPipelineCapacityPlanList = apsGasPipelineCapacityPlanMapper.selectApsGasPipelineCapacityPlanList(searchCapacityPlan);
            apsGasPipelineCapacityPlanList.forEach(apsGasPipelineCapacityPlan -> {
                String key = apsGasPipelineCapacityPlan.getProcessName() + "-" + apsGasPipelineCapacityPlan.getOrgCode() + "-" + apsGasPipelineCapacityPlan.getYear() + "-" + (Integer.parseInt(apsGasPipelineCapacityPlan.getMonth())<10?"0"+apsGasPipelineCapacityPlan.getMonth():apsGasPipelineCapacityPlan.getMonth());
                apsGasPipingPlanMap.put(key, apsGasPipelineCapacityPlan);
            });
            //计算日产能数据
            DateTimeFormatter formatter = null;
            List<ApsGasPipingRouteStat> apsGasPipingRouteStats;
            SimpleDateFormat simpleDateFormat = null;
            apsGasPipingRouteStat.setSearchStartDate(apsGasPipingRouteStat.getSearchStartDate()+"-01 00:00:00");
            apsGasPipingRouteStat.setSearchEndDate(apsGasPipingRouteStat.getSearchEndDate()+"-"+ daysInMonth +" 23:59:59");
            if("day".equals(apsGasPipingRouteStat.getSearchType())){
                formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            }else if("month".equals(apsGasPipingRouteStat.getSearchType())){
                formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            }
            ApsGasPipingRouteStat queryStatParam = new ApsGasPipingRouteStat();
            BeanUtils.copyProperties(apsGasPipingRouteStat,queryStatParam);
            queryStatParam.setMajor("");
            apsGasPipingRouteStats = apsGasPipingRouteStatMapper.selectApsGasPipingRouteStatList(queryStatParam);
            //根据开工日进行升序排序
            apsGasPipingRouteStats.sort((a, b)->a.getProcessPlanStartDay().compareTo(b.getProcessPlanStartDay()));
            //工序开工日期
            String planStartDate = "";
            //统计所有工序对应的开工时间
            for (ApsGasPipingRouteStat apsGasPipingRouteStatTemp : apsGasPipingRouteStats) {
                if(processMap.containsKey(apsGasPipingRouteStatTemp.getProcessName())){
                    planStartDate = simpleDateFormat.format(apsGasPipingRouteStatTemp.getProcessPlanStartDay());
                    if("month".equals(apsGasPipingRouteStat.getSearchType())){
                        planStartDate = planStartDate+"-01";
                    }
                    ApsResourceDateStat apsResourceDateStat = new ApsResourceDateStat();
                    apsResourceDateStat.setPlanDay(LocalDate.parse(planStartDate, formatter));
                    apsResourceDateStat.setResourceName(apsGasPipingRouteStatTemp.getProcessName());
                    apsResourceDateStat.setPlant(apsGasPipingRouteStatTemp.getPlant());
                    //查询气柜管路产能规划表
                    String capacityKey = apsGasPipingRouteStatTemp.getProcessName() + "-" + apsGasPipingRouteStatTemp.getPlant() + "-" + planStartDate.substring(0, 7);
                    apsResourceDateStat.setDesignTimes(apsGasPipingPlanMap.get(capacityKey)!=null?apsGasPipingPlanMap.get(capacityKey).getDayProduceAllNum():new BigDecimal(0));
                    //查询料号工序产能表
                    apsResourceDateStat.setRequireTimes(apsGasPipingRouteStatTemp.getProcessTotalTime());
                    if(apsResourceDateStat.getDesignTimes().compareTo(BigDecimal.ZERO)>0){
                        apsResourceDateStat.setCapacityLoad(apsResourceDateStat.getRequireTimes()
                                .divide(apsResourceDateStat.getDesignTimes(), 2, RoundingMode.HALF_UP)
                                .multiply(new BigDecimal(100)));
                    }else{
                        apsResourceDateStat.setCapacityLoad(BigDecimal.valueOf(0));
                    }
 
                    List<ApsResourceDateStat> apsResourceDateStatList = processMap.get(apsGasPipingRouteStatTemp.getProcessName());
                    apsResourceDateStatList.add(apsResourceDateStat);
                    processMap.put(apsGasPipingRouteStatTemp.getProcessName(), apsResourceDateStatList);
                }
            }
            //聚合每道工序的开工时间和产能
            for (Map.Entry<String, List<ApsResourceDateStat>> entry : processMap.entrySet()) {
                String processName = entry.getKey();
                List<ApsResourceDateStat> apsResourceDateStatList = entry.getValue();
 
                if("day".equals(apsGasPipingRouteStat.getSearchType())) {
                    // 按天统计时保持原有逻辑,不按工厂分组
                    LinkedHashMap<String, ApsResourceDateStat> dayMap = new LinkedHashMap<>();
 
                    // 首先,为所有日期创建初始记录
                    for(String date : startPlanTimeSet) {
                        ApsResourceDateStat initStat = new ApsResourceDateStat();
                        initStat.setPlanDay(LocalDate.parse(date, formatter));
                        initStat.setResourceName(processName);
                        initStat.setResourceGroupName(processName);
                        initStat.setRequireTimes(new BigDecimal(0));
                        String capacityKey = processName + "-" + date.substring(0,7);
                        initStat.setDesignTimes(apsGasPipingPlanMap.get(capacityKey)!=null?apsGasPipingPlanMap.get(capacityKey).getDayProduceAllNum():new BigDecimal(0));
                        initStat.setCapacityLoad(new BigDecimal(0));
                        dayMap.put(date, initStat);
                    }
 
                    // 然后处理实际数据
                    for (ApsResourceDateStat apsResourceDateStat : apsResourceDateStatList) {
                        String dateKey = apsResourceDateStat.getPlanDay().toString();
                        if(dayMap.containsKey(dateKey)){
                            ApsResourceDateStat apsResourceDateStatTemp = dayMap.get(dateKey);
                            String capacityKey = processName + "-" + dateKey.substring(0,7);
                            apsResourceDateStatTemp.setDesignTimes(apsGasPipingPlanMap.get(capacityKey)!=null?apsGasPipingPlanMap.get(capacityKey).getDayProduceAllNum():new BigDecimal(0));
                            apsResourceDateStatTemp.setRequireTimes(apsResourceDateStatTemp.getRequireTimes().add(apsResourceDateStat.getRequireTimes()));
                            if(apsResourceDateStatTemp.getDesignTimes().compareTo(BigDecimal.ZERO) > 0){
                                apsResourceDateStatTemp.setCapacityLoad(apsResourceDateStatTemp.getRequireTimes()
                                        .divide(apsResourceDateStatTemp.getDesignTimes(), 2, RoundingMode.HALF_UP)
                                        .multiply(new BigDecimal(100)));
                            }else{
                                apsResourceDateStatTemp.setCapacityLoad(new BigDecimal(0));
                            }
                            apsResourceDateStatTemp.setResourceGroupName(processName);
                            apsResourceDateStatTemp.setPlanDay(apsResourceDateStat.getPlanDay());
                            dayMap.put(dateKey, apsResourceDateStatTemp);
                        }
                    }
 
                    List<ApsResourceDateStat> tempList = new ArrayList<>(dayMap.values());
                    HashMap<String, List<ApsResourceDateStat>> temp = new HashMap<>();
                    temp.put(processName, tempList);
                    processList.add(temp);
                } else {
                    // 按月统计时才按工厂分组
                    if (apsResourceDateStatList.isEmpty()) {
                        // 从产能规划数据中获取所有的工厂
                        Set<String> plants = apsGasPipelineCapacityPlanList.stream()
                                .filter(plan -> plan.getProcessName().equals(processName))
                                .map(ApsGasPipelineCapacityPlan::getOrgCode)
                                .filter(orgCode -> orgCode != null && !orgCode.trim().isEmpty())
                                .collect(Collectors.toSet());
 
                        // 如果没有找到任何有效工厂,跳过这个工序
                        if (plants.isEmpty()) {
                            continue;
                        }
 
                        // 为每个工厂创建空记录
                        for (String plant : plants) {
                            LinkedHashMap<String, ApsResourceDateStat> dayMap = new LinkedHashMap<>();
                            // 为每个月份创建记录
                            for(String monthDate : startPlanTimeSet) {
                                String tempTime = monthDate + "-01";
                                ApsResourceDateStat apsResourceDateStat = new ApsResourceDateStat();
                                apsResourceDateStat.setPlanDay(LocalDate.parse(tempTime, formatter));
                                apsResourceDateStat.setResourceName(processName);
                                apsResourceDateStat.setResourceGroupName(processName + "-" + plant);
                                apsResourceDateStat.setPlant(plant);
                                apsResourceDateStat.setRequireTimes(new BigDecimal(0));
                                String capacityKey = processName + "-" + plant + "-" + monthDate;
                                apsResourceDateStat.setDesignTimes(apsGasPipingPlanMap.get(capacityKey)!=null?apsGasPipingPlanMap.get(capacityKey).getMonthProduceAllNum():new BigDecimal(0));
                                apsResourceDateStat.setCapacityLoad(new BigDecimal(0));
                                dayMap.put(monthDate, apsResourceDateStat);
                            }
                            List<ApsResourceDateStat> tempList = new ArrayList<>(dayMap.values());
                            HashMap<String, List<ApsResourceDateStat>> temp = new HashMap<>();
                            temp.put(processName + "_" + plant, tempList);
                            processList.add(temp);
                        }
                    } else {
                        // 按工厂分组,并过滤掉plant为null或空字符串的记录
                        Map<String, List<ApsResourceDateStat>> plantGroups = apsResourceDateStatList.stream()
                                .filter(stat -> stat.getPlant() != null && !stat.getPlant().trim().isEmpty())
                                .collect(groupingBy(ApsResourceDateStat::getPlant));
 
                        // 如果过滤后没有有效的工厂数据,跳过这个工序
                        if (plantGroups.isEmpty()) {
                            continue;
                        }
 
                        // 对每个工厂的数据进行处理
                        for (Map.Entry<String, List<ApsResourceDateStat>> plantEntry : plantGroups.entrySet()) {
                            String plant = plantEntry.getKey();
                            // 再次确认plant不为空
                            if (plant == null || plant.trim().isEmpty()) {
                                continue;
                            }
                            List<ApsResourceDateStat> plantStats = plantEntry.getValue();
                            LinkedHashMap<String, ApsResourceDateStat> dayMap = new LinkedHashMap<>();
 
                            // 首先为所有月份创建初始记录
                            for(String monthDate : startPlanTimeSet) {
                                String tempTime = monthDate + "-01";
                                ApsResourceDateStat initStat = new ApsResourceDateStat();
                                initStat.setPlanDay(LocalDate.parse(tempTime, formatter));
                                initStat.setResourceName(processName);
                                initStat.setResourceGroupName(processName + "-" + plant);
                                initStat.setPlant(plant);
                                initStat.setRequireTimes(new BigDecimal(0));
                                String capacityKey = processName + "-" + plant + "-" + monthDate;
                                initStat.setDesignTimes(apsGasPipingPlanMap.get(capacityKey)!=null?apsGasPipingPlanMap.get(capacityKey).getMonthProduceAllNum():new BigDecimal(0));
                                initStat.setCapacityLoad(new BigDecimal(0));
                                dayMap.put(monthDate, initStat);
                            }
 
                            // 然后处理实际数据
                            for (ApsResourceDateStat stat : plantStats) {
                                String monthKey = stat.getPlanDay().toString().substring(0, 7);
                                if (dayMap.containsKey(monthKey)) {
                                    ApsResourceDateStat existingStat = dayMap.get(monthKey);
                                    String capacityKey = processName + "-" + plant + "-" + monthKey;
                                    existingStat.setDesignTimes(apsGasPipingPlanMap.get(capacityKey)!=null?apsGasPipingPlanMap.get(capacityKey).getMonthProduceAllNum():new BigDecimal(0));
                                    existingStat.setRequireTimes(existingStat.getRequireTimes().add(stat.getRequireTimes()));
                                    if(existingStat.getDesignTimes().compareTo(BigDecimal.ZERO) > 0){
                                        existingStat.setCapacityLoad(existingStat.getRequireTimes()
                                                .divide(existingStat.getDesignTimes(), 2, RoundingMode.HALF_UP)
                                                .multiply(new BigDecimal(100)));
                                    }
                                }
                            }
 
                            List<ApsResourceDateStat> tempList = new ArrayList<>(dayMap.values());
                            HashMap<String, List<ApsResourceDateStat>> temp = new HashMap<>();
                            temp.put(processName + "_" + plant, tempList);
                            processList.add(temp);
                        }
                    }
                }
            }
            //排序时间标题
            List<String> sortedStartPlanTimeList = new ArrayList<>(startPlanTimeSet);
            Collections.sort(sortedStartPlanTimeList);
            for (int i=0;i<processList.size();i++){
                HashMap<String, List<ApsResourceDateStat>> temp = processList.get(i);
                for (Map.Entry<String, List<ApsResourceDateStat>> entry : temp.entrySet()){
                    List<ApsResourceDateStat> apsResourceDateStatList = entry.getValue();
                    String key = entry.getKey();
                    List<ApsResourceDateStat> crtList = new ArrayList<>();
                    for(String tempTime:sortedStartPlanTimeList) {
                        if("month".equals(apsGasPipingRouteStat.getSearchType())){
                            tempTime += "-01";
                        }
                        LocalDate crtDate = LocalDate.parse(tempTime, formatter);
                        Optional<ApsResourceDateStat> first = apsResourceDateStatList.stream().filter(x -> x.getPlanDay().equals(crtDate)).findFirst();
                        if (first.isPresent()) {
                            ApsResourceDateStat apsResourceDateStat = first.get();
                            crtList.add(apsResourceDateStat);
                        } else {
                            ApsResourceDateStat apsResourceDateStat = new ApsResourceDateStat();
                            apsResourceDateStat.setPlanDay(LocalDate.parse(tempTime, formatter));
                            String[] keyParts = key.split("-");
                            String processNamePart = keyParts[0];
                            String plantPart = keyParts[1];
                            String capacityKey = processNamePart + "-" + plantPart + "-" + tempTime.substring(0,7);
                            if ("month".equals(apsGasPipingRouteStat.getSearchType())) {
                                apsResourceDateStat.setDesignTimes(apsGasPipingPlanMap.get(capacityKey) != null ? apsGasPipingPlanMap.get(capacityKey).getMonthProduceAllNum() : new BigDecimal(0));
                            } else {
                                apsResourceDateStat.setDesignTimes(apsGasPipingPlanMap.get(capacityKey) != null ? apsGasPipingPlanMap.get(capacityKey).getDayProduceAllNum() : new BigDecimal(0));
                            }
                            apsResourceDateStat.setRequireTimes(new BigDecimal(0));
                            apsResourceDateStat.setCapacityLoad(new BigDecimal(0));
                            apsResourceDateStat.setResourceName(processNamePart);
                            apsResourceDateStat.setResourceGroupName(key);
                            apsResourceDateStat.setPlant(plantPart);
                            apsResourceDateStatList.add(apsResourceDateStat);
                            crtList.add(apsResourceDateStat);
                        }
                        temp.put(entry.getKey(), crtList);
                        processList.set(i, temp);
                    }
                }
            }
            result.put("planTable", processList);
            result.put("planTitle", sortedStartPlanTimeList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
 
    @Override
    public void exportExcel(HttpServletResponse response, ApsGasPipingRouteStat apsGasPipingRouteStat) {
        SXSSFWorkbook wb = new SXSSFWorkbook(500);
        wb.createSheet();
        wb.setSheetName(0, "气柜管路产能负载统计表");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
 
        Map<String, CellStyle> styles = createStyles(wb);
        CellStyle title = styles.get("title");
        try
        {
            JSONObject stat = getCapacityPlanData(apsGasPipingRouteStat);
            List<String> days = (List<String>) stat.get("planTitle");
            List<HashMap<String, List<ApsResourceDateStat>>> table= (List<HashMap<String, List<ApsResourceDateStat>>>) stat.get("planTable");
            SXSSFSheet sheet = wb.getSheetAt(0);
            /*填写日期列 和 工时列*/
            SXSSFRow rowDay = sheet.createRow(0);
            SXSSFRow rowTitle = sheet.createRow(1);
 
            SXSSFCell daytitle = rowDay.createCell(0);
            daytitle.setCellValue("日期");
            daytitle.setCellStyle(title);
            SXSSFCell titleCell = rowTitle.createCell(0);
            titleCell.setCellValue("工序");
            titleCell.setCellStyle(title);
 
            for (int i = 0; i < days.size(); i++) {
                SXSSFCell dateCell = rowDay.createCell(i * 3 + 1);
                SXSSFCell designHoursCell = rowTitle.createCell(i * 3 + 1);
                SXSSFCell requireHoursCell = rowTitle.createCell(i * 3 + 2);
                SXSSFCell loadCell = rowTitle.createCell(i * 3 + 3);
                dateCell.setCellValue(days.get(i));
                designHoursCell.setCellValue("设计工时");
                requireHoursCell.setCellValue("需求工时");
                loadCell.setCellValue("产能负荷");
                /*set cell style*/
                dateCell.setCellStyle(title);
                designHoursCell.setCellStyle(title);
                requireHoursCell.setCellStyle(title);
                loadCell.setCellStyle(title);
 
                /*合并日期单元格*/
                sheet.addMergedRegion( new CellRangeAddress(0, 0, i*3+1, i*3+3));
            }
            for (int i = 0; i < table.size(); i++) {
                Map<String, List<ApsResourceDateStat>> resourceList = table.get(i);
                /*创建数据行*/
                SXSSFRow dataRow  = sheet.createRow(i+2);
                for( Map.Entry<String, List<ApsResourceDateStat>> entry : resourceList.entrySet()){
                    String resourceName = entry.getKey();
                    List<ApsResourceDateStat> resourceDateStats = entry.getValue();
                    dataRow.createCell(0).setCellValue(resourceName);
                    for (int j = 0; j < resourceDateStats.size(); j++) {
                        ApsResourceDateStat apsResourceDateStat = resourceDateStats.get(j);
                        dataRow.createCell(j*3+1).setCellValue(apsResourceDateStat.getDesignTimes().doubleValue());
                        dataRow.createCell(j*3+2).setCellValue(apsResourceDateStat.getRequireTimes().doubleValue());
                        if(apsResourceDateStat.getCapacityLoad()!=null){
                            dataRow.createCell(j*3+3).setCellValue(apsResourceDateStat.getCapacityLoad().doubleValue()+"%");
                        }else{
                            dataRow.createCell(j*3+3).setCellValue("%");
                        }
                    }
                }
 
            }
            wb.write(response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("导出Excel异常{}", e.getMessage());
        }
        finally
        {
            IOUtils.closeQuietly(wb);
        }
    }
    private Map<String,CellStyle> createStyles(SXSSFWorkbook wb)
    {
        Map<String,CellStyle> styles=new HashMap<>();
        CellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        Font titleFont = wb.createFont();
        titleFont.setFontName("Arial");
        titleFont.setFontHeightInPoints((short) 12);
        titleFont.setBold(true);
        style.setFont(titleFont);
        DataFormat dataFormat = wb.createDataFormat();
        style.setDataFormat(dataFormat.getFormat("@"));
        styles.put("title", style);
        return styles;
    }
 
    public static List<String> getYearMonthsInRange(YearMonth start, YearMonth end) {
        List<String> yearMonths = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
 
        while (!start.isAfter(end)) {
            yearMonths.add(start.format(formatter));
            start = start.plusMonths(1);
        }
 
        return yearMonths;
    }
 
    @Override
    public void saveGasPipingProcessStat(){
        try {
            String batchNum = IdUtils.fastSimpleUUID();
            List<ApsGasPipingRouteStat> tempList = apsGasPipingRouteStatMapper.queryTempStat();
            Map<String, List<ApsGasPipingRouteStat>> groupByOrderNo = tempList.stream().collect(groupingBy(ApsGasPipingRouteStat::getWorkOrderNo));
            Boolean hasBefore = false;
            LocalDateTime now = LocalDateTime.now();
            for (Map.Entry<String, List<ApsGasPipingRouteStat>> entry : groupByOrderNo.entrySet()) {
                List<ApsGasPipingRouteStat> statPerOrder = entry.getValue();
                /*num 为根据完工时间排序出的序号,按此排序,可保证是按完工时间倒叙排列*/
                statPerOrder.sort((a, b)->a.getNum().compareTo(b.getNum()));
                ApsGasPipingRouteStat last=null;
                for (int i = 0; i <statPerOrder.size(); i++) {
                    ApsGasPipingRouteStat stat = statPerOrder.get(i);
                    stat.setId(IdUtils.fastSimpleUUID());
                    stat.setBatchNumber(batchNum);
                    stat.setCreateBy(SecurityUtils.getUsername());
                    stat.setWarning(false);
                    if(i==0){
                        Date orderPlanEndDay = stat.getOrderPlanEndDay();
                        LocalDateTime transLocalDateTime = transLocalDateTime(orderPlanEndDay);
                        LocalTime endOfDay = LocalTime.of(23, 59, 59);
                        LocalDateTime orderPlanEndDayLocalDateTime =  LocalDateTime.of( transLocalDateTime.toLocalDate(), endOfDay);
                        if(orderPlanEndDayLocalDateTime.isBefore(now)){
                            hasBefore = true;
                            stat.setWarning(true);
                            stat.setProcessPlanEndDay(transDate(now));
                            stat.setProcessPlanStartDay(transDate(now));
                        }else {
                            /*计划完工日=钣金计划工单完成时间*/
                            stat.setProcessPlanEndDay(transDate(orderPlanEndDayLocalDateTime));
                            /*计划开工日=钣金计划工单完成时间 -  工序总工时*/
                            long seconds = stat.getProcessTotalTime().multiply(new BigDecimal(60)).multiply(new BigDecimal(60)).longValue();
                            LocalDateTime lastPlanStartDt = orderPlanEndDayLocalDateTime.minusSeconds(seconds);
                            if(lastPlanStartDt.isBefore(now)){
                                hasBefore = true;
                                stat.setProcessPlanStartDay(transDate(now));
                            }else {
                                stat.setProcessPlanStartDay(transDate(lastPlanStartDt));
                            }
                        }
                    }
                    /*当工艺工序号 >= 工单当前工序 代表是未来工序,才进行计划开工日 和计划完工日的计算
                     * 当工艺工序号 < 工单当前工序  过去工序,不进行计算
                     * */
                    if( stat.getRouteProcessNumber().compareTo(stat.getCurrentProcessNumber())>=0){
                        /*倒排时 下一道工序存在 比当前时间小的计划时间,则当前计划开始和结束时间都是当前时间*/
                        if(hasBefore){
                            stat.setWarning(true);
                            stat.setProcessPlanEndDay(transDate(now));
                            stat.setProcessPlanStartDay(transDate(now));
                        }else{
                            /*下一道工序计划时间都正常时,*/
                            if (last != null) {
                                /*当前工序结束时间=下一道工序的开始时间*/
                                stat.setProcessPlanEndDay(last.getProcessPlanStartDay());
                                /*开始时间=结束时间-总工时*/
                                long seconds = stat.getProcessTotalTime().multiply(new BigDecimal(60)).multiply(new BigDecimal(60)).longValue();
                                LocalDateTime crtStartDt = transLocalDateTime(last.getProcessPlanStartDay()).minusSeconds(seconds);
                                /*如果开始时间小于当前时间*/
                                if(crtStartDt.isBefore(now)){
                                    hasBefore=true;
                                    stat.setWarning(true);
                                    stat.setProcessPlanStartDay(transDate(now));
                                }else {
                                    stat.setProcessPlanStartDay(transDate(crtStartDt));
                                }
                            }
                        }
                    }
                    last = stat;
                    apsGasPipingRouteStatMapper.insertApsGasPipingRouteStat(stat);
                }
                hasBefore=false;
 
            }
            apsGasPipingRouteStatMapper.deleteApsGasPipingRouteStatByBatchNum(batchNum);
        } catch (Exception e) {
            e.printStackTrace();
        }
    };
 
    private Date transDate(LocalDateTime localDateTime){
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }
 
    private LocalDateTime transLocalDateTime(Date date){
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }
 
    /**
     * 保存钣金统计数据
     */
    @Transactional
    @Override
    public void saveGasPipingRoutStateList() {
        String batchNum = IdUtils.fastSimpleUUID();
        List<ApsGasPipingRouteStat> tempList = apsGasPipingRouteStatMapper.queryTempStat();
        Map<String, List<ApsGasPipingRouteStat>> groupByOrderNo = tempList.stream().collect(groupingBy(ApsGasPipingRouteStat::getWorkOrderNo));
 
        LocalDateTime now = LocalDateTime.now();
        /*待保存的数据*/
        List<ApsGasPipingRouteStat> cptStateList = new ArrayList<>();
        for (Map.Entry<String, List<ApsGasPipingRouteStat>> entry : groupByOrderNo.entrySet()) {
            List<ApsGasPipingRouteStat> statPerOrder = entry.getValue();
            /*num 为根据完工时间排序出的序号,按此排序,可保证是按完工时间倒叙排列*/
            statPerOrder.sort((a, b)->a.getNum().compareTo(b.getNum()));
            ApsGasPipingRouteStat last=null;
            /*当前工序是否存在 计划开工时间 小于 当前的时间,如果存在后续设置为当前时间*/
            boolean hasBefore = false;
            for (int i = 0; i <statPerOrder.size(); i++) {
                ApsGasPipingRouteStat stat = statPerOrder.get(i);
                stat.setId(String.valueOf(IdUtil.getSnowflakeNextId()));
                stat.setBatchNumber(batchNum);
                stat.setCreateTime(DateUtils.getNowDate());
                stat.setCreateBy(SecurityUtils.getUsername());
                stat.setWarning(false);
                stat.setDelFlag("0");
                if(i==0){
                    Date orderPlanEndDay = stat.getOrderPlanEndDay();
                    LocalDateTime transLocalDateTime = transLocalDateTime(orderPlanEndDay);
                    LocalTime endOfDay = LocalTime.of(23, 59, 59);
                    LocalDateTime orderPlanEndDayLocalDateTime =  LocalDateTime.of( transLocalDateTime.toLocalDate(), endOfDay);
                    if(orderPlanEndDayLocalDateTime.isBefore(now)){
                        hasBefore = true;
                        stat.setWarning(true);
                        stat.setProcessPlanEndDay(transDate(now));
                        stat.setProcessPlanStartDay(transDate(now));
                    }else {
                        /*计划完工日=钣金计划工单完成时间*/
                        stat.setProcessPlanEndDay(transDate(orderPlanEndDayLocalDateTime));
                        /*计划开工日=钣金计划工单完成时间 -  工序总工时*/
                        long seconds = stat.getProcessTotalTime().multiply(new BigDecimal(60)).multiply(new BigDecimal(60)).longValue();
                        LocalDateTime lastPlanStartDt = orderPlanEndDayLocalDateTime.minusSeconds(seconds);
                        if(lastPlanStartDt.isBefore(now)){
                            hasBefore = true;
                            stat.setProcessPlanStartDay(transDate(now));
                        }else {
                            stat.setProcessPlanStartDay(transDate(lastPlanStartDt));
                        }
                    }
                }
                /*当工艺工序号 >= 工单当前工序 代表是未来工序,才进行计划开工日 和计划完工日的计算
                 * 当工艺工序号 < 工单当前工序  过去工序,不进行计算
                 * */
                if( stat.getRoadProcessNumber().compareTo(stat.getCurrentProcessNumber())>=0){
                    /*倒排时 下一道工序存在 比当前时间小的计划时间,则当前计划开始和结束时间都是当前时间*/
                    if(hasBefore){
                        stat.setWarning(true);
                        stat.setProcessPlanEndDay(transDate(now));
                        stat.setProcessPlanStartDay(transDate(now));
                    }else{
                        /*下一道工序计划时间都正常时,*/
                        if (last != null) {
                            /*当前工序结束时间=下一道工序的开始时间*/
                            stat.setProcessPlanEndDay(last.getProcessPlanStartDay());
                            /*开始时间=结束时间-总工时*/
                            long seconds = stat.getProcessTotalTime().multiply(new BigDecimal(60)).multiply(new BigDecimal(60)).longValue();
                            LocalDateTime crtStartDt = transLocalDateTime(last.getProcessPlanStartDay()).minusSeconds(seconds);
                            /*如果开始时间小于当前时间*/
                            if(crtStartDt.isBefore(now)){
                                hasBefore=true;
                                stat.setWarning(true);
                                stat.setProcessPlanStartDay(transDate(now));
                            }else {
                                stat.setProcessPlanStartDay(transDate(crtStartDt));
                            }
                        }
                    }
                }
               if(stat.getProcessPlanStartDay()!=null){
                   String[] strNow = new SimpleDateFormat("yyyy-MM-dd").format(stat.getProcessPlanStartDay()).toString().split("-");
                   stat.setPlanStartYear(strNow[0]);
                   stat.setPlanStartMonth(strNow[1]);
                   stat.setPlanStartDay(strNow[2]);
               }
                last = stat;
                cptStateList.add(stat);
            }
        }
        // 批量插入以提高性能
        if (!cptStateList.isEmpty()) {
            int batchSize = 1000;
            int size = cptStateList.size();
            for (int i = 0; i < size; i += batchSize) {
                int end = Math.min(i + batchSize, size);
                List<ApsGasPipingRouteStat> batch = cptStateList.subList(i, end);
                apsGasPipingRouteStatMapper.insertApsGasPipingRouteStatBatch(batch);
                log.info("批量插入数据,开始位置:{},结束位置:{}", i, end);
            }
        }
        apsGasPipingRouteStatMapper.deleteApsGasPipingRouteStatByBatchNum(batchNum);
        log.info("批量插入数据完成,batchNum:"+batchNum);
    }
 
}