mitao
2025-04-07 6c17cac744b3b439e38f6998ce4704c9a01c5dd2
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
package com.sinata.system.service.biz;
 
import cn.idev.excel.FastExcel;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.sinata.common.utils.CollUtils;
import com.sinata.common.utils.DateUtils;
import com.sinata.common.utils.StringUtils;
import com.sinata.system.config.AutoColumnWidthStrategy;
import com.sinata.system.config.CustomCellWriteHeightConfig;
import com.sinata.system.domain.MwCollectRecord;
import com.sinata.system.domain.MwWarningRecord;
import com.sinata.system.domain.SysDepartment;
import com.sinata.system.domain.query.DisposalReportQuery;
import com.sinata.system.domain.query.HospitalReportQuery;
import com.sinata.system.domain.query.TransformQuery;
import com.sinata.system.domain.vo.DepartmentReportItemVO;
import com.sinata.system.domain.vo.DepartmentReportVO;
import com.sinata.system.domain.vo.MwCollectRecordVO;
import com.sinata.system.domain.vo.MwDisposalRecordReportVO;
import com.sinata.system.domain.vo.MwMedicalWasteBoxVO;
import com.sinata.system.domain.vo.SysDictDataVO;
import com.sinata.system.domain.vo.TransformVO;
import com.sinata.system.service.ISysDictDataService;
import com.sinata.system.service.MwCheckoutRecordService;
import com.sinata.system.service.MwCollectRecordService;
import com.sinata.system.service.MwDisposalHandleRecordService;
import com.sinata.system.service.MwDisposalRecordService;
import com.sinata.system.service.MwMicroEquipmentRecordItemService;
import com.sinata.system.service.MwWarningRecordService;
import com.sinata.system.service.SysDepartmentService;
import com.sinata.system.utils.ImageToBase64;
import com.sinata.system.utils.ImgUtils;
import lombok.RequiredArgsConstructor;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
 
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
 
/**
 * @author mitao
 * @date 2024/12/25
 */
@Service
@RequiredArgsConstructor
public class StaticsService {
    private final SysDepartmentService sysDepartmentService;
    private final MwCollectRecordService mwCollectRecordService;
    private final MwCheckoutRecordService mwCheckoutRecordService;
    private final ISysDictDataService sysDictDataService;
    private final MwWarningRecordService mwWarningRecordService;
    private final HttpServletResponse response;
    private final MwDisposalRecordService mwDisposalRecordService;
    private final MwDisposalHandleRecordService mwDisposalHandleRecordService;
    private final MwMicroEquipmentRecordItemService mwMicroEquipmentRecordItemService;
 
 
 
    /**
     * 医院报表
     *
     * @param query
     * @return
     */
    public DepartmentReportVO hospitalReport(HospitalReportQuery query) {
        DepartmentReportVO vo = new DepartmentReportVO();
        SysDepartment department = sysDepartmentService.getById(query.getDepartmentId());
        if (Objects.nonNull(department)) {
            vo.setDepartmentName(department.getDepartmentName());
        }
        List<SysDictDataVO> wasteTypeList = sysDictDataService.medicalWasteTypeList();
 
        if (CollUtils.isEmpty(wasteTypeList)) {
            return vo;
        }
        vo.setLegend(wasteTypeList.stream().map(SysDictDataVO::getDictLabel).collect(Collectors.toList()));
        vo.getLegend().add("小计");
        List<MwCollectRecord> collectRecordList = mwCollectRecordService.lambdaQuery()/*.eq(query.getReportType().equals(1), MwCollectRecord::getStatus, MedicalWasteStatusEnum.TEMPORARILY_STORED.getCode())
                .ne(query.getReportType().equals(2), MwCollectRecord::getStatus, MedicalWasteStatusEnum.TEMPORARILY_STORED.getCode())*/
                .eq(MwCollectRecord::getDepartmentId, query.getDepartmentId())
                .between(query.getReportType().equals(1), MwCollectRecord::getCollectTime, query.getStartTime(), query.getEndTime())
                .between(query.getReportType().equals(2), MwCollectRecord::getCheckoutTime, query.getStartTime(), query.getEndTime())
                .orderByDesc(MwCollectRecord::getCollectTime).list();
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);
        switch (query.getDateType()) {
            case 1:
                sdf = new SimpleDateFormat(DateUtils.YYYY_MM_DD);
                break;
            case 2:
                sdf = new SimpleDateFormat(DateUtils.YYYY_MM);
                break;
            case 3:
                sdf = new SimpleDateFormat(DateUtils.YYYY);
                break;
        }
        List<String> dateList = DateUtils.getDayBetween(query.getStartTime(), query.getEndTime(), query.getDateType());
        List<DepartmentReportItemVO> list = new ArrayList<>();
        for (String date : dateList) {
            DepartmentReportItemVO itemVO = new DepartmentReportItemVO();
            itemVO.setName(date);
            itemVO.setData(new ArrayList<>());
            BigDecimal totalCount = BigDecimal.ZERO;
            BigDecimal totalWeight = BigDecimal.ZERO;
            SimpleDateFormat finalSdf = sdf;
            for (SysDictDataVO sysDictData : wasteTypeList) {
                BigDecimal weight = BigDecimal.ZERO;
                BigDecimal currentCount = BigDecimal.ZERO;
                if (query.getReportType().equals(1)) {
                    weight = collectRecordList.stream().filter(e -> e.getWasteType().equals(sysDictData.getDictCode())
                                    && finalSdf.format(e.getCollectTime()).equals(date)).map(MwCollectRecord::getWeight)
                            .reduce(BigDecimal::add).orElse(BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP);
                    long count = collectRecordList.stream()
                            .filter(e -> e.getWasteType().equals(sysDictData.getDictCode()) && finalSdf.format(e.getCollectTime()).equals(date))
                            .count();
                    currentCount = BigDecimal.valueOf(count);
                } else {
                    weight = collectRecordList.stream().filter(e -> e.getWasteType().equals(sysDictData.getDictCode())
                                    && finalSdf.format(e.getCheckoutTime()).equals(date)).map(MwCollectRecord::getWeight)
                            .reduce(BigDecimal::add).orElse(BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP);
                    long count = collectRecordList.stream()
                            .filter(e -> e.getWasteType().equals(sysDictData.getDictCode()) && finalSdf.format(e.getCheckoutTime()).equals(date))
                            .count();
                    currentCount = BigDecimal.valueOf(count);
                }
                itemVO.getData().add(currentCount);
                itemVO.getData().add(weight);
                totalCount = totalCount.add(currentCount);
                totalWeight = totalWeight.add(weight);
            }
            itemVO.getData().add(totalCount);
            itemVO.getData().add(totalWeight);
            //查询预警记录判断是否超时
            if (query.getDateType().equals(1)) {
                itemVO.setOverTimeFlag("否");
                List<Long> collectIdList = collectRecordList.stream().filter(e -> finalSdf.format(e.getCollectTime()).equals(date))
                        .map(MwCollectRecord::getId).collect(Collectors.toList());
                if (CollUtils.isNotEmpty(collectIdList)) {
                    List<MwWarningRecord> warningRecordList = mwWarningRecordService.lambdaQuery().in(MwWarningRecord::getWarningTargetId, collectIdList).list();
                    if (CollUtils.isNotEmpty(warningRecordList)) {
                        itemVO.setOverTimeFlag("是");
                    }
                }
            }
            list.add(itemVO);
        }
        // 添加合计行
        if (!list.isEmpty()) {
            DepartmentReportItemVO totalRow = new DepartmentReportItemVO();
            totalRow.setName("合计");
            totalRow.setData(new ArrayList<>());
 
            // 计算各类型废物的数量和重量总计
            for (SysDictDataVO sysDictDataVO : wasteTypeList) {
                BigDecimal totalTypeCount = BigDecimal.ZERO;
                BigDecimal totalTypeWeight = BigDecimal.ZERO;
 
                for (DepartmentReportItemVO item : list) {
                    // 每种废物类型占用两列(数量和重量)
                    int index = wasteTypeList.indexOf(sysDictDataVO);
                    int countIndex = index * 2;
                    int weightIndex = countIndex + 1;
 
                    if (countIndex < item.getData().size()) {
                        totalTypeCount = totalTypeCount.add(item.getData().get(countIndex));
                    }
                    if (weightIndex < item.getData().size()) {
                        totalTypeWeight = totalTypeWeight.add(item.getData().get(weightIndex));
                    }
                }
 
                totalRow.getData().add(totalTypeCount);
                totalRow.getData().add(totalTypeWeight);
            }
 
            // 计算总的数量和重量
            BigDecimal finalTotalCount = BigDecimal.ZERO;
            BigDecimal finalTotalWeight = BigDecimal.ZERO;
 
            for (DepartmentReportItemVO item : list) {
                int totalCountIndex = item.getData().size() - 2;
                int totalWeightIndex = item.getData().size() - 1;
 
                if (totalCountIndex >= 0 && totalWeightIndex >= 0) {
                    finalTotalCount = finalTotalCount.add(item.getData().get(totalCountIndex));
                    finalTotalWeight = finalTotalWeight.add(item.getData().get(totalWeightIndex));
                }
            }
 
            totalRow.getData().add(finalTotalCount);
            totalRow.getData().add(finalTotalWeight);
 
            // 超时标记处理(如果有)
            if (query.getDateType().equals(1)) {
                totalRow.setOverTimeFlag("—"); // 合计行不显示超时标记
            }
 
            // 将合计行添加到列表开头
            list.add(0, totalRow);
        }
        vo.setList(list);
        return vo;
    }
 
    /**
     * 医院报表-导出
     *
     * @param query
     * @return
     */
    public void hospitalReportExport(HospitalReportQuery query) throws IOException {
        List<List<String>> head = hospitalReportHead(query);
        System.out.println(JSONObject.toJSONString(head));
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("医院报表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 这里需要设置不关闭流
        FastExcel.write(response.getOutputStream())
                .head(head)
                .autoCloseStream(Boolean.TRUE)
                .registerWriteHandler(new AutoColumnWidthStrategy())
                .sheet("医院报表")
                .doWrite(getHospitalReportStaticsData(query));
    }
 
    /**
     * 封装Excel导出数据
     *
     * @param query
     * @return
     */
    private List<List<Object>> getHospitalReportStaticsData(HospitalReportQuery query) {
        DepartmentReportVO vo = hospitalReport(query);
        if (CollUtils.isNotEmpty(vo.getList())) {
            List<List<Object>> result = new ArrayList<>();
            for (DepartmentReportItemVO departmentReportItemVO : vo.getList()) {
                List<Object> data = new ArrayList<>();
                data.add(departmentReportItemVO.getName());
                data.addAll(departmentReportItemVO.getData());
                if (query.getDateType().equals(1)) {
                    data.add(departmentReportItemVO.getOverTimeFlag());
                }
                result.add(data);
            }
            return result;
        }
        return CollUtils.emptyList();
    }
 
    /**
     * 医院报表表头
     *
     * @return
     */
    private List<List<String>> hospitalReportHead(HospitalReportQuery query) {
        SysDepartment department = sysDepartmentService.getById(query.getDepartmentId());
        List<SysDictDataVO> wasteTypeList = sysDictDataService.medicalWasteTypeList();
        List<List<String>> headTitles = Lists.newArrayList();
        String title = "";
        if (Objects.nonNull(department)) {
            title = department.getDepartmentName() + "医废报表";
        } else {
            title = "医废报表";
        }
        headTitles.add(Lists.newArrayList(title, "日期", "日期"));
        String finalTitle = title;
        wasteTypeList.forEach(item -> {
            headTitles.add(Lists.newArrayList(finalTitle, item.getDictLabel(), "数量"));
            headTitles.add(Lists.newArrayList(finalTitle, item.getDictLabel(), "重量(kg)"));
        });
        headTitles.add(Lists.newArrayList(title, "小计", "数量"));
        headTitles.add(Lists.newArrayList(title, "小计", "重量(kg)"));
        if (query.getDateType().equals(1)) {
            headTitles.add(Lists.newArrayList(title, "是否超时", "是否超时"));
        }
        return headTitles;
    }
 
    /**
     * 转移联单
     *
     * @param query
     * @return
     */
    public DepartmentReportVO transformList(TransformQuery query) {
        DepartmentReportVO vo = new DepartmentReportVO();
        SysDepartment department = sysDepartmentService.getById(query.getDepartmentId());
        if (Objects.nonNull(department)) {
            vo.setDepartmentName(department.getDepartmentName());
        }
        SysDepartment region = sysDepartmentService.getDepartmentByParentId(department.getParentId());
        //List<SysDepartment> hospitalList = sysDepartmentService.lambdaQuery().likeRight(SysDepartment::getTreeCode, region.getTreeCode()).eq(SysDepartment::getOrgType, DepartmentEnum.MEDICAL_INSTITUTION.getCode()).list();
        List<TransformVO> checkoutRecordVOList = mwCheckoutRecordService.getCheckoutRecordList(query, region.getTreeCode());
        //查询医废类型
        List<SysDictDataVO> sysDictDataVOS = sysDictDataService.medicalWasteTypeListByDictCode(query.getWasteTypeCodeList());
        if (CollUtils.isNotEmpty(sysDictDataVOS)) {
            vo.setLegend(sysDictDataVOS.stream().map(SysDictDataVO::getDictLabel).collect(Collectors.toList()));
            vo.getLegend().add("小计");
 
            List<DepartmentReportItemVO> list = new ArrayList<>();
 
            // 处理各医院数据
            for (TransformVO transformVO : checkoutRecordVOList) {
                BigDecimal totalCount = BigDecimal.ZERO;
                BigDecimal totalWeight = BigDecimal.ZERO;
                DepartmentReportItemVO departmentReportItemVO = new DepartmentReportItemVO();
                departmentReportItemVO.setName(transformVO.getHospitalName());
                departmentReportItemVO.setData(new ArrayList<>());
                departmentReportItemVO.setDriverName(transformVO.getDriverName());
                departmentReportItemVO.setHospitalSignature(ImageToBase64.convertImageToBase64(transformVO.getHospitalSignature()));
                departmentReportItemVO.setHospitalSignatureUrl(transformVO.getHospitalSignature());
                departmentReportItemVO.setHandoverTime(transformVO.getCheckoutTime());
                for (SysDictDataVO sysDictData : sysDictDataVOS) {
                    BigDecimal count = BigDecimal.valueOf(transformVO.getCollectRecordList().stream().filter(item -> item.getWasteType().equals(sysDictData.getDictCode())).count());
                    BigDecimal weight = transformVO.getCollectRecordList().stream().filter(item -> item.getWasteType().equals(sysDictData.getDictCode())).map(MwMedicalWasteBoxVO::getTotalWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
                    departmentReportItemVO.getData().add(count);
                    departmentReportItemVO.getData().add(weight);
                    totalCount = totalCount.add(count);
                    totalWeight = totalWeight.add(weight);
                }
                departmentReportItemVO.getData().add(totalCount);
                departmentReportItemVO.getData().add(totalWeight);
                list.add(departmentReportItemVO);
            }
 
            // 添加合计行
            if (!list.isEmpty()) {
                DepartmentReportItemVO totalRow = new DepartmentReportItemVO();
                totalRow.setName("合计");
                totalRow.setData(new ArrayList<>());
 
                // 计算各类型废物的总数量和总重量
                for (SysDictDataVO sysDictData : sysDictDataVOS) {
                    BigDecimal totalTypeCount = BigDecimal.ZERO;
                    BigDecimal totalTypeWeight = BigDecimal.ZERO;
 
                    for (DepartmentReportItemVO item : list) {
                        // 获取当前废物类型在数据列表中的索引位置
                        int index = sysDictDataVOS.indexOf(sysDictData);
                        // 每个废物类型占两列(数量和重量)
                        int countIndex = index * 2;
                        int weightIndex = countIndex + 1;
 
                        if (countIndex < item.getData().size()) {
                            totalTypeCount = totalTypeCount.add(item.getData().get(countIndex));
                        }
                        if (weightIndex < item.getData().size()) {
                            totalTypeWeight = totalTypeWeight.add(item.getData().get(weightIndex));
                        }
                    }
 
                    totalRow.getData().add(totalTypeCount);
                    totalRow.getData().add(totalTypeWeight);
                }
 
                // 计算总的数量和重量
                BigDecimal finalTotalCount = BigDecimal.ZERO;
                BigDecimal finalTotalWeight = BigDecimal.ZERO;
 
                for (DepartmentReportItemVO item : list) {
                    int totalCountIndex = item.getData().size() - 2;
                    int totalWeightIndex = item.getData().size() - 1;
 
                    if (totalCountIndex >= 0 && totalWeightIndex >= 0) {
                        finalTotalCount = finalTotalCount.add(item.getData().get(totalCountIndex));
                        finalTotalWeight = finalTotalWeight.add(item.getData().get(totalWeightIndex));
                    }
                }
 
                totalRow.getData().add(finalTotalCount);
                totalRow.getData().add(finalTotalWeight);
 
                // 将合计行添加到列表开头
                list.add(0, totalRow);
            }
 
            vo.setList(list);
        }
        return vo;
    }
 
    public void transformListExport(TransformQuery query) throws IOException {
        List<List<String>> head = transformReportHead(query);
        System.out.println(JSONObject.toJSONString(head));
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("转移联单", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 这里需要设置不关闭流
        FastExcel.write(response.getOutputStream())
                .head(head)
                .autoCloseStream(Boolean.TRUE)
                .registerWriteHandler(new AutoColumnWidthStrategy())
                .registerWriteHandler(new CustomCellWriteHeightConfig())
                .sheet("转移联单")
                .doWrite(getTransformReportStaticsData(query));
    }
 
    /**
     * 转运联单导出数据
     *
     * @param query
     * @return
     * @throws MalformedURLException
     */
    private List<List<Object>> getTransformReportStaticsData(TransformQuery query) throws MalformedURLException {
        DepartmentReportVO vo = transformList(query);
        List<DepartmentReportItemVO> list = vo.getList();
        if (CollUtils.isNotEmpty(list)) {
            List<List<Object>> result = new ArrayList<>();
            for (DepartmentReportItemVO departmentReportItemVO : list) {
                List<Object> data = new ArrayList<>();
                data.add(departmentReportItemVO.getName());
                data.addAll(departmentReportItemVO.getData());
                if (StringUtils.isNotBlank(departmentReportItemVO.getHospitalSignatureUrl())) {
                    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                        //获取文件后缀
                        String extension = FilenameUtils.getExtension(departmentReportItemVO.getHospitalSignatureUrl());
                        BufferedImage originalImage = ImageIO.read(ImgUtils.getFileByHttpURL(departmentReportItemVO.getHospitalSignatureUrl()));
                        Thumbnails.of(originalImage).scale(0.8).rotate(270).outputFormat(extension).toOutputStream(outputStream);
                        data.add(outputStream.toByteArray());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    data.add("");
                }
                data.add(departmentReportItemVO.getDriverName());
                data.add(departmentReportItemVO.getHandoverTime());
                result.add(data);
            }
            return result;
        }
        return CollUtils.emptyList();
    }
    /**
     * 转运联单导出表头
     *
     * @param query
     * @return
     */
    private List<List<String>> transformReportHead(TransformQuery query) {
        //查询医废类型
        List<SysDictDataVO> sysDictDataVOS = sysDictDataService.medicalWasteTypeListByDictCode(query.getWasteTypeCodeList());
        SysDepartment department = sysDepartmentService.getById(query.getDepartmentId());
        String title = "";
        if (Objects.nonNull(department)) {
            title = department.getDepartmentName() + "转移联单";
        } else {
            title = "转移联单";
        }
        List<List<String>> headTitles = Lists.newArrayList();
        headTitles.add(Lists.newArrayList(title, "医院名称", "医院名称"));
        String finalTitle = title;
        sysDictDataVOS.forEach(item -> {
            headTitles.add(Lists.newArrayList(finalTitle, item.getDictLabel(), "数量"));
            headTitles.add(Lists.newArrayList(finalTitle, item.getDictLabel(), "重量(kg)"));
        });
        headTitles.add(Lists.newArrayList(title, "小计", "数量"));
        headTitles.add(Lists.newArrayList(title, "小计", "重量(kg)"));
        headTitles.add(Lists.newArrayList(title, "机构人员签字", "机构人员签字"));
        headTitles.add(Lists.newArrayList(title, "运输人员签字", "运输人员签字"));
        headTitles.add(Lists.newArrayList(title, "交接时间", "交接时间"));
        return headTitles;
    }
 
    /**
     * 处置报表
     *
     * @param query
     * @return
     */
    public DepartmentReportVO disposalReport(DisposalReportQuery query) {
        DepartmentReportVO vo = new DepartmentReportVO();
        SysDepartment department = sysDepartmentService.getById(query.getDepartmentId());
        if (Objects.nonNull(department)) {
            vo.setDepartmentName(department.getDepartmentName());
        }
        //已接收
        List<MwDisposalRecordReportVO> receivedList = mwDisposalRecordService.disposalReceiveReport(query);
        //已处置
        List<MwDisposalRecordReportVO> disposaledList = mwDisposalHandleRecordService.disposalReport(query);
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);
        switch (query.getDateType()) {
            case 1:
                sdf = new SimpleDateFormat(DateUtils.YYYY_MM_DD);
                break;
            case 2:
                sdf = new SimpleDateFormat(DateUtils.YYYY_MM);
                break;
            case 3:
                sdf = new SimpleDateFormat(DateUtils.YYYY);
                break;
        }
        List<String> dateList = DateUtils.getDayBetween(query.getStartTime(), query.getEndTime(), query.getDateType());
        //查询医废类型
        List<SysDictDataVO> sysDictDataVOS = sysDictDataService.medicalWasteTypeListByDictCode(query.getWasteTypeCodeList());
        if (CollUtils.isNotEmpty(sysDictDataVOS)) {
            List<String> legend = sysDictDataVOS.stream().map(SysDictDataVO::getDictLabel).collect(Collectors.toList());
            vo.setLegend(legend);
            List<DepartmentReportItemVO> list = new ArrayList<>();
            for (String date : dateList) {
                DepartmentReportItemVO departmentReportItemVO = new DepartmentReportItemVO();
                departmentReportItemVO.setName(date);
                departmentReportItemVO.setData(new ArrayList<>());
                SimpleDateFormat finalSdf = sdf;
                //接收
                for (SysDictDataVO sysDictData : sysDictDataVOS) {
                    BigDecimal totalWeight = receivedList.stream().filter(item -> item.getWasteType().equals(sysDictData.getDictCode()) &&
                                    finalSdf.format(item.getReceiveTime()).equals(date)).map(MwDisposalRecordReportVO::getWeight)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    departmentReportItemVO.getData().add(totalWeight);
                }
                //处置
                for (SysDictDataVO sysDictData : sysDictDataVOS) {
                    BigDecimal totalWeight = disposaledList.stream().filter(item -> item.getWasteType().equals(sysDictData.getDictCode()) &&
                                    finalSdf.format(item.getDisposalTime()).equals(date)).map(MwDisposalRecordReportVO::getWeight)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    departmentReportItemVO.getData().add(totalWeight);
                }
                list.add(departmentReportItemVO);
            }
 
            // 添加合计行
            if (!list.isEmpty()) {
                DepartmentReportItemVO totalRow = new DepartmentReportItemVO();
                totalRow.setName("合计");
                totalRow.setData(new ArrayList<>());
 
                // 计算各类型废物的接收总量
                for (SysDictDataVO sysDictData : sysDictDataVOS) {
                    BigDecimal totalReceiveWeight = BigDecimal.ZERO;
 
                    for (DepartmentReportItemVO item : list) {
                        int index = sysDictDataVOS.indexOf(sysDictData);
                        if (index < item.getData().size()) {
                            totalReceiveWeight = totalReceiveWeight.add(item.getData().get(index));
                        }
                    }
 
                    totalRow.getData().add(totalReceiveWeight);
                }
 
                // 计算各类型废物的处置总量
                for (SysDictDataVO sysDictData : sysDictDataVOS) {
                    BigDecimal totalDisposalWeight = BigDecimal.ZERO;
 
                    for (DepartmentReportItemVO item : list) {
                        int index = sysDictDataVOS.indexOf(sysDictData);
                        // 处置量数据在接收量数据之后,所以索引需要加上sysDictDataVOS的大小
                        int disposalIndex = sysDictDataVOS.size() + index;
                        if (disposalIndex < item.getData().size()) {
                            totalDisposalWeight = totalDisposalWeight.add(item.getData().get(disposalIndex));
                        }
                    }
 
                    totalRow.getData().add(totalDisposalWeight);
                }
 
                // 将合计行添加到列表开头
                list.add(0, totalRow);
            }
 
            vo.setList(list);
        }
        return vo;
    }
 
    /**
     * 处置报表导出
     *
     * @param query
     * @throws IOException
     */
    public void disposalReportExport(DisposalReportQuery query) throws IOException {
        List<List<String>> head = disposalReportHead(query);
        System.out.println(JSONObject.toJSONString(head));
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("处置报表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 这里需要设置不关闭流
        FastExcel.write(response.getOutputStream())
                .head(head)
                .autoCloseStream(Boolean.TRUE)
                .registerWriteHandler(new AutoColumnWidthStrategy())
                .sheet("处置报表")
                .doWrite(getDisposalReportStaticsData(query));
    }
 
    /**
     * 处置报表统计数据
     *
     * @param query
     * @return
     */
    private List<List<Object>> getDisposalReportStaticsData(DisposalReportQuery query) {
        DepartmentReportVO vo = disposalReport(query);
        List<DepartmentReportItemVO> list = vo.getList();
        if (CollUtils.isNotEmpty(list)) {
            List<List<Object>> result = new ArrayList<>();
            for (DepartmentReportItemVO departmentReportItemVO : list) {
                List<Object> data = new ArrayList<>();
                data.add(departmentReportItemVO.getName());
                data.addAll(departmentReportItemVO.getData());
                result.add(data);
            }
            return result;
        }
        return CollUtils.emptyList();
    }
 
    /**
     * 处置报表表头
     *
     * @param query
     * @return
     */
    private List<List<String>> disposalReportHead(DisposalReportQuery query) {
        //查询医废类型
        List<SysDictDataVO> sysDictDataVOS = sysDictDataService.medicalWasteTypeListByDictCode(query.getWasteTypeCodeList());
        SysDepartment department = sysDepartmentService.getById(query.getDepartmentId());
        String title = "";
        if (Objects.nonNull(department)) {
            title = department.getDepartmentName() + "处置报表";
        } else {
            title = "处置报表";
        }
        List<List<String>> headTitles = Lists.newArrayList();
        headTitles.add(Lists.newArrayList(title, "日期", "日期"));
        String finalTitle = title;
        sysDictDataVOS.forEach(item -> {
            headTitles.add(Lists.newArrayList(finalTitle, "医疗废物接收量(kg)", item.getDictLabel()));
        });
        String finalTitle1 = title;
        sysDictDataVOS.forEach(item -> {
            headTitles.add(Lists.newArrayList(finalTitle1, "医疗废物处置量(kg)", item.getDictLabel()));
        });
        return headTitles;
    }
 
    /**
     * 监管报表
     *
     * @param query
     * @return
     */
    public DepartmentReportVO regulationReport(DisposalReportQuery query) {
        DepartmentReportVO vo = new DepartmentReportVO();
        SysDepartment department = sysDepartmentService.getById(query.getDepartmentId());
        if (Objects.nonNull(department)) {
            vo.setDepartmentName(department.getDepartmentName());
        }
        //医废产生量
        List<MwCollectRecordVO> collectRecordList = mwCollectRecordService.getRegulationReportList(query);
        //医废转移量
        List<MwCollectRecordVO> checkoutRecordList = mwCheckoutRecordService.getRegulationReportList(query);
        //医废处置量
        List<MwCollectRecordVO> disposalRecordList = mwDisposalRecordService.getRegulationReportList(query);
        List<MwCollectRecordVO> microEquipmentRecordList = mwMicroEquipmentRecordItemService.getRegulationReportList(query);
        disposalRecordList.addAll(microEquipmentRecordList);
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.YYYY_MM_DD_HH_MM_SS);
        switch (query.getDateType()) {
            case 1:
                sdf = new SimpleDateFormat(DateUtils.YYYY_MM_DD);
                break;
            case 2:
                sdf = new SimpleDateFormat(DateUtils.YYYY_MM);
                break;
            case 3:
                sdf = new SimpleDateFormat(DateUtils.YYYY);
                break;
        }
        List<String> dateList = DateUtils.getDayBetween(query.getStartTime(), query.getEndTime(), query.getDateType());
        //查询医废类型
        List<SysDictDataVO> sysDictDataVOS = sysDictDataService.medicalWasteTypeListByDictCode(query.getWasteTypeCodeList());
        if (CollUtils.isNotEmpty(sysDictDataVOS)) {
            vo.setLegend(sysDictDataVOS.stream().map(SysDictDataVO::getDictLabel).collect(Collectors.toList()));
            vo.setList(new ArrayList<>());
            List<DepartmentReportItemVO> list = new ArrayList<>();
            for (String date : dateList) {
                DepartmentReportItemVO departmentReportItemVO = new DepartmentReportItemVO();
                departmentReportItemVO.setName(date);
                departmentReportItemVO.setData(new ArrayList<>());
                SimpleDateFormat finalSdf = sdf;
                for (SysDictDataVO sysDictData : sysDictDataVOS) {
                    BigDecimal weight = collectRecordList.stream().filter(e -> e.getWasteType().equals(sysDictData.getDictCode()) &&
                            finalSdf.format(e.getCollectTime()).equals(date)).map(MwCollectRecordVO::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
                    departmentReportItemVO.getData().add(weight);
 
                }
                for (SysDictDataVO sysDictData : sysDictDataVOS) {
                    BigDecimal weight = checkoutRecordList.stream().filter(e -> e.getWasteType().equals(sysDictData.getDictCode()) &&
                            finalSdf.format(e.getCheckoutTime()).equals(date)).map(MwCollectRecordVO::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
                    departmentReportItemVO.getData().add(weight);
                }
                for (SysDictDataVO sysDictData : sysDictDataVOS) {
                    BigDecimal weight = disposalRecordList.stream().filter(e -> e.getWasteType().equals(sysDictData.getDictCode()) &&
                            finalSdf.format(e.getCollectTime()).equals(date)).map(MwCollectRecordVO::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
                    departmentReportItemVO.getData().add(weight);
                }
                list.add(departmentReportItemVO);
            }
 
            // 添加合计行
            if (!list.isEmpty()) {
                DepartmentReportItemVO totalRow = new DepartmentReportItemVO();
                totalRow.setName("合计");
                totalRow.setData(new ArrayList<>());
 
                // 计算各类型废物的产生总量
                for (SysDictDataVO sysDictData : sysDictDataVOS) {
                    BigDecimal totalGeneratedWeight = BigDecimal.ZERO;
 
                    for (DepartmentReportItemVO item : list) {
                        int index = sysDictDataVOS.indexOf(sysDictData);
                        if (index < item.getData().size()) {
                            totalGeneratedWeight = totalGeneratedWeight.add(item.getData().get(index));
                        }
                    }
 
                    totalRow.getData().add(totalGeneratedWeight);
                }
 
                // 计算各类型废物的转移总量
                for (SysDictDataVO sysDictData : sysDictDataVOS) {
                    BigDecimal totalTransferWeight = BigDecimal.ZERO;
 
                    for (DepartmentReportItemVO item : list) {
                        int index = sysDictDataVOS.indexOf(sysDictData);
                        // 转移量数据在产生量数据之后,所以索引需要加上wasteTypeList的大小
                        int transferIndex = sysDictDataVOS.size() + index;
                        if (transferIndex < item.getData().size()) {
                            totalTransferWeight = totalTransferWeight.add(item.getData().get(transferIndex));
                        }
                    }
 
                    totalRow.getData().add(totalTransferWeight);
                }
 
                // 计算各类型废物的处置总量
                for (SysDictDataVO sysDictData : sysDictDataVOS) {
                    BigDecimal totalDisposalWeight = BigDecimal.ZERO;
 
                    for (DepartmentReportItemVO item : list) {
                        int index = sysDictDataVOS.indexOf(sysDictData);
                        // 处置量数据在产生量和转移量数据之后,所以索引需要加上wasteTypeList的大小的2倍
                        int disposalIndex = sysDictDataVOS.size() * 2 + index;
                        if (disposalIndex < item.getData().size()) {
                            totalDisposalWeight = totalDisposalWeight.add(item.getData().get(disposalIndex));
                        }
                    }
 
                    totalRow.getData().add(totalDisposalWeight);
                }
 
                // 将合计行添加到列表开头
                list.add(0, totalRow);
            }
 
            vo.setList(list);
        }
        return vo;
    }
 
    public void regulationReportExport(DisposalReportQuery query) throws IOException {
        List<List<String>> head = regulationReportHead(query);
        System.out.println(JSONObject.toJSONString(head));
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("监管报表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 这里需要设置不关闭流
        FastExcel.write(response.getOutputStream())
                .head(head)
                .autoCloseStream(Boolean.TRUE)
                .registerWriteHandler(new AutoColumnWidthStrategy())
                .sheet("监管报表")
                .doWrite(getRegulationReportStaticsData(query));
    }
 
    /**
     * 监管报表导出数据
     *
     * @param query
     * @return
     */
    private List<List<Object>> getRegulationReportStaticsData(DisposalReportQuery query) {
        DepartmentReportVO vo = regulationReport(query);
        List<DepartmentReportItemVO> list = vo.getList();
        if (CollUtils.isNotEmpty(list)) {
            List<List<Object>> result = new ArrayList<>();
            for (DepartmentReportItemVO departmentReportItemVO : list) {
                List<Object> data = new ArrayList<>();
                data.add(departmentReportItemVO.getName());
                data.addAll(departmentReportItemVO.getData());
                result.add(data);
            }
            return result;
        }
        return CollUtils.emptyList();
    }
 
    /**
     * 监管报表表头
     *
     * @param query
     * @return
     */
    private List<List<String>> regulationReportHead(DisposalReportQuery query) {
        //查询医废类型
        List<SysDictDataVO> sysDictDataVOS = sysDictDataService.medicalWasteTypeListByDictCode(query.getWasteTypeCodeList());
        SysDepartment department = sysDepartmentService.getById(query.getDepartmentId());
        String title = "";
        if (Objects.nonNull(department)) {
            title = department.getDepartmentName() + "监管报表";
        } else {
            title = "监管报表";
        }
        List<List<String>> headTitles = Lists.newArrayList();
        headTitles.add(Lists.newArrayList(title, "日期", "日期"));
        String finalTitle = title;
        sysDictDataVOS.forEach(item -> {
            headTitles.add(Lists.newArrayList(finalTitle, "医疗废物产生量(kg)", item.getDictLabel()));
        });
        String finalTitle1 = title;
        sysDictDataVOS.forEach(item -> {
            headTitles.add(Lists.newArrayList(finalTitle1, "医疗废物转移量(kg)", item.getDictLabel()));
        });
        String finalTitle2 = title;
        sysDictDataVOS.forEach(item -> {
            headTitles.add(Lists.newArrayList(finalTitle2, "医疗废物处置量(kg)", item.getDictLabel()));
        });
        return headTitles;
    }
}