医院废弃物信息化管理平台
“mitao”
2025-12-24 3763145f34d7706923d55edc32f5cfbc8bc08b92
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
package cn.besteam.modules.system.service.impl;
 
import cn.besteam.common.constant.CacheConstant;
import cn.besteam.common.constant.DepartmentEnum;
import cn.besteam.common.constant.ErrorCode;
import cn.besteam.common.exception.BusinessException;
import cn.besteam.common.util.RedisUtil;
import cn.besteam.common.util.oConvertUtils;
import cn.besteam.modules.shiro.authc.util.EnvUtils;
import cn.besteam.common.aspect.annotation.AutoLog;
import cn.besteam.modules.system.biz.AliSmsService;
import cn.besteam.modules.system.biz.SysDepartmentBiz;
import cn.besteam.modules.system.dto.*;
import cn.besteam.modules.system.entity.SysDepartment;
import cn.besteam.modules.system.entity.SysDict;
import cn.besteam.modules.system.entity.SysDictItem;
import cn.besteam.modules.system.entity.SysUserDepartment;
import cn.besteam.modules.system.mapper.SysDepartmentMapper;
import cn.besteam.modules.system.service.ISysDepartmentService;
import cn.besteam.modules.system.service.ISysDictItemService;
import cn.besteam.modules.system.service.ISysDictService;
import cn.besteam.modules.system.service.ISysUserDepartmentService;
import cn.besteam.modules.system.vo.*;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.concurrent.CountDownLatch;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
/**
 * @Description: 组织架构表
 * @author: besteam
 * @date: 2020-04-17
 * @version: V1.0
 */
@Service
public class SysDepartmentServiceImpl extends ServiceImpl<SysDepartmentMapper, SysDepartment> implements ISysDepartmentService {
 
    @Autowired
    private ISysUserDepartmentService sysUserDepartmentService;
 
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
 
    @Autowired
    private ISysDictService sysDictService;
 
    @Autowired
    private ISysDictItemService sysDictItemService;
 
    @Autowired
    private AliSmsService aliSmsService;
 
    @Autowired
    private SysDepartmentBiz sysDepartmentBiz;
 
    @Autowired
    private RedisUtil redisUtil;
 
    @Autowired
    private ISysDepartmentService sysDepartmentService;
 
    @Override
    public SysDepartment getById(Serializable id) {
 
        /*String key = CacheConstant.SYS_DEPARTMENT_CACHE + id;
        if (redisTemplate.hasKey(key)) {
            return (SysDepartment) redisTemplate.opsForValue().get(key);
        } else {
            SysDepartment sysDepartment = baseMapper.selectById(id);
            if (sysDepartment != null) {
                redisTemplate.opsForValue().set(key, sysDepartment);
            }
            return sysDepartment;
        }*/
 
        SysDepartment sysDepartment = baseMapper.selectById(id);
        return sysDepartment;
    }
 
    /**
     * 获取部门、科室所在医院
     *
     * @param id
     * @return
     */
    @Override
    public SysDepartment getHospital(Integer id) {
 
        SysDepartment sysDepartment = getById(id);
 
        if (sysDepartment == null) {
            return null;
        }
        if (DepartmentEnum.OrgTypeEnum.HOSPITAL.getType().equals(sysDepartment.getOrgType())) {
            return sysDepartment;
        }
        return getHospital(sysDepartment.getParentId());
    }
 
    @Override
    public List<Integer> getParentIdList(Integer id) {
 
        List<Integer> idList = new LinkedList<>();
        SysDepartment department = getById(id);
        while (department != null) {
            idList.add(0, department.getId());
            department = getById(department.getParentId());
        }
        return idList;
    }
 
    @Override
    public SysDepartment getMyDepartment(Integer userId) {
 
        SysUserDepartment userDepartment = sysUserDepartmentService.getOne(new QueryWrapper<SysUserDepartment>().lambda().eq(SysUserDepartment::getUserId, userId));
        if (userDepartment != null) {
            return getById(userDepartment.getDepartmentId());
        }
        return null;
    }
 
    @Override
    public List<SysDepartment> listMyHospital(Integer userId) {
 
        List<SysDepartment> list = new ArrayList<>();
        SysDepartment myDepartment = getMyDepartment(userId);
        if (myDepartment == null) {
            return list;
        }
        if (myDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.DEPARTMENT.getType()) || myDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType())) {
            SysDepartment hospital = getHospital(myDepartment.getParentId());
            list.add(hospital);
        } else {
            list = list(new QueryWrapper<SysDepartment>().lambda()//
                    .eq(SysDepartment::getOrgType, DepartmentEnum.OrgTypeEnum.HOSPITAL.getType())//
                    .likeRight(SysDepartment::getTreeCode, myDepartment.getTreeCode()));
        }
        return list;
    }
 
    private static final Map<String, String> importHeaderAliasMap = new HashMap<>();
 
    static {
        importHeaderAliasMap.put("区域", "area");
        importHeaderAliasMap.put("单位;医院等级", "hospital");
        importHeaderAliasMap.put("部门", "department");
        importHeaderAliasMap.put("科室;是否暂存间", "office");
        importHeaderAliasMap.put("科室分类", "officeType");
    }
 
    @Transactional
    @Override
    public boolean importDepartment(ImportDTO dto) throws IOException {
 
        SysDepartment sysDepartment = getById(dto.getDepartmentId());
        if (sysDepartment == null) {
            throw new BusinessException(ErrorCode.DEPARTMENT_NOT_FOUND);
        }
        if (sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType())) {
            throw new BusinessException(ErrorCode.DEPARTMENT_OFFICE_CAN_NOT_BE_PARENT);
        }
        List<SysDictItem> hospitalLevelList = getHospitalLevelList();
        ExcelReader reader = ExcelUtil.getReader(dto.getFile().getInputStream());
        reader.setHeaderAlias(importHeaderAliasMap);
        List<DepartmentImportEntity> list = reader.read(0, 1, DepartmentImportEntity.class);
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException(ErrorCode.ERR_500, "导入组织架构列表不能为空");
        }
        int count = 0;
        List<SysDictItem> dictItems = sysDictItemService.list(new QueryWrapper<SysDictItem>()
                .eq("dict_id",5));
        //System.out.println("科室分类DictList=====》:"+dictItems.size());
        List<SysDepartment> sysDepartmentList = new ArrayList<>();
        for (DepartmentImportEntity importEntity : list) {
            count++;
            //
            SysDepartment parent = sysDepartment;
            if (sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.AREA.getType())) {
                if (StringUtils.isNotEmpty(importEntity.getArea())) {
                    if (!validateDepartName(importEntity.getArea())) {
                        throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,区域名称格式错误");
                    }
                    String[] areaArrays = importEntity.getArea().split(";");
                    for (int i = 0; i < areaArrays.length; i++) {
                        String areaArray = areaArrays[i];
                        if (areaArray.equals(sysDepartment.getDepartName()) && i == 0) {
                            continue;
                        }
                        String departName=areaArray;
                        //去掉空格
                        departName= oConvertUtils.replaceBlank(departName);
                        SysDepartment parentTemp = getOne(new QueryWrapper<SysDepartment>().lambda().eq(SysDepartment::getParentId, parent.getId()).eq(SysDepartment::getDepartName, departName));
                        if (parentTemp == null) {
                            parentTemp = getOne(new QueryWrapper<SysDepartment>().lambda().eq(SysDepartment::getOrgType, DepartmentEnum.OrgTypeEnum.AREA.getType()).eq(SysDepartment::getDepartName, departName));
                            if (parentTemp != null) {
                                throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,区域:" + areaArray + "父级组织错误");
                            }
                            parent = saveImportDepartment(departName, parent.getId(), DepartmentEnum.OrgTypeEnum.AREA.getType(), null, 0);
                            sysDepartmentList.add(parent);
                        } else {
                            parent = parentTemp;
                        }
                    }
                }
                if (StringUtils.isNotEmpty(importEntity.getHospital())) {
                    if (!validateDepartName(importEntity.getHospital())) {
                        throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,医院名称格式错误");
                    }
                    String[] hospitalArray = importEntity.getHospital().split(";");
                    String departName=hospitalArray[0];
                    //去掉空格
                    departName=oConvertUtils.replaceBlank(departName);
                    SysDepartment parentTemp = getOne(new QueryWrapper<SysDepartment>().lambda().eq(SysDepartment::getParentId, parent.getId()).eq(SysDepartment::getDepartName,departName));
                    if (parentTemp == null) {
                        if (hospitalArray.length > 1) {
                            Integer level = null;
                            for (SysDictItem sysDictItem : hospitalLevelList) {
                                if (hospitalArray[1].equals(sysDictItem.getItemValue())) {
                                    level = sysDictItem.getId();
                                }
                            }
                            parent = saveImportDepartment(departName, parent.getId(), DepartmentEnum.OrgTypeEnum.HOSPITAL.getType(), level, 0);
                            sysDepartmentList.add(parent);
                        } else {
                            parent = saveImportDepartment(departName, parent.getId(), DepartmentEnum.OrgTypeEnum.HOSPITAL.getType(), null, 0);
                            sysDepartmentList.add(parent);
                        }
                    } else {
                        parent = parentTemp;
                    }
                    if (StringUtils.isNotEmpty(importEntity.getDepartment())) {
                        if (!validateDepartName(importEntity.getDepartment())) {
                            throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,部门名称格式错误");
                        }
                        String[] departmentArrays = importEntity.getDepartment().split(";");
                        for (String departmentArray : departmentArrays) {
                            String departName_=departmentArray;
                            //去掉空格
                            departName_=oConvertUtils.replaceBlank(departName_);
                            parentTemp = getOne(new QueryWrapper<SysDepartment>().lambda().eq(SysDepartment::getParentId, parent.getId()).eq(SysDepartment::getDepartName, departName_));
                            if (parentTemp == null) {
                                parent = saveImportDepartment(departName_, parent.getId(), DepartmentEnum.OrgTypeEnum.DEPARTMENT.getType(), null, 0);
                                sysDepartmentList.add(parent);
                            } else {
                                parent = parentTemp;
                            }
                        }
                    }
                    if (StringUtils.isNotEmpty(importEntity.getOffice())) {
                        if (!validateDepartName(importEntity.getOffice())) {
                            throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,科室名称格式错误");
                        }
                        Integer officeType=0;
                        //判断科室分类名称是否输入正确
                        //System.out.println("excel分类名称=====》:"+importEntity.getOfficeType());
                        if (StringUtils.isNotEmpty(importEntity.getOfficeType())) {
                            for(SysDictItem sysDictItem:dictItems){
                                if(sysDictItem.getItemText().equals(importEntity.getOfficeType().trim())){
                                    officeType = sysDictItem.getId();
                                }
                            }
                            if(officeType==0) {
                                throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,科室分类名称有误");
                            }
                        }
                        //System.out.println("科室分类ID=====》:"+officeType);
                        String[] officeArray = importEntity.getOffice().split(";");
                        String departName_=officeArray[0];
                        //去掉空格
                        departName_=oConvertUtils.replaceBlank(departName_);
                        parentTemp = getOne(new QueryWrapper<SysDepartment>().lambda().eq(SysDepartment::getParentId, parent.getId()).eq(SysDepartment::getDepartName, departName_));
                        if (parentTemp == null) {
                            if (officeArray.length > 1) {
                                SysDepartment sysDepartment1 = saveImportDepartment(departName_, parent.getId(), DepartmentEnum.OrgTypeEnum.OFFICE.getType(), null, officeArray[1].equals("是") ? 1 : 0,officeType);
                                sysDepartmentList.add(sysDepartment1);
                            } else {
                                SysDepartment sysDepartment1 = saveImportDepartment(departName_, parent.getId(), DepartmentEnum.OrgTypeEnum.OFFICE.getType(), null, 0,officeType);
                                sysDepartmentList.add(sysDepartment1);
                            }
                        } else {
                            throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,科室:" + officeArray[0] + "已存在");
                        }
                    }
                }
            } else {
                if (StringUtils.isNotEmpty(importEntity.getDepartment())) {
                    if (!validateDepartName(importEntity.getDepartment())) {
                        throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,部门名称格式错误");
                    }
                    String[] departmentArrays = importEntity.getDepartment().split(";");
                    for (int i = 0; i < departmentArrays.length; i++) {
                        String departmentArray = departmentArrays[i];
                        if (departmentArray.equals(sysDepartment.getDepartName()) && i == 0) {
                            continue;
                        }
                        String departName=departmentArray;
                        //去掉空格
                        departName=oConvertUtils.replaceBlank(departName);
                        SysDepartment parentTemp = getOne(new QueryWrapper<SysDepartment>().lambda().eq(SysDepartment::getParentId, parent.getId()).eq(SysDepartment::getDepartName, departName));
                        if (parentTemp == null) {
                            parent = saveImportDepartment(departName, parent.getId(), DepartmentEnum.OrgTypeEnum.DEPARTMENT.getType(), null, 0);
                            sysDepartmentList.add(parent);
                        } else {
                            parent = parentTemp;
                        }
                    }
                }
                if (StringUtils.isNotEmpty(importEntity.getOffice())) {
                    if (!validateDepartName(importEntity.getOffice())) {
                        throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,科室名称格式错误");
                    }
                    Integer officeType=0;
                    //判断科室分类名称是否输入正确
                    //System.out.println("excel分类名称=====》:"+importEntity.getOfficeType());
                    if (StringUtils.isNotEmpty(importEntity.getOfficeType())) {
                        for(SysDictItem sysDictItem:dictItems){
                            if(sysDictItem.getItemText().equals(importEntity.getOfficeType().trim())){
                                officeType = sysDictItem.getId();
                            }
                        }
                        if(officeType==0) {
                            throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,科室分类名称有误");
                        }
                    }
                    //System.out.println("科室分类ID=====》:"+officeType);
                    String[] officeArray = importEntity.getOffice().split(";");
                    String departName=officeArray[0];
                    //去掉空格
                    departName=oConvertUtils.replaceBlank(departName);
                    SysDepartment parentTemp = getOne(new QueryWrapper<SysDepartment>().lambda().eq(SysDepartment::getParentId, parent.getId()).eq(SysDepartment::getDepartName, departName));
                    if (parentTemp == null) {
                        if (officeArray.length > 1) {
                            SysDepartment sysDepartment1 = saveImportDepartment(departName, parent.getId(), DepartmentEnum.OrgTypeEnum.OFFICE.getType(), null, officeArray[1].equals("是") ? 1 : 0,officeType);
                            sysDepartmentList.add(sysDepartment1);
                        } else {
                            SysDepartment sysDepartment1 = saveImportDepartment(departName, parent.getId(), DepartmentEnum.OrgTypeEnum.OFFICE.getType(), null, 0,officeType);
                            sysDepartmentList.add(sysDepartment1);
                        }
                    } else {
                        throw new BusinessException(ErrorCode.ERR_500, "第" + count + "行错误,科室:" + officeArray[0] + "已存在");
                    }
                }
            }
        }
        //todo 异步更新缓存
        ExecutorService threadPool = Executors.newCachedThreadPool();
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                // updateCache(sysDepartmentList);
                joinCache();
            }
        });
 
        return true;
 
    }
 
    private boolean validateDepartName(String departName) {
 
        // String regex = "^[A-Za-z0-9_\\-\\u4e00-\\u9fa5]{1,20}$";
        // Pattern pattern = Pattern.compile(regex);
        // Matcher matcher = pattern.matcher(departName);
        // return matcher.matches();
        return true;
    }
 
    @Data
    private static class DepartmentImportEntity {
 
        private String area;
 
        private String hospital;
 
        private String department;
 
        private String office;
 
        private String officeType;
 
    }
 
    /**
     * 导入更新缓存
     * @param sysDepartmentList
     */
    public void updateCache(List<SysDepartment> sysDepartmentList){
        sysDepartmentBiz.updateCache(1,sysDepartmentList,null);
 
    }
 
    @Transactional(rollbackFor = Exception.class)
    public SysDepartment saveImportDepartment(String departName, Integer parentId, Integer orgType, Integer level, Integer isWarehouse) {
 
        SysDepartment sysDepartment = new SysDepartment();
        //去掉空格
        departName=oConvertUtils.replaceBlank(departName);
        sysDepartment.setDepartName(departName);
        sysDepartment.setOrgType(orgType);
        sysDepartment.setParentId(parentId);
        sysDepartment.setTreeCode(getTreeCode(parentId));
        sysDepartment.setLevel(level);
        sysDepartment.setIsWarehouse(isWarehouse);
        sysDepartment.setOrgCode(getOrgCode(parentId, orgType));
        this.baseMapper.insert(sysDepartment);
        return sysDepartment;
    }
    @Transactional(rollbackFor = Exception.class)
    public SysDepartment saveImportDepartment(String departName, Integer parentId, Integer orgType, Integer level, Integer isWarehouse,Integer officeType) {
 
        SysDepartment sysDepartment = new SysDepartment();
        //去掉空格
        departName=oConvertUtils.replaceBlank(departName);
        sysDepartment.setDepartName(departName);
        sysDepartment.setOrgType(orgType);
        sysDepartment.setParentId(parentId);
        sysDepartment.setTreeCode(getTreeCode(parentId));
        sysDepartment.setLevel(level);
        sysDepartment.setIsWarehouse(isWarehouse);
        sysDepartment.setOrgCode(getOrgCode(parentId, orgType));
        if(isWarehouse==0){
            sysDepartment.setOfficeType(officeType);
        }
        this.baseMapper.insert(sysDepartment);
        return sysDepartment;
    }
 
    @Override
    public void downloadImportTemplate(HttpServletResponse response) throws IOException {
 
        XSSFWorkbook workbook = new XSSFWorkbook(this.getClass().getResourceAsStream("/excel/department_import_template.xlsx"));
        response.setContentType("application/octet-stream;charset=utf-8");
        String fileName = "组织架构导入模板";
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (workbook != null) {
                workbook.close();
            }
        }
    }
 
    @Override
    public String getTreeCode(Integer parentId) {
 
        String treeId;
        String preTreeCode = "";
        StringBuilder sb = new StringBuilder();
        //
        SysDepartment sysDepartment = getById(parentId);
        if (sysDepartment != null) {
            preTreeCode = sysDepartment.getTreeCode();
        }
        //设置key
        String key = CacheConstant.SYS_DEPARTS_CACHE + parentId;
        int count = 0;
        //判断是否存在key
        if (redisTemplate.hasKey(key)) {
            count = (int) redisTemplate.opsForValue().get(key);
        }
        do {
            count++;
            treeId = sb.append(preTreeCode).append(org.apache.commons.lang.StringUtils.leftPad(String.valueOf(count), 4, "0")).toString();
            SysDepartment department = getOne(new QueryWrapper<SysDepartment>().lambda().eq(SysDepartment::getTreeCode, treeId));
            if (department == null) {
                break;
            }
            sb = new StringBuilder();
        } while (true);
        //设置缓存过期时间
        redisTemplate.opsForValue().set(key, count, 365, TimeUnit.DAYS);
        return treeId;
    }
 
    /**
     * 生成组织编码
     * 区域、医院、部门 4位 按组织类型不重复
     * 科室 3位 按医院不重复
     *
     * @param parentId
     * @param orgType
     * @return
     */
    @Override
    public String getOrgCode(Integer parentId, Integer orgType) {
 
        String key = CacheConstant.SYS_DEPARTMENT_ORG_CODE + orgType;
        int length = 4;
        //医院
        SysDepartment hospital = null;
        if (orgType.equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType())) {
            hospital = getHospital(parentId);
            key = key + ":" + hospital.getId();
            length = 3;
        }
        int count = 0;
        //判断是否存在key
        if (redisTemplate.hasKey(key)) {
            count = (int) redisTemplate.opsForValue().get(key);
        }
        //组织编码
        String orgCode;
        do {
            count++;
            orgCode = org.apache.commons.lang.StringUtils.leftPad(String.valueOf(count), length, "0");
            if (!orgType.equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType())) {
                SysDepartment department = getOne(new QueryWrapper<SysDepartment>().lambda().eq(SysDepartment::getOrgCode, orgCode).eq(SysDepartment::getOrgType, orgType).last("limit 1"));
                if (department == null) {
                    break;
                }
            } else {
                SysDepartment department = getOne(new QueryWrapper<SysDepartment>().lambda().likeRight(SysDepartment::getTreeCode, hospital.getTreeCode()).eq(SysDepartment::getOrgCode, orgCode).eq(SysDepartment::getOrgType, DepartmentEnum.OrgTypeEnum.OFFICE.getType()).last("limit 1"));
                if (department == null) {
                    break;
                }
            }
        } while (true);
        //设置缓存过期时间
        redisTemplate.opsForValue().set(key, count, 365, TimeUnit.DAYS);
        return orgCode;
    }
 
    /**
     * 获取医院分级列表
     *
     * @return
     */
    private List<SysDictItem> getHospitalLevelList() {
 
        SysDict sysDict = sysDictService.getOne(new QueryWrapper<SysDict>().lambda().eq(SysDict::getDictCode, "DEPARTMENT_LEVEL"));
        if (sysDict == null) {
            return new ArrayList<>();
        }
        return sysDictItemService.list(new QueryWrapper<SysDictItem>().lambda().eq(SysDictItem::getDictId, sysDict.getId()).eq(SysDictItem::getStatus, 1).orderByAsc(SysDictItem::getSortOrder));
    }
 
    @Override
    public boolean deleteCache(Integer id) {
 
        String key = CacheConstant.SYS_DEPARTMENT_CACHE + id;
        return redisTemplate.delete(key);
    }
 
    @Override
    public SysDepartment getSysDepartmentById(Integer id) {
 
        return baseMapper.getSysDepartmentById(id);
    }
 
    @Override
    public IPage<SysDepartmentVO> queryDepartmentPageList(Integer pageNo, Integer pageSize, SysDepartmentVO dto){
 
        Page<SysDepartmentVO> page = new Page<>(pageNo, pageSize);
        List<Integer> hospitalIdList = getSearchHospitalIdList(dto.getHospitalId());
        if (CollectionUtils.isEmpty(hospitalIdList)) {
            return page;
        }
        dto.setDepartmentIdList(hospitalIdList);
        IPage<SysDepartmentVO> result = baseMapper.queryDepartmentPageList(page, dto);
        SysDepartment sysDepartment = null;
        if (dto.getHospitalId() == null) {
            sysDepartment = this.getMyDepartment(EnvUtils.getUser().getId());
            if (sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.DEPARTMENT.getType()) || sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType())) {
                sysDepartment = this.getHospital(sysDepartment.getParentId());
            }
        } else {
            sysDepartment = this.getById(dto.getHospitalId());
        }
        //List<SysDepartment> sysDepartmentList = this.list(new QueryWrapper<SysDepartment>().lambda().likeRight(SysDepartment::getTreeCode, sysDepartment.getTreeCode()));
        //Map<Integer, SysDepartment> sysDepartmentMap = sysDepartmentList.stream().collect(Collectors.toMap(SysDepartment::getId, e -> e));
        List<SysDepartment> sysDepartmentList = this.list(new QueryWrapper<SysDepartment>().lambda().likeRight(SysDepartment::getTreeCode, sysDepartment.getTreeCode()));
        Map<Integer, SysDepartment> sysDepartmentMap = sysDepartmentList.stream().collect(Collectors.toMap(SysDepartment::getId, e -> e));
        for (SysDepartmentVO vo : result.getRecords()) {
            vo.setDepartmentIdList(new ArrayList<>());
            fillDepartmentPath(sysDepartmentMap, vo, "/");
        }
        return result;
    }
 
    /**
     * 填充用户列表中的区域、医院、部门、科室字段
     *
     * @param vo
     */
    private void fillDepartmentPath(Map<Integer, SysDepartment> sysDepartmentMap, SysDepartmentVO vo, String separateChar) {
 
        if (StringUtils.isEmpty(separateChar)) {
            separateChar = "/";
        }
        if (vo.getHospitalId() != null) {
            SysDepartment sysDepartment = sysDepartmentMap.get(vo.getHospitalId());
            if (sysDepartment == null) {
                sysDepartment = this.getById(vo.getHospitalId());
                if (sysDepartment != null) {
                    sysDepartmentMap.put(sysDepartment.getId(), sysDepartment);
                }
            }
            if (sysDepartment != null && sysDepartment.getId().equals(-1)) {
                vo.setArea(sysDepartment.getDepartName());
                vo.getDepartmentIdList().add(0, sysDepartment.getId());
                return;
            }
            while (sysDepartment != null && !sysDepartment.getId().equals(-1)) {
                //科室
                if (sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType())) {
                }
                //部门
                else if (sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.DEPARTMENT.getType())) {
                }
                //医院
                else if (sysDepartment.getOrgType().equals(DepartmentEnum.OrgTypeEnum.HOSPITAL.getType())) {
                    vo.setHospitalName(sysDepartment.getDepartName());
                }
                //区域
                else {
                    if (StringUtils.isNotEmpty(vo.getArea())) {
                        vo.setArea(sysDepartment.getDepartName() + separateChar + vo.getArea());
                    } else {
                        vo.setArea(sysDepartment.getDepartName());
                    }
                }
                vo.getDepartmentIdList().add(0, sysDepartment.getId());
                if (sysDepartmentMap.get(sysDepartment.getParentId()) == null) {
                    sysDepartment = this.getById(sysDepartment.getParentId());
                    if (sysDepartment != null) {
                        sysDepartmentMap.put(sysDepartment.getId(), sysDepartment);
                    }
                } else {
                    sysDepartment = sysDepartmentMap.get(sysDepartment.getParentId());
                }
            }
        }
    }
 
    @Override
    public List<Integer> getSearchHospitalIdList(Integer hospitalId) {
 
        if (hospitalId == null) {
            return this.listMyHospital(EnvUtils.getUser().getId()).stream().map(SysDepartment::getId).collect(Collectors.toList());
        } else {
            SysDepartment sysDepartment = this.getById(hospitalId);
            if (sysDepartment == null) {
                return new ArrayList<>();
            }
            List<SysDepartment> childrenList = this.list(new QueryWrapper<SysDepartment>().lambda().likeRight(SysDepartment::getTreeCode, sysDepartment.getTreeCode()).eq(SysDepartment::getOrgType, DepartmentEnum.OrgTypeEnum.HOSPITAL.getType()));
            if (CollectionUtils.isEmpty(childrenList)) {
                return new ArrayList<>();
            }
            return childrenList.stream().map(SysDepartment::getId).collect(Collectors.toList());
        }
    }
 
    @Override
    public IPage<CollectAppletAuthorizationListVO> getCollectAppletAuthorization(CollectAppletAuthorizationVO vo, Integer pageNo, Integer pageSize) {
        pageNo = vo.getPageNo();
        pageSize = vo.getPageSize();
        List<Integer> searchHospitalIdList = getSearchHospitalIdList(vo.getId());
 
        Page<CollectAppletAuthorizationListVO> pageParam = new Page<>(pageNo, pageSize);
        List<CollectAppletAuthorizationListVO> collectAppletAuthorization = this.baseMapper.getCollectAppletAuthorization(pageParam, vo, searchHospitalIdList);
        return pageParam.setRecords(collectAppletAuthorization);
    }
 
 
    @Override
    public void batchEditCollectAppletAuthorization(List<String> ids, Integer status, Integer userId) {
        this.baseMapper.batchEditCollectAppletAuthorization(ids, status, userId);
    }
 
 
    @Override
    public IPage<MonthlySmsAuthorizationListVO> getMonthlySmsAuthorization(MonthlySmsAuthorizationVO vo, Integer pageNo, Integer pageSize) {
        pageNo = vo.getPageNo();
        pageSize = vo.getPageSize();
        Page<MonthlySmsAuthorizationListVO> pageParam = new Page<>(pageNo, pageSize);
        return this.baseMapper.getMonthlySmsAuthorization(pageParam, vo);
    }
 
    @Override
    public void batchEditMonthlySmsAuthorization(List<String> ids, Integer status, Integer userId) {
        this.baseMapper.batchEditMonthlySmsAuthorization(ids, status, userId);
    }
 
    @Override
    public void sendMonthlySMS() {
        List<Map<String, Object>> monthlySMSHospitalData = this.baseMapper.getMonthlySMSHospitalData();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String month = sdf.format(calendar.getTime());
        for (Map<String, Object> map : monthlySMSHospitalData) {
            Integer id = Integer.valueOf(map.get("id").toString());
            String hospital = map.get("hospital").toString();
            String phone = map.get("phone").toString();
            List<Map<String, Object>> monthlySMSData = this.baseMapper.getMonthlySMSData(id, month, 1);
            if(monthlySMSData.size() > 0){
                //1新增 2已入库 3已出库
                //${hospitalName},您${month}月产废:感${wasteTypeA}kg;损${wasteTypeB}kg;药${wasteTypeC}kg;病${wasteTypeD}kg;化${wasteTypeE}kg;合计${total}kg。
                Map<String, String> map1 = new HashMap<>();
                map1.put("hospitalName", hospital);
                map1.put("month", month);
 
                BigDecimal total = new BigDecimal("0");
                for (Map<String, Object> datum : monthlySMSData) {
                    String wasteType = datum.get("wasteType").toString();
                    Double weight = Double.valueOf(datum.get("weight").toString());
                    switch (wasteType){
                        case "1":
                            map1.put("wasteTypeA", weight.toString());
                            break;
                        case "2":
                            map1.put("wasteTypeB", weight.toString());
                            break;
                        case "3":
                            map1.put("wasteTypeC", weight.toString());
                            break;
                        case "4":
                            map1.put("wasteTypeD", weight.toString());
                            break;
                        case "5":
                            map1.put("wasteTypeE", weight.toString());
                            break;
                    }
 
                    total = total.add(new BigDecimal(weight));
                }
 
                map1.put("total", total.toString());
                aliSmsService.sendMonthlySMS(phone, map1);
            }
        }
    }
    private Logger logger = LoggerFactory.getLogger(SysDepartmentServiceImpl.class);
    /**
     * 操作更新缓存
     */
    @Override
    public void joinCache(){
       /* List<SysDepartmentCascadeVO> myHospitalAndOfficeCascadeList = sysDepartmentBiz.getMyHospitalAndOfficeCascadeList(1);
        redisUtil.set("myHospitalAndOfficeCascadeList",myHospitalAndOfficeCascadeList);
        List<SysDepartmentCascadeVO> myHospitalCascadeList= sysDepartmentBiz.getMyHospitalCascadeList(1);
        redisUtil.set("myHospitalCascadeList",myHospitalCascadeList);
        List<SysDepartmentTreeModel> myDepartmentTreeList= sysDepartmentBiz.getMyDepartmentTreeList(1);
        redisUtil.set("myDepartmentTreeList",myDepartmentTreeList);
        logger.debug("加入缓存结束");
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.execute(new Runnable() {
            public void run() {
 
            }
        });*/
        // 创建CountDownLatch, 计数器初始值为4
        CountDownLatch latch = new CountDownLatch(4);
        long startTime = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        // 启动并行任务
        executorService.submit(() -> {
            try {
                long start = System.currentTimeMillis();
                List<SysDepartmentDTO> sysDepartmentDTOS = sysDepartmentBiz.getMyRegionTreeList(1);
                redisUtil.set("myRegionTreeList", sysDepartmentDTOS);
                logger.debug("myRegionTreeList耗时:{}秒", (System.currentTimeMillis() - start) / 1000);
            } finally {
                latch.countDown();
            }
        });
 
        executorService.submit(() -> {
            try {
                long start = System.currentTimeMillis();
                List<SysDepartmentTreeModel> myDepartmentTreeList = sysDepartmentBiz.getMyDepartmentTreeList(1);
                redisUtil.set("myDepartmentTreeList", myDepartmentTreeList);
                logger.debug("myDepartmentTreeList耗时:{}秒", (System.currentTimeMillis() - start) / 1000);
            } finally {
                latch.countDown();
            }
        });
 
        executorService.submit(() -> {
            try {
                long start = System.currentTimeMillis();
                List<SysDepartmentCascadeVO> myHospitalAndOfficeCascadeList = sysDepartmentBiz.getMyHospitalAndOfficeCascadeListV2(1);
                redisUtil.set("myHospitalAndOfficeCascadeList", myHospitalAndOfficeCascadeList);
                logger.debug("myHospitalAndOfficeCascadeList耗时:{}秒", (System.currentTimeMillis() - start) / 1000);
            } finally {
                latch.countDown();
            }
        });
 
        executorService.submit(() -> {
            try {
                long start = System.currentTimeMillis();
                List<SysDepartmentCascadeVO> myHospitalCascadeList = sysDepartmentBiz.getMyHospitalCascadeList(1);
                redisUtil.set("myHospitalCascadeList", myHospitalCascadeList);
                logger.debug("myHospitalCascadeList耗时:{}秒", (System.currentTimeMillis() - start) / 1000);
            } finally {
                latch.countDown();
            }
        });
        // 等待所有任务完成
        try {
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error("任务执行被中断", e);
        } finally {
            executorService.shutdown();
            logger.debug("总计耗时:{}秒", (System.currentTimeMillis() - startTime) / 1000);
            logger.debug("更新缓存结束");
        }
    }
 
    @Override
    public List<Integer> getDeptIdListByTreeCode(String treeCode) {
        return baseMapper.getDeptIdListByTreeCode(treeCode);
    }
 
    @Override
    public IPage<SysDepartmentOfficeVO> queryOfficePageList(SysDepartmentOfficeQueryDTO queryVO) {
        Page<SysDepartmentOfficeVO> page = new Page<>(queryVO.getPageNo(), queryVO.getPageSize());
 
        // 获取当前用户权限范围内的部门ID列表
        SysDepartment sysDepartment = sysDepartmentService.getById(queryVO.getHospitalId());
        if (Objects.isNull(sysDepartment)) {
            return page;
        }
        IPage<SysDepartmentOfficeVO> result = baseMapper.queryOfficePageList(page, queryVO, sysDepartment.getTreeCode());
 
        // 修正医院名称:科室的父级可能是部门而非医院,需要递归向上查找真正的医院
        for (SysDepartmentOfficeVO vo : result.getRecords()) {
            SysDepartment hospital = getHospital(vo.getParentId());
            if (hospital != null) {
                vo.setHospitalName(hospital.getDepartName());
            }
        }
        return result;
    }
 
    @Override
    @Transactional
    @AutoLog(value = "更新科室信息")
    public boolean updateOfficeInfo(SysDepartmentOfficeUpdateDTO updateVO) {
        SysDepartment department = getById(updateVO.getId());
        if (department == null) {
            throw new BusinessException(ErrorCode.ERR_500, "科室不存在");
        }
        
        if (!department.getOrgType().equals(DepartmentEnum.OrgTypeEnum.OFFICE.getType())) {
            throw new BusinessException(ErrorCode.ERR_500, "只能修改科室信息");
        }
        
        // 检查科室名称是否重复(同一医院下)
        SysDepartment existDepartment = getOne(new QueryWrapper<SysDepartment>().lambda()
                .eq(SysDepartment::getParentId, department.getParentId())
                .eq(SysDepartment::getDepartName, updateVO.getDepartName())
                .ne(SysDepartment::getId, updateVO.getId())
                .eq(SysDepartment::getDelFlag, 0));
        
        if (existDepartment != null) {
            throw new BusinessException(ErrorCode.ERR_500, "同一医院下科室名称不能重复");
        }
        
        // 更新科室信息
        department.setDepartName(updateVO.getDepartName());
        department.setDepartmentLocation(updateVO.getDepartmentLocation());
        department.setBedCount(updateVO.getBedCount());
        department.setWasteThreshold(updateVO.getWasteThreshold());
        department.setUpdateTime(new Date());
        department.setUpdateBy(EnvUtils.getUser().getId());
        
        return updateById(department);
    }
 
}