mitao
2025-03-28 4922e5fb02c3a095791a6f6e65c70883054fa3d9
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
package com.sinata.system.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinata.common.constant.CacheConstants;
import com.sinata.common.core.domain.entity.SysUser;
import com.sinata.common.entity.PageDTO;
import com.sinata.common.exception.ServiceException;
import com.sinata.common.utils.BeanUtils;
import com.sinata.common.utils.CollUtils;
import com.sinata.common.utils.SecurityUtils;
import com.sinata.common.utils.StringUtils;
import com.sinata.system.domain.MwApplication;
import com.sinata.system.domain.SysDepartment;
import com.sinata.system.domain.SysDepartmentInfo;
import com.sinata.system.domain.dto.DisposalUnitDTO;
import com.sinata.system.domain.dto.MedicalInstitutionDTO;
import com.sinata.system.domain.dto.RegulatoryUnitDTO;
import com.sinata.system.domain.dto.SysDepartmentDTO;
import com.sinata.system.domain.query.DepartmentQuery;
import com.sinata.system.domain.vo.DisposalUnitVO;
import com.sinata.system.domain.vo.MedicalInstitutionVO;
import com.sinata.system.domain.vo.RegulatoryUnitVO;
import com.sinata.system.domain.vo.SysDepartmentVO;
import com.sinata.system.enums.DepartmentEnum;
import com.sinata.system.mapper.SysDepartmentMapper;
import com.sinata.system.service.ISysUserService;
import com.sinata.system.service.SysDepartmentInfoService;
import com.sinata.system.service.SysDepartmentService;
import com.sinata.system.service.SysUserDepartmentService;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 区域表 服务实现类
 * </p>
 *
 * @author mitao
 * @since 2024-12-02
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy})
public class SysDepartmentServiceImpl extends ServiceImpl<SysDepartmentMapper, SysDepartment> implements SysDepartmentService {
    private final SysUserDepartmentService sysUserDepartmentService;
    private final RedisTemplate<Object, Object> redisTemplate;
    private final SysDepartmentInfoService sysDepartmentInfoService;
    private final ISysUserService sysUserService;
    /**
     * 获取区域树
     * @return
     */
    @Override
    public List<SysDepartmentVO> listByType(Integer type) {
        List<SysDepartmentVO> root = new ArrayList<>();
        SysDepartment myDepartment = getMyDepartment();
        if (Objects.isNull(myDepartment)) {
            return root;
        }
        Map<Long, List<SysDepartment>> childrenMap;
        switch (type) {
            case 1:
                if (!myDepartment.getOrgType().equals(DepartmentEnum.REGION.getCode())) {
                    return root;
                }
                childrenMap = getChildrenDepartmentByOrgType(myDepartment, Collections.singletonList(DepartmentEnum.REGION.getCode()));
                break;
            case 2:
                childrenMap = getChildrenDepartmentByOrgType(myDepartment, Arrays.asList(DepartmentEnum.REGION.getCode(), DepartmentEnum.MEDICAL_INSTITUTION.getCode()));
                break;
            case 3:
                childrenMap = getChildrenDepartmentByOrgType(myDepartment, Arrays.asList(DepartmentEnum.REGION.getCode(), DepartmentEnum.DISPOSAL_UNIT.getCode()));
                break;
            case 4:
                childrenMap = getChildrenDepartmentByOrgType(myDepartment, Arrays.asList(DepartmentEnum.REGION.getCode(), DepartmentEnum.REGULATORY_UNIT.getCode()));
                break;
            case 5:
                childrenMap = getChildrenDepartmentByOrgType(myDepartment, Arrays.asList(DepartmentEnum.REGION.getCode(), DepartmentEnum.MEDICAL_INSTITUTION.getCode(), DepartmentEnum.DISPOSAL_UNIT.getCode()));
                break;
            case 6:
                childrenMap = getChildrenDepartmentByOrgType(myDepartment, Arrays.asList(DepartmentEnum.REGION.getCode(), DepartmentEnum.MEDICAL_INSTITUTION.getCode(), DepartmentEnum.REGULATORY_UNIT.getCode()));
                break;
            case 7:
                childrenMap = getChildrenDepartmentByOrgType(myDepartment, Arrays.asList(DepartmentEnum.REGION.getCode(), DepartmentEnum.DISPOSAL_UNIT.getCode(), DepartmentEnum.REGULATORY_UNIT.getCode()));
                break;
            default:
                childrenMap = getChildrenDepartmentByOrgType(myDepartment, null);
        }
        SysDepartmentVO sysDepartmentVO = fillChildrenTreeModel(myDepartment, childrenMap);
        switch (type) {
            case 2:
            case 3:
            case 4:
                filterEmptyChildren(sysDepartmentVO.getChildren());
                break;
        }
        root.add(sysDepartmentVO);
        return root;
    }
 
    /**
     * 移除子节点为空的区域
     *
     * @param departments
     */
    private void filterEmptyChildren(List<SysDepartmentVO> departments) {
        if (departments == null) {
            return;
        }
 
        Iterator<SysDepartmentVO> iterator = departments.iterator();
        while (iterator.hasNext()) {
            SysDepartmentVO department = iterator.next();
 
            // 递归过滤子节点
            filterEmptyChildren(department.getChildren());
 
            // 如果 orgType == 1 且 children 为空,则移除当前节点
            if (department.getOrgType() == 1 && department.getChildren().isEmpty()) {
                iterator.remove();
            }
        }
    }
 
    /**
     * @param myDepartment
     * @param orgTypes     查询区域类型列表
     * @return
     */
    @NotNull
    private Map<Long, List<SysDepartment>> getChildrenDepartmentByOrgType(SysDepartment myDepartment, List<Integer> orgTypes) {
        List<SysDepartment> sysDepartmentList = this.lambdaQuery()
                .in(CollUtils.isNotEmpty(orgTypes), SysDepartment::getOrgType, orgTypes)
                .likeRight(SysDepartment::getTreeCode, myDepartment.getTreeCode())
                .orderByDesc(SysDepartment::getCreateTime)
                .list();
        return sysDepartmentList.stream()
                .collect(Collectors.groupingBy(SysDepartment::getParentId));
    }
 
    @NotNull
    private Map<Long, List<SysDepartment>> getChildrenDepartmentMap(SysDepartment myDepartment) {
        List<SysDepartment> sysDepartmentList = this.lambdaQuery()
                .ne(SysDepartment::getOrgType , 4)
                .ne(SysDepartment::getOrgType , 3)
                .ne(SysDepartment::getOrgType , 2)
                .likeRight(SysDepartment::getTreeCode, myDepartment.getTreeCode())
                .orderByDesc(SysDepartment::getCreateTime)
                .list();
        return sysDepartmentList.stream()
                .collect(Collectors.groupingBy(SysDepartment::getParentId));
    }
    @Override
    public SysDepartment getDepartmentByParentId(Long parentId) {
        return this.lambdaQuery().eq(SysDepartment::getId, parentId).one();
    }
 
    /**
     * 获取区域树
     *
     * @return
     */
    @Override
    public List<SysDepartmentVO> getRegionTree(String keyword) {
        List<SysDepartmentVO> root = new ArrayList<>();
        SysDepartment currentDepartment = getMyDepartment();
        if (Objects.isNull(currentDepartment)) {
            return root;
        }
        if (!currentDepartment.getOrgType().equals(DepartmentEnum.REGION.getCode())) {
            return root;
        }
        Map<Long, List<SysDepartment>> childrenMap = getChildrenDepartmentByOrgType(currentDepartment, Collections.singletonList(DepartmentEnum.REGION.getCode()));
        SysDepartmentVO sysDepartmentVO = fillChildrenTreeModel(currentDepartment, childrenMap);
        root.add(sysDepartmentVO);
        if (StringUtils.isNotBlank(keyword)) {
            treeMatch(root, keyword);
        }
        return root;
    }
    @Override
    public List<SysDepartmentVO> getRegionTree1(String keyword) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
 
        List<SysDepartmentVO> root = new ArrayList<>();
        SysDepartment sysDepartment = this.baseMapper.selectById(sysUser.getDepartmentId());
        SysDepartment currentDepartment = this.baseMapper.selectById(sysDepartment.getParentId());
        if (Objects.isNull(currentDepartment)) {
            return root;
        }
        if (!currentDepartment.getOrgType().equals(DepartmentEnum.REGION.getCode())) {
            return root;
        }
        Map<Long, List<SysDepartment>> childrenMap = getChildrenDepartmentByOrgType(currentDepartment, Collections.singletonList(DepartmentEnum.REGION.getCode()));
        SysDepartmentVO sysDepartmentVO = fillChildrenTreeModel(currentDepartment, childrenMap);
        root.add(sysDepartmentVO);
        if (StringUtils.isNotBlank(keyword)) {
            treeMatch(root, keyword);
        }
        return root;
    }
    public List<SysDepartmentVO> getRegionTree2(String keyword) {
 
//        SysDepartment currentDepartment = getMyDepartment();
 
        List<SysDepartmentVO> root = new ArrayList<>();
        SysDepartment currentDepartment = getMyDepartment();
        if (Objects.isNull(currentDepartment)) {
            return root;
        }
//        if (!currentDepartment.getOrgType().equals(DepartmentEnum.REGION.getCode())) {
//            return root;
//        }
        Map<Long, List<SysDepartment>> childrenMap = getChildrenDepartmentMap(currentDepartment);
        SysDepartmentVO sysDepartmentVO = fillChildrenTreeModel(currentDepartment, childrenMap);
        Integer orgType = sysDepartmentVO.getOrgType();
        if (sysDepartmentVO.getOrgType()==4){
            SysDepartment byId = this.getById(sysDepartmentVO.getParentId());
            childrenMap = getChildrenDepartmentMap(byId);
            sysDepartmentVO = fillChildrenTreeModel(byId, childrenMap);
//            sysDepartmentVO.setChildren(new ArrayList<>());
        }
        if (sysDepartmentVO.getTreeCode().length()==10){
            SysDepartment sysDepartment = this.baseMapper.selectById(sysDepartmentVO.getParentId());
            SysDepartmentVO sysDepartmentVO1 = new SysDepartmentVO();
            BeanUtils.copyProperties(sysDepartment,sysDepartmentVO1);
            List<SysDepartmentVO> root1 = new ArrayList<>();
            root1.add(sysDepartmentVO);
            sysDepartmentVO1.setChildren(root1);
            sysDepartmentVO = sysDepartmentVO1;
        }
        if (sysDepartmentVO.getTreeCode().length()>=14){
            SysDepartment sysDepartment = this.baseMapper.selectById(sysDepartmentVO.getParentId());
            SysDepartmentVO sysDepartmentVO1 = new SysDepartmentVO();
            BeanUtils.copyProperties(sysDepartment,sysDepartmentVO1);
            List<SysDepartmentVO> root1 = new ArrayList<>();
                root1.add(sysDepartmentVO);
            sysDepartmentVO1.setChildren(root1);
 
 
            SysDepartment sysDepartment2 = this.baseMapper.selectById(sysDepartment.getParentId());
            SysDepartmentVO sysDepartmentVO2 = new SysDepartmentVO();
            BeanUtils.copyProperties(sysDepartment2,sysDepartmentVO2);
            List<SysDepartmentVO> root2 = new ArrayList<>();
            root2.add(sysDepartmentVO1);
                sysDepartmentVO2.setChildren(root2);
            sysDepartmentVO = sysDepartmentVO2;
        }
        root.add(sysDepartmentVO);
        if (StringUtils.isNotBlank(keyword)) {
            treeMatch(root, keyword);
        }
        return root;
    }
 
    /**
     * 获取当前登录用户所属区域
     *
     * @return
     */
    @Override
    public SysDepartment getMyDepartment() {
        Long userId = SecurityUtils.getUserId();
        return baseMapper.getDepartmentByUserId(userId);
    }
 
    /**
     * 构建树结构
     *
     * @param myDepartment
     * @param childrenMap
     * @return
     */
    private SysDepartmentVO fillChildrenTreeModel(SysDepartment myDepartment, Map<Long, List<SysDepartment>> childrenMap) {
        SysDepartmentVO currentNode = BeanUtils.copyBean(myDepartment, SysDepartmentVO.class);
        // 使用部门映射直接获取子部门,避免了遍历整个列表
        List<SysDepartment> children = childrenMap.getOrDefault(currentNode.getId(),
                Collections.emptyList());
        List<SysDepartmentVO> childrenList = children.stream().map(child -> fillChildrenTreeModel(child, childrenMap)).collect(Collectors.toList());
        currentNode.setChildren(childrenList.isEmpty() ? new ArrayList<>() : childrenList);
        childrenMap.remove(currentNode.getId());
        return currentNode;
    }
 
    /**
     * 递归方法
     *
     * @param tree    任意层级的目录集合
     * @param keyword 关键字
     */
    public static void treeMatch(List<SysDepartmentVO> tree, String keyword) {
        Iterator<SysDepartmentVO> iter = tree.iterator();
        while (iter.hasNext()) {
            // 获取当前遍历到的目录
            SysDepartmentVO department = iter.next();
            // 如果当前目录名称包含关键字,则什么也不做(不移除),否则就看下一级
            if (!department.getDepartmentName().contains(keyword)) {
                // 取出下一级目录集合
                List<SysDepartmentVO> childrenSysDepartmentVOList = department.getChildren();
                // 递归
                if (!CollUtils.isEmpty(childrenSysDepartmentVOList)) {
                    treeMatch(childrenSysDepartmentVOList, keyword);
                }
                // 下一级目录看完了,如果下一级目录全部被移除,则移除当前目录
                if (CollUtils.isEmpty(department.getChildren())) {
                    iter.remove();
                }
            }
        }
    }
 
    /**
     * 新增区域
     *
     * @param dto
     * @return
     */
    @Override
    public void addRegion(SysDepartmentDTO dto) {
        SysDepartment currentDepartment = getMyDepartment();
        if (Objects.isNull(currentDepartment)) {
            throw new ServiceException("无操作权限");
        }
        SysDepartment parent = this.getById(dto.getParentId());
        if (Objects.isNull(parent)) {
            throw new ServiceException("找不到对应父级组织");
        }
        if (!parent.getTreeCode().startsWith(currentDepartment.getTreeCode())) {
            throw new ServiceException("无操作权限");
        }
        Long count = this.lambdaQuery().eq(SysDepartment::getDepartmentName, dto.getDepartmentName())
                .eq(SysDepartment::getOrgType, DepartmentEnum.REGION.getCode())
                .count();
        if (count > 0) {
            throw new ServiceException("区域已存在");
        }
        SysDepartment department = BeanUtils.copyBean(dto, SysDepartment.class);
        //获取部门树编码
        department.setOrgType(DepartmentEnum.REGION.getCode());
        department.setTreeCode(generateTreeCode(dto.getParentId()));
        department.setOrgCode(getOrgCode(dto.getParentId(), DepartmentEnum.REGION.getCode()));
        save(department);
    }
 
    /**
     * 编辑区域
     *
     * @param dto
     * @return
     */
    @Override
    public void editRegion(SysDepartmentDTO dto) {
        SysDepartment currentDepartment = getMyDepartment();
        if (Objects.isNull(currentDepartment)) {
            throw new ServiceException("无操作权限");
        }
        SysDepartment parent = this.getById(dto.getParentId());
        if (Objects.isNull(parent)) {
            throw new ServiceException("找不到对应父级组织");
        }
        if (!parent.getTreeCode().startsWith(currentDepartment.getTreeCode())) {
            throw new ServiceException("无操作权限");
        }
        Long count = this.lambdaQuery().eq(SysDepartment::getDepartmentName, dto.getDepartmentName())
                .eq(SysDepartment::getOrgType, DepartmentEnum.REGION.getCode())
                .ne(SysDepartment::getId, dto.getId())
                .count();
        if (count > 0) {
            throw new ServiceException("区域已存在");
        }
        SysDepartment department = BeanUtils.copyBean(dto, SysDepartment.class);
        SysDepartment sysDepartment = getById(dto.getId());
        if (!dto.getParentId().equals(sysDepartment.getParentId())) {
            //获取部门树编码
            department.setTreeCode(generateTreeCode(dto.getParentId()));
        }
        updateById(department);
    }
 
    /**
     * 获取树编码
     *
     * @param parentId
     * @return
     */
    @Override
    public String generateTreeCode(Long parentId) {
 
        String treeId;
        String preTreeCode = "";
        StringBuilder sb = new StringBuilder();
 
        SysDepartment sysDepartment = getById(parentId);
        if (sysDepartment != null) {
            preTreeCode = sysDepartment.getTreeCode();
        }
        //设置key
 
        String key = CacheConstants.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(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位 按组织类型不重复
     *
     * @param parentId
     * @param orgType
     * @return
     */
    @Override
    public String getOrgCode(Long parentId, Integer orgType) {
 
        String key = CacheConstants.SYS_DEPARTMENT_ORG_CODE + orgType;
        int length = 4;
        int count = 0;
        //判断是否存在key
        if (redisTemplate.hasKey(key)) {
            count = (int) redisTemplate.opsForValue().get(key);
        }
        //组织编码
        String orgCode;
        do {
            count++;
            orgCode = StringUtils.leftPad(String.valueOf(count), length, "0");
            SysDepartment department = getOne(new QueryWrapper<SysDepartment>().lambda().eq(SysDepartment::getOrgCode, orgCode).eq(SysDepartment::getOrgType, orgType).last("limit 1"));
            if (department == null) {
                break;
            }
        } while (true);
        //设置缓存过期时间
        redisTemplate.opsForValue().set(key, count, 365, TimeUnit.DAYS);
        return orgCode;
    }
 
    @Override
    public void deleteRegion(Long id) {
        SysDepartment myDepartment = getMyDepartment();
        SysDepartment sysDepartment = getById(id);
        if (!sysDepartment.getTreeCode().startsWith(myDepartment.getTreeCode())) {
            throw new ServiceException("无操作权限");
        }
        List<SysDepartment> sysDepartmentList = this.lambdaQuery()
                .likeRight(SysDepartment::getTreeCode, sysDepartment.getTreeCode())
                .eq(SysDepartment::getOrgType, DepartmentEnum.REGION.getCode())
                .orderByDesc(SysDepartment::getCreateTime)
                .list();
        List<Long> departmentIds = sysDepartmentList.stream().map(SysDepartment::getId).collect(Collectors.toList());
        Long count = sysUserService.lambdaQuery().in(SysUser::getDepartmentId, departmentIds).count();
        if (count > 0) {
            throw new ServiceException("该区域已关联用户,无法删除");
        }
        removeById(id);
    }
 
    /**
     * 医疗机构分页列表
     *
     * @param query
     * @return
     */
    @Override
    public PageDTO<MedicalInstitutionVO> pageMedicalList(DepartmentQuery query) {
        String treeCode;
        if (Objects.isNull(query.getDepartmentId())) {
            SysDepartment department = getMyDepartment();
            treeCode = department.getTreeCode();
        } else {
            SysDepartment department = getById(query.getDepartmentId());
            //如果是处置单位,则获取父级部门
            if (department.getOrgType().equals(DepartmentEnum.DISPOSAL_UNIT.getCode())) {
                department = getDepartmentByParentId(department.getParentId());
            }
            treeCode = department.getTreeCode();
        }
        if (StringUtils.isBlank(treeCode)) {
            return PageDTO.empty(0L, 0L);
        }
        Page<MedicalInstitutionVO> page = baseMapper.pageMedicalList(new Page<>(query.getPageCurr(), query.getPageSize()), query.getDepartmentName(), query.getContactPerson(), query.getContactPhone(), treeCode);
        return PageDTO.of(page);
    }
 
    /**
     * 新增医疗机构
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addMedical(MedicalInstitutionDTO dto) {
        SysDepartment currentDepartment = getMyDepartment();
        if (Objects.isNull(currentDepartment)) {
            throw new ServiceException("无操作权限");
        }
        SysDepartment parent = this.getById(dto.getParentId());
        if (Objects.isNull(parent)) {
            throw new ServiceException("找不到对应父级组织");
        }
        if (!parent.getTreeCode().startsWith(currentDepartment.getTreeCode())) {
            throw new ServiceException("无操作权限");
        }
        Long count = this.lambdaQuery().eq(SysDepartment::getDepartmentName, dto.getDepartmentName())
                .eq(SysDepartment::getOrgType, DepartmentEnum.MEDICAL_INSTITUTION.getCode())
                .count();
        if (count > 0) {
            throw new ServiceException("医疗机构已存在");
        }
        SysDepartment department = BeanUtils.copyBean(dto, SysDepartment.class);
        department.setTreeCode(generateTreeCode(parent.getId()));
        department.setOrgCode(getOrgCode(parent.getId(), DepartmentEnum.MEDICAL_INSTITUTION.getCode()));
        department.setOrgType(DepartmentEnum.MEDICAL_INSTITUTION.getCode());
        //查询父级完整区域
        String region = getRegionName(parent);
        department.setRegion(region);
        save(department);
        SysDepartmentInfo sysDepartmentInfo = BeanUtils.copyBean(dto, SysDepartmentInfo.class);
        sysDepartmentInfo.setDepartmentId(department.getId());
        sysDepartmentInfoService.save(sysDepartmentInfo);
    }
 
    /**
     * 根据父级区域id查询处置单位列表
     *
     * @param id
     * @return
     */
    @Override
    public List<DisposalUnitVO> getDisposalUnitListByParentId(Long id) {
        List<DisposalUnitVO> disposalUnitList = null;
        SysDepartment parent = getById(id);
        if (Objects.nonNull(parent)) {
            //查询处置单位
            disposalUnitList = baseMapper.getDisposalUnitListByTreeCode(parent.getTreeCode());
        }
        return disposalUnitList;
    }
 
    /**
     * 获取完整区域
     *
     * @param department
     * @return
     */
    @Override
    public String getRegionName(SysDepartment department) {
        String region = department.getDepartmentName();
        SysDepartment sysDepartment = this.lambdaQuery().eq(SysDepartment::getId, department.getParentId()).ne(SysDepartment::getId, -1).one();
        if (Objects.nonNull(sysDepartment)) {
            region = getRegionName(sysDepartment) + region;
        }
        return region;
    }
 
    /**
     * 编辑医疗机构
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editMedical(MedicalInstitutionDTO dto) {
        if (Objects.isNull(dto.getId())) {
            throw new ServiceException("id不能为空");
        }
        SysDepartment sysDepartment = getById(dto.getId());
        if (Objects.isNull(sysDepartment)) {
            throw new ServiceException("医疗机构不存在");
        }
        SysDepartment currentDepartment = getMyDepartment();
        if (Objects.isNull(currentDepartment)) {
            throw new ServiceException("无操作权限");
        }
 
        SysDepartment parent = this.getById(dto.getParentId());
        if (Objects.isNull(parent)) {
            throw new ServiceException("找不到对应父级组织");
        }
        if (!parent.getTreeCode().startsWith(currentDepartment.getTreeCode())) {
            throw new ServiceException("无操作权限");
        }
        Long count = this.lambdaQuery().eq(SysDepartment::getDepartmentName, dto.getDepartmentName())
                .eq(SysDepartment::getOrgType, DepartmentEnum.MEDICAL_INSTITUTION.getCode()).ne(SysDepartment::getId, dto.getId())
                .count();
        if (count > 0) {
            throw new ServiceException("机构已存在");
        }
        SysDepartment department = BeanUtils.copyBean(dto, SysDepartment.class);
        if (!department.getParentId().equals(sysDepartment.getParentId())) {
            department.setTreeCode(generateTreeCode(parent.getId()));
            //查询父级完整区域
            String region = getRegionName(parent);
            department.setRegion(region);
        }
        updateById(department);
        sysDepartmentInfoService.lambdaUpdate().eq(SysDepartmentInfo::getDepartmentId, sysDepartment.getId()).remove();
        SysDepartmentInfo sysDepartmentInfo = BeanUtils.copyBean(dto, SysDepartmentInfo.class);
        sysDepartmentInfo.setDepartmentId(department.getId());
        sysDepartmentInfo.setId(null);
        sysDepartmentInfoService.save(sysDepartmentInfo);
    }
 
    /**
     * 医疗机构详情
     *
     * @param id
     * @return
     */
    @Override
    public MedicalInstitutionVO getMedicalDetailById(Long id) {
        MedicalInstitutionVO vo = baseMapper.getMedicalDetailById(id);
        List<DisposalUnitVO> disposalUnitList = getDisposalUnitListByParentId(vo.getParentId());
        vo.setDisposalUnitList(disposalUnitList);
        return vo;
    }
 
    /**
     * 删除医疗机构
     *
     * @param id
     */
    @Override
    public void deleteMedical(Long id) {
        Long count = sysUserService.lambdaQuery().eq(SysUser::getDepartmentId, id).count();
        if (count > 0) {
            throw new ServiceException("该医疗机构已关联用户,无法删除");
        }
        removeById(id);
    }
 
    /**
     * 处置单位分页列表
     *
     * @param query
     * @return
     */
    @Override
    public PageDTO<DisposalUnitVO> pageDisposalUnitList(DepartmentQuery query) {
        String treeCode = getTreeCodeByDepartmentId(query.getDepartmentId());
        if (StringUtils.isBlank(treeCode)) {
            return PageDTO.empty(0L, 0L);
        }
        Page<DisposalUnitVO> page = baseMapper.pageRegulatoryUnitList(new Page<>(query.getPageCurr(), query.getPageSize()), query.getDepartmentId(), query.getDepartmentName(), query.getContactPerson(), query.getContactPhone(), treeCode);
        return PageDTO.of(page);
    }
 
    /**
     * 新增处置单位
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDisposalUnit(DisposalUnitDTO dto) {
        SysDepartment currentDepartment = getMyDepartment();
        if (Objects.isNull(currentDepartment)) {
            throw new ServiceException("无操作权限");
        }
        SysDepartment parent = this.getById(dto.getParentId());
        if (Objects.isNull(parent)) {
            throw new ServiceException("找不到对应父级组织");
        }
        if (!parent.getTreeCode().startsWith(currentDepartment.getTreeCode())) {
            throw new ServiceException("无操作权限");
        }
        Long count = this.lambdaQuery().eq(SysDepartment::getDepartmentName, dto.getDepartmentName())
                .eq(SysDepartment::getOrgType, DepartmentEnum.DISPOSAL_UNIT.getCode())
                .count();
        if (count > 0) {
            throw new ServiceException("处置单位已存在");
        }
        SysDepartment department = BeanUtils.copyBean(dto, SysDepartment.class);
        department.setTreeCode(generateTreeCode(parent.getId()));
        department.setOrgCode(getOrgCode(parent.getId(), DepartmentEnum.DISPOSAL_UNIT.getCode()));
        department.setOrgType(DepartmentEnum.DISPOSAL_UNIT.getCode());
        //查询父级完整区域
        String region = getRegionName(parent);
        department.setRegion(region);
        save(department);
        SysDepartmentInfo sysDepartmentInfo = BeanUtils.copyBean(dto, SysDepartmentInfo.class);
        sysDepartmentInfo.setDepartmentId(department.getId());
        sysDepartmentInfoService.save(sysDepartmentInfo);
    }
 
    /**
     * 编辑处置单位
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editDisposalUnit(DisposalUnitDTO dto) {
        if (Objects.isNull(dto.getId())) {
            throw new ServiceException("id不能为空");
        }
        SysDepartment sysDepartment = getById(dto.getId());
        if (Objects.isNull(sysDepartment)) {
            throw new ServiceException("处置单位不存在");
        }
        SysDepartment currentDepartment = getMyDepartment();
        if (Objects.isNull(currentDepartment)) {
            throw new ServiceException("无操作权限");
        }
        SysDepartment parent = this.getById(dto.getParentId());
        if (Objects.isNull(parent)) {
            throw new ServiceException("找不到对应父级组织");
        }
        if (!parent.getTreeCode().startsWith(currentDepartment.getTreeCode())) {
            throw new ServiceException("无操作权限");
        }
        Long count = this.lambdaQuery().eq(SysDepartment::getDepartmentName, dto.getDepartmentName())
                .eq(SysDepartment::getOrgType, DepartmentEnum.DISPOSAL_UNIT.getCode()).ne(SysDepartment::getId, dto.getId())
                .count();
        if (count > 0) {
            throw new ServiceException("处置单位已存在");
        }
        SysDepartment department = BeanUtils.copyBean(dto, SysDepartment.class);
 
        if (!department.getParentId().equals(sysDepartment.getParentId())) {
            department.setTreeCode(generateTreeCode(parent.getId()));
            //查询父级完整区域
            String region = getRegionName(parent);
            department.setRegion(region);
        }
        updateById(department);
        sysDepartmentInfoService.lambdaUpdate().eq(SysDepartmentInfo::getDepartmentId, sysDepartment.getId()).remove();
        SysDepartmentInfo sysDepartmentInfo = BeanUtils.copyBean(dto, SysDepartmentInfo.class);
        sysDepartmentInfo.setId(null);
        sysDepartmentInfo.setDepartmentId(department.getId());
        sysDepartmentInfoService.save(sysDepartmentInfo);
    }
 
    /**
     * 处置单位详情
     *
     * @param id
     * @return
     */
    @Override
    public DisposalUnitVO getDisposalUnitDetailById(Long id) {
        return baseMapper.getDisposalUnitDetailById(id);
    }
 
    @Override
    public void deleteDisposalUnit(Long id) {
        Long count = sysUserService.lambdaQuery().eq(SysUser::getDepartmentId, id).count();
        if (count > 0) {
            throw new ServiceException("该处置单位构已关联用户,无法删除");
        }
        removeById(id);
    }
 
    /**
     * 监管单位分页列表
     *
     * @param query
     * @return
     */
    @Override
    public PageDTO<RegulatoryUnitVO> pageRegulatoryUnitList(DepartmentQuery query) {
        String treeCode = getTreeCodeByDepartmentId(query.getDepartmentId());
        if (StringUtils.isBlank(treeCode)) {
            return PageDTO.empty(0L, 0L);
        }
        Page<SysDepartment> page = this.lambdaQuery().eq(Objects.nonNull(query.getDepartmentId()), SysDepartment::getParentId, query.getDepartmentId())
                .likeRight(StringUtils.isNotBlank(treeCode), SysDepartment::getTreeCode, treeCode)
                .like(StringUtils.isNotEmpty(query.getDepartmentName()), SysDepartment::getDepartmentName, query.getDepartmentName())
                .like(StringUtils.isNotBlank(query.getContactPerson()), SysDepartment::getContactPerson, query.getContactPerson())
                .like(StringUtils.isNotBlank(query.getContactPhone()), SysDepartment::getContactPhone, query.getContactPhone())
                .eq(SysDepartment::getOrgType, DepartmentEnum.REGULATORY_UNIT.getCode())
                .orderByDesc(SysDepartment::getCreateTime)
                .page(new Page<>(query.getPageCurr(), query.getPageSize()));
        return PageDTO.of(page, RegulatoryUnitVO.class);
    }
 
    /**
     * 新增监管单位
     *
     * @param dto
     */
    @Override
    public void addRegulatoryUnit(RegulatoryUnitDTO dto) {
        SysDepartment currentDepartment = getMyDepartment();
        if (Objects.isNull(currentDepartment)) {
            throw new ServiceException("无操作权限");
        }
        SysDepartment parent = this.getById(dto.getParentId());
        if (Objects.isNull(parent)) {
            throw new ServiceException("找不到对应父级组织");
        }
        if (!parent.getTreeCode().startsWith(currentDepartment.getTreeCode())) {
            throw new ServiceException("无操作权限");
        }
        Long count = this.lambdaQuery().eq(SysDepartment::getDepartmentName, dto.getDepartmentName())
                .eq(SysDepartment::getOrgType, DepartmentEnum.REGULATORY_UNIT.getCode())
                .count();
        if (count > 0) {
            throw new ServiceException("监管单位已存在");
        }
        SysDepartment department = BeanUtils.copyBean(dto, SysDepartment.class);
        department.setTreeCode(generateTreeCode(parent.getId()));
        department.setOrgCode(getOrgCode(parent.getId(), DepartmentEnum.REGULATORY_UNIT.getCode()));
        department.setOrgType(DepartmentEnum.REGULATORY_UNIT.getCode());
        //查询父级完整区域
        String region = getRegionName(parent);
        department.setRegion(region);
        save(department);
    }
 
    /**
     * 编辑监管单位
     *
     * @param dto
     * @return
     */
    @Override
    public void editRegulatoryUnit(RegulatoryUnitDTO dto) {
        if (Objects.isNull(dto.getId())) {
            throw new ServiceException("id不能为空");
        }
        SysDepartment sysDepartment = getById(dto.getId());
        if (Objects.isNull(sysDepartment)) {
            throw new ServiceException("监管单位不存在");
        }
        SysDepartment currentDepartment = getMyDepartment();
        if (Objects.isNull(currentDepartment)) {
            throw new ServiceException("无操作权限");
        }
        SysDepartment parent = this.getById(dto.getParentId());
        if (Objects.isNull(parent)) {
            throw new ServiceException("找不到对应父级组织");
        }
        if (!parent.getTreeCode().startsWith(currentDepartment.getTreeCode())) {
            throw new ServiceException("无操作权限");
        }
        Long count = this.lambdaQuery().eq(SysDepartment::getDepartmentName, dto.getDepartmentName())
                .eq(SysDepartment::getOrgType, DepartmentEnum.REGULATORY_UNIT.getCode()).ne(SysDepartment::getId, dto.getId())
                .count();
        if (count > 0) {
            throw new ServiceException("监管单位已存在");
        }
        SysDepartment department = BeanUtils.copyBean(dto, SysDepartment.class);
 
        if (!department.getParentId().equals(sysDepartment.getParentId())) {
            department.setTreeCode(generateTreeCode(parent.getId()));
            //查询父级完整区域
            String region = getRegionName(parent);
            department.setRegion(region);
        }
        updateById(department);
    }
 
    /**
     * 监管单位详情
     *
     * @param id
     * @return
     */
    @Override
    public RegulatoryUnitVO getRegulatoryUnitDetailById(Long id) {
        SysDepartment department = this.lambdaQuery().eq(SysDepartment::getId, id).eq(SysDepartment::getOrgType, DepartmentEnum.REGULATORY_UNIT.getCode()).one();
        if (Objects.nonNull(department)) {
            return BeanUtils.copyBean(department, RegulatoryUnitVO.class);
        }
        return null;
    }
 
    /**
     * 删除监管单位
     *
     * @param id
     */
    @Override
    public void deleteRegulatoryUnit(Long id) {
        Long count = sysUserService.lambdaQuery().eq(SysUser::getDepartmentId, id).count();
        if (count > 0) {
            throw new ServiceException("该监管单位构已关联用户,无法删除");
        }
        removeById(id);
    }
 
    /**
     * 根据部门id获取树编码,如果为空则获取当前登录用户所在区域树编码
     *
     * @param departmentId
     * @return
     */
    @Override
    public String getTreeCodeByDepartmentId(Long departmentId) {
        SysDepartment department;
        if (Objects.isNull(departmentId)) {
            department = getMyDepartment();
        } else {
            department = getById(departmentId);
        }
        if (Objects.nonNull(department)) {
            return department.getTreeCode();
        }
        return null;
    }
 
    /**
     * 路线关联医院列表
     *
     * @param id
     * @return
     */
    @Override
    public List<MedicalInstitutionVO> getHospitalListByRouteId(Long id) {
        return baseMapper.getHospitalListByRouteId(id);
    }
 
    /**
     * 创建机构
     *
     * @param mwApplication
     */
    @Override
    public void createDepartment(MwApplication mwApplication) {
        SysDepartment parent = this.getById(mwApplication.getDepartmentId());
        if (Objects.isNull(parent)) {
            throw new ServiceException("找不到对应父级组织");
        }
        SysDepartment department = new SysDepartment();
        department.setParentId(mwApplication.getDepartmentId());
        department.setDepartmentName(mwApplication.getUnitName());
        department.setContactPerson(mwApplication.getConcat());
        department.setContactPhone(mwApplication.getPhone());
        department.setOrgType(mwApplication.getUnitType().equals(1) ? DepartmentEnum.MEDICAL_INSTITUTION.getCode() : DepartmentEnum.DISPOSAL_UNIT.getCode());
        department.setRegion(mwApplication.getRegion());
        department.setRelation(mwApplication.getRelation());
        department.setTreeCode(generateTreeCode(parent.getId()));
        department.setOrgCode(getOrgCode(parent.getId(), department.getOrgType()));
        save(department);
    }
}