zzw
19 小时以前 ffe06be91f95ffd2459ebdb2f9130d1e38d53ea7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
package com.emergencyrepair.system.service;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.emergencyrepair.business.entity.BaseEquipment;
import com.emergencyrepair.business.entity.EngineeringMajor;
import com.emergencyrepair.business.entity.TeamMajor;
import com.emergencyrepair.business.entity.ProductNode;
import com.emergencyrepair.business.mapper.BaseEquipmentMapper;
import com.emergencyrepair.business.mapper.EngineeringMajorMapper;
import com.emergencyrepair.business.mapper.ProductNodeMapper;
import com.emergencyrepair.business.mapper.TeamMajorMapper;
import com.emergencyrepair.common.BusinessException;
import com.emergencyrepair.system.entity.SysMenu;
import com.emergencyrepair.system.entity.SysErrorLog;
import com.emergencyrepair.system.entity.SysLoginLog;
import com.emergencyrepair.system.entity.SysOperationLog;
import com.emergencyrepair.system.entity.SysRole;
import com.emergencyrepair.system.entity.SysRoleMenu;
import com.emergencyrepair.system.entity.SysRoleUser;
import com.emergencyrepair.system.entity.SysTenantMenu;
import com.emergencyrepair.system.mapper.SysMenuMapper;
import com.emergencyrepair.system.mapper.SysErrorLogMapper;
import com.emergencyrepair.system.mapper.SysLoginLogMapper;
import com.emergencyrepair.system.mapper.SysOperationLogMapper;
import com.emergencyrepair.system.mapper.SysRoleMapper;
import com.emergencyrepair.system.mapper.SysRoleMenuMapper;
import com.emergencyrepair.system.mapper.SysRoleUserMapper;
import com.emergencyrepair.system.mapper.SysTenantMenuMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
 
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
 
@Service
@RequiredArgsConstructor
public class SystemService {
    private final SysMenuMapper menuMapper;
    private final SysRoleMapper roleMapper;
    private final SysRoleMenuMapper roleMenuMapper;
    private final SysTenantMenuMapper tenantMenuMapper;
    private final SysRoleUserMapper roleUserMapper;
    private final SysLoginLogMapper loginLogMapper;
    private final SysOperationLogMapper operationLogMapper;
    private final SysErrorLogMapper errorLogMapper;
    private final ButtonPermissionCatalog buttonPermissionCatalog;
    private final JdbcTemplate jdbcTemplate;
    private final EngineeringMajorMapper engineeringMajorMapper;
    private final TeamMajorMapper teamMajorMapper;
    private final ProductNodeMapper productNodeMapper;
    private final BaseEquipmentMapper baseEquipmentMapper;
 
    public List<SysMenu> menuTree() {
        // Buttons are permission points, not navigable nodes.
        List<SysMenu> navigable = listMenus().stream()
                .filter(menu -> menu.getMenuType() == null || menu.getMenuType() != 2)
                .collect(Collectors.toList());
        return buildTree(navigable);
    }
 
    public List<SysMenu> menuTreeWithButtons() {
        return buildTree(listMenus());
    }
 
    private List<SysMenu> buildTree(List<SysMenu> menus) {
        Map<Long, SysMenu> map = menus.stream().collect(Collectors.toMap(SysMenu::getId, item -> item));
        List<SysMenu> roots = new ArrayList<>();
        for (SysMenu menu : menus) {
            if (menu.getPid() == null || menu.getPid() == 0L || !map.containsKey(menu.getPid())) {
                roots.add(menu);
            } else {
                map.get(menu.getPid()).getChildren().add(menu);
            }
        }
        sortTree(roots);
        return roots;
    }
 
    public List<SysMenu> listMenus() {
        return menuMapper.selectList(Wrappers.<SysMenu>lambdaQuery().orderByAsc(SysMenu::getSortNo));
    }
 
    @Transactional
    public SysMenu saveMenu(SysMenu menu) {
        if (!StringUtils.hasText(menu.getName())) {
            throw new BusinessException("菜单名称不能为空");
        }
        if (menu.getMenuType() == null) {
            menu.setMenuType(menu.getId() == null ? 1 : menu.getMenuType());
        }
        boolean isRoot = menu.getPid() == null || menu.getPid() == 0L;
        if (menu.getId() != null && !isRoot && menu.getId().equals(menu.getPid())) {
            throw new BusinessException("上级菜单不能选择当前菜单");
        }
        SysMenu parent = null;
        if (!isRoot) {
            parent = menuMapper.selectById(menu.getPid());
            if (parent == null) {
                throw new BusinessException("上级菜单不存在");
            }
            if (menu.getId() != null && isMenuDescendant(menu.getPid(), menu.getId())) {
                throw new BusinessException("上级菜单不能选择当前菜单的下级");
            }
        }
        if (menu.getMenuType() == 2) {
            if (parent == null || parent.getMenuType() == null || parent.getMenuType() != 1) {
                throw new BusinessException("按钮类型只能建在菜单类型下级");
            }
            if (!StringUtils.hasText(menu.getPermissions())) {
                throw new BusinessException("按钮权限标识不能为空");
            }
            menu.setUrl(null);
            menu.setIcon(null);
        } else if (parent != null && parent.getMenuType() != null && parent.getMenuType() == 2) {
            throw new BusinessException("按钮类型下级不能再建菜单");
        }
        LocalDateTime now = LocalDateTime.now();
        menu.setUpdateTime(now);
        if (menu.getId() == null) {
            menu.setCreateTime(now);
            if (menu.getVisible() == null) {
                menu.setVisible(1);
            }
            if (menu.getMenuType() == null) {
                menu.setMenuType(1);
            }
            menuMapper.insert(menu);
        } else {
            menuMapper.updateById(menu);
        }
        return menuMapper.selectById(menu.getId());
    }
 
    private boolean isMenuDescendant(Long candidateId, Long ancestorId) {
        Long cursor = candidateId;
        int guard = 0;
        while (cursor != null && cursor != 0L && guard++ < 64) {
            if (cursor.equals(ancestorId)) {
                return true;
            }
            SysMenu current = menuMapper.selectById(cursor);
            cursor = current == null ? null : current.getPid();
        }
        return false;
    }
 
    @Transactional
    public void deleteMenu(Long id) {
        long children = menuMapper.selectCount(Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getPid, id));
        if (children > 0) {
            throw new BusinessException("请先删除下级菜单");
        }
        menuMapper.deleteById(id);
        roleMenuMapper.delete(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getMenuId, id));
        tenantMenuMapper.delete(Wrappers.<SysTenantMenu>lambdaQuery().eq(SysTenantMenu::getMenuId, id));
    }
 
    public List<SysRole> listRoles() {
        return roleMapper.selectList(Wrappers.<SysRole>lambdaQuery().orderByAsc(SysRole::getSortNo));
    }
 
    @Transactional
    public SysRole saveRole(SysRole role) {
        if (!StringUtils.hasText(role.getName()) || !StringUtils.hasText(role.getCode())) {
            throw new BusinessException("角色名称和编码不能为空");
        }
        LocalDateTime now = LocalDateTime.now();
        role.setUpdateTime(now);
        if (role.getId() == null) {
            role.setCreateTime(now);
            roleMapper.insert(role);
        } else {
            roleMapper.updateById(role);
        }
        return roleMapper.selectById(role.getId());
    }
 
    @Transactional
    public void deleteRole(Long id) {
        roleMapper.deleteById(id);
        roleMenuMapper.delete(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getRoleId, id));
        roleUserMapper.delete(Wrappers.<SysRoleUser>lambdaQuery().eq(SysRoleUser::getRoleId, id));
    }
 
    /**
     * Contractor units are maintained as department records with DEPT_TYPE='cj'.
     */
    public List<Map<String, Object>> listContractors() {
        return jdbcTemplate.query(
                "SELECT DEPT_ID, DEPT_NAME, ORDER_NUM, LEADER, PHONE, STATUS, DEPT_CODE FROM CSICZB_ZB.SYS_DEPT "
                        + "WHERE DEPT_TYPE = 'cj' AND (DEL_FLAG = '0' OR DEL_FLAG IS NULL) ORDER BY ORDER_NUM, DEPT_ID",
                (rs, rowNum) -> {
                    Map<String, Object> row = new LinkedHashMap<>();
                    row.put("id", String.valueOf(rs.getLong("DEPT_ID")));
                    row.put("name", rs.getString("DEPT_NAME"));
                    row.put("shortName", null);
                    row.put("nature", "承修单位");
                    row.put("sortNo", rs.getObject("ORDER_NUM"));
                    row.put("contact", rs.getString("LEADER"));
                    row.put("phone", rs.getString("PHONE"));
                    row.put("status", rs.getString("STATUS"));
                    row.put("deptCode", rs.getString("DEPT_CODE"));
                    row.put("dishonest", 0);
                    return row;
                });
    }
 
    public List<EngineeringMajor> listEngineeringMajors() {
        return engineeringMajorMapper.selectList(Wrappers.<EngineeringMajor>lambdaQuery()
                .orderByAsc(EngineeringMajor::getId));
    }
 
    @Transactional
    public EngineeringMajor saveEngineeringMajor(EngineeringMajor major) {
        if (major == null || !StringUtils.hasText(major.getName())) {
            throw new BusinessException("工程专业名称不能为空");
        }
        String name = major.getName().trim();
        LambdaQueryWrapper<EngineeringMajor> duplicate = Wrappers.<EngineeringMajor>lambdaQuery()
                .eq(EngineeringMajor::getName, name);
        if (major.getId() != null) {
            duplicate.ne(EngineeringMajor::getId, major.getId());
        }
        if (engineeringMajorMapper.selectCount(duplicate) > 0) {
            throw new BusinessException("工程专业名称已存在:" + name);
        }
        LocalDateTime now = LocalDateTime.now();
        major.setName(name);
        major.setUpdateTime(now);
        if (major.getId() == null) {
            major.setCreateTime(now);
            engineeringMajorMapper.insert(major);
        } else {
            engineeringMajorMapper.updateById(major);
        }
        return engineeringMajorMapper.selectById(major.getId());
    }
 
    @Transactional
    public void deleteEngineeringMajor(Long id) {
        engineeringMajorMapper.deleteById(id);
    }
 
    public List<TeamMajor> listTeamMajors() {
        return teamMajorMapper.selectList(Wrappers.<TeamMajor>lambdaQuery()
                .orderByAsc(TeamMajor::getId));
    }
 
    @Transactional
    public TeamMajor saveTeamMajor(TeamMajor major) {
        if (major == null || !StringUtils.hasText(major.getName())) {
            throw new BusinessException("rk_T队专业名称不能为空");
        }
        String name = major.getName().trim();
        String category = StringUtils.hasText(major.getCategory()) ? major.getCategory().trim().toUpperCase() : "";
        if (!"A".equals(category) && !"B".equals(category)) {
            throw new BusinessException("rk_T队专业分类只能是A或B");
        }
        LambdaQueryWrapper<TeamMajor> duplicate = Wrappers.<TeamMajor>lambdaQuery()
                .eq(TeamMajor::getName, name);
        if (major.getId() != null) {
            duplicate.ne(TeamMajor::getId, major.getId());
        }
        if (teamMajorMapper.selectCount(duplicate) > 0) {
            throw new BusinessException("rk_T队专业名称已存在:" + name);
        }
        LocalDateTime now = LocalDateTime.now();
        major.setName(name);
        major.setCategory(category);
        major.setUpdateTime(now);
        if (major.getId() == null) {
            major.setCreateTime(now);
            teamMajorMapper.insert(major);
        } else {
            teamMajorMapper.updateById(major);
        }
        return teamMajorMapper.selectById(major.getId());
    }
 
    @Transactional
    public void deleteTeamMajor(Long id) {
        teamMajorMapper.deleteById(id);
    }
 
    public List<Map<String, Object>> tree(String type) {
        if ("product".equals(type)) {
            return productTree();
        }
        if ("base".equals(type)) {
            return baseTree();
        }
        throw new BusinessException("未知树类型");
    }
 
    public List<Map<String, Object>> selectedProductNodes(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Collections.emptyList();
        }
        List<ProductNode> source = productNodeMapper.selectList(Wrappers.<ProductNode>lambdaQuery()
                .in(ProductNode::getId, ids));
        Map<Long, ProductNode> unique = uniqueProductNodes(source);
        List<Map<String, Object>> result = new ArrayList<>();
        Set<Long> seen = new HashSet<>();
        for (Long id : ids) {
            ProductNode node = unique.get(id);
            if (node == null || !seen.add(id)) {
                continue;
            }
            List<ProductNode> path = productPath(node);
            Map<String, Object> row = mapProduct(node, Collections.emptySet());
            row.put("pathNames", path.stream().map(ProductNode::getName).collect(Collectors.toList()));
            row.put("parentPathNames", path.stream()
                    .filter(item -> item != node)
                    .filter(item -> item.getNodeLevel() != null && item.getNodeLevel() > 2)
                    .map(ProductNode::getName)
                    .collect(Collectors.toList()));
            ProductNode xNode = path.stream()
                    .filter(item -> item.getNodeLevel() != null && item.getNodeLevel() == 2)
                    .findFirst().orElse(null);
            row.put("xNo", xNode == null ? null : xNode.getName());
            result.add(row);
        }
        return result;
    }
 
    private List<Map<String, Object>> mapProductTreeNodes(List<ProductNode> source, Set<Long> forcedBranchIds) {
        Map<Long, ProductNode> unique = uniqueProductNodes(source);
        List<ProductNode> nodes = sortProductNodes(unique.values());
        Set<Long> branchIds = new HashSet<>(forcedBranchIds);
        if (!unique.isEmpty()) {
            List<ProductNode> childRows = productNodeMapper.selectList(Wrappers.<ProductNode>lambdaQuery()
                    .select(ProductNode::getParentId, ProductNode::getIsDelete)
                    .in(ProductNode::getParentId, unique.keySet()));
            for (ProductNode child : childRows) {
                if (!"1".equals(child.getIsDelete()) && child.getParentId() != null) {
                    branchIds.add(child.getParentId());
                }
            }
        }
        List<Map<String, Object>> rows = new ArrayList<>();
        for (ProductNode node : nodes) {
            rows.add(mapProduct(node, branchIds));
        }
        return rows;
    }
 
    private Map<Long, ProductNode> uniqueProductNodes(Collection<ProductNode> source) {
        Map<Long, ProductNode> unique = new LinkedHashMap<>();
        if (source == null) {
            return unique;
        }
        for (ProductNode node : source) {
            if (node.getId() == null || "1".equals(node.getIsDelete())) {
                continue;
            }
            unique.putIfAbsent(node.getId(), node);
        }
        return unique;
    }
 
    private List<ProductNode> sortProductNodes(Collection<ProductNode> source) {
        List<ProductNode> nodes = new ArrayList<>(source);
        nodes.sort(Comparator.comparingInt(this::productNodeLevel)
                .thenComparing(ProductNode::getSortNo, Comparator.nullsLast(Integer::compareTo))
                .thenComparing(ProductNode::getId, Comparator.nullsLast(Long::compareTo)));
        return nodes;
    }
 
    private ProductNode findProductRoot(ProductNode node) {
        ProductNode current = node;
        Set<Long> visited = new HashSet<>();
        while (current != null && current.getParentId() != null && current.getParentId() != 0L
                && visited.add(current.getId())) {
            current = findProductNode(current.getParentId());
        }
        return current;
    }
 
    private List<ProductNode> productPath(ProductNode node) {
        List<ProductNode> reversed = new ArrayList<>();
        Set<Long> visited = new HashSet<>();
        ProductNode current = node;
        while (current != null && visited.add(current.getId())) {
            reversed.add(current);
            if (current.getParentId() == null || current.getParentId() == 0L) {
                break;
            }
            current = findProductNode(current.getParentId());
        }
        Collections.reverse(reversed);
        return reversed;
    }
 
    public List<Map<String, Object>> productTreeForXNo(String xNo) {
        if (!StringUtils.hasText(xNo)) {
            return productTreeRoots();
        }
        List<ProductNode> sideNodes = productNodeMapper.selectList(Wrappers.<ProductNode>lambdaQuery()
                .in(ProductNode::getLayer, Arrays.asList("side", "SIDE"))
                .eq(ProductNode::getName, xNo.trim())
                .orderByAsc(ProductNode::getSortNo).orderByAsc(ProductNode::getId));
        return mapProductTreeNodes(sideNodes, Collections.emptySet());
    }
 
    public List<String> productXNumbers() {
        List<ProductNode> nodes = productNodeMapper.selectList(Wrappers.<ProductNode>lambdaQuery()
                .in(ProductNode::getLayer, Arrays.asList("side", "SIDE"))
                .orderByAsc(ProductNode::getSortNo).orderByAsc(ProductNode::getId));
        return nodes.stream()
                .filter(node -> !"1".equals(node.getIsDelete()))
                .map(ProductNode::getName)
                .filter(StringUtils::hasText)
                .map(String::trim)
                .distinct()
                .sorted(String.CASE_INSENSITIVE_ORDER)
                .collect(Collectors.toList());
    }
 
    public List<Map<String, Object>> productTreeRoots() {
        List<ProductNode> nodes = productNodeMapper.selectList(Wrappers.<ProductNode>lambdaQuery()
                .and(wrapper -> wrapper.isNull(ProductNode::getParentId).or().eq(ProductNode::getParentId, 0L))
                .orderByAsc(ProductNode::getSortNo).orderByAsc(ProductNode::getId));
        return mapProductTreeNodes(nodes, Collections.emptySet());
    }
 
    public List<Map<String, Object>> productTreeChildren(Long parentId) {
        if (parentId == null || parentId == 0L) {
            return productTreeRoots();
        }
        List<ProductNode> nodes = productNodeMapper.selectList(Wrappers.<ProductNode>lambdaQuery()
                .eq(ProductNode::getParentId, parentId)
                .orderByAsc(ProductNode::getSortNo).orderByAsc(ProductNode::getId));
        return mapProductTreeNodes(nodes, Collections.emptySet());
    }
 
    public List<Map<String, Object>> productTree() {
        List<ProductNode> nodes = productNodeMapper.selectList(Wrappers.<ProductNode>lambdaQuery()
                .orderByAsc(ProductNode::getId).orderByAsc(ProductNode::getSortNo));
        Map<Long, ProductNode> unique = new LinkedHashMap<>();
        for (ProductNode node : nodes) {
            if (node.getId() == null || "1".equals(node.getIsDelete())) {
                continue;
            }
            unique.putIfAbsent(node.getId(), node);
        }
        nodes = new ArrayList<>(unique.values());
        nodes.sort(Comparator.comparingInt(this::productNodeLevel)
                .thenComparing(ProductNode::getSortNo, Comparator.nullsLast(Integer::compareTo))
                .thenComparing(ProductNode::getId, Comparator.nullsLast(Long::compareTo)));
        Map<Long, Map<String, Object>> map = new LinkedHashMap<>();
        for (ProductNode node : nodes) {
            map.put(node.getId(), mapProduct(node));
        }
        List<Map<String, Object>> roots = new ArrayList<>();
        for (ProductNode node : nodes) {
            Map<String, Object> target = map.get(node.getId());
            if (node.getParentId() == null || node.getParentId() == 0L || !map.containsKey(node.getParentId())) {
                roots.add(target);
            } else {
                children(map.get(node.getParentId())).add(target);
            }
        }
        return roots;
    }
 
    public List<Map<String, Object>> baseTree() {
        List<BaseEquipment> nodes = baseEquipmentMapper.selectList(Wrappers.<BaseEquipment>lambdaQuery()
                .orderByAsc(BaseEquipment::getNodeLevel).orderByAsc(BaseEquipment::getSortNo));
        Map<Long, Map<String, Object>> map = new LinkedHashMap<>();
        for (BaseEquipment node : nodes) {
            map.put(node.getId(), mapBase(node));
        }
        List<Map<String, Object>> roots = new ArrayList<>();
        for (BaseEquipment node : nodes) {
            Map<String, Object> target = map.get(node.getId());
            if (node.getParentId() == null || node.getParentId() == 0L || !map.containsKey(node.getParentId())) {
                roots.add(target);
            } else {
                children(map.get(node.getParentId())).add(target);
            }
        }
        return roots;
    }
 
    @Transactional
    public ProductNode saveProductNode(ProductNode node) {
        if (!StringUtils.hasText(node.getName())) {
            throw new BusinessException("节点名称不能为空");
        }
        LocalDateTime now = LocalDateTime.now();
        String layer = resolveProductLayer(node);
        node.setLayer(layer);
        node.setConnectGroup(buildConnectGroup(node.getParentId()));
 
        if (node.getId() == null) {
            node.setId(IdWorker.getId());
            node.setRecordId(String.valueOf(node.getId()));
            node.setProject(StringUtils.hasText(node.getProject()) ? node.getProject().trim() : "0");
            node.setSortNo(node.getSortNo() == null ? 1 : node.getSortNo());
            node.setIsDelete("0");
            node.setCreateBy(StringUtils.hasText(node.getCreateBy()) ? node.getCreateBy().trim() : "system");
            node.setCreateTime(now);
            productNodeMapper.insert(node);
        } else {
            ProductNode current = findProductNode(node.getId());
            if (current == null) {
                throw new BusinessException("节点不存在");
            }
            node.setRecordId(current.getRecordId());
            node.setProject(StringUtils.hasText(current.getProject()) ? current.getProject() : "0");
            node.setIsDelete(StringUtils.hasText(current.getIsDelete()) ? current.getIsDelete() : "0");
            node.setCreateBy(current.getCreateBy());
            node.setCreateTime(current.getCreateTime());
            productNodeMapper.updateById(node);
        }
        return findProductNode(node.getId());
    }
 
    @Transactional
    public void deleteProductNode(Long id) {
        assertNoChildren(productNodeMapper.selectCount(Wrappers.<ProductNode>lambdaQuery()
                .eq(ProductNode::getParentId, id).ne(ProductNode::getIsDelete, "1")));
        ProductNode current = findProductNode(id);
        if (current == null) {
            throw new BusinessException("节点不存在");
        }
        current.setIsDelete("1");
        productNodeMapper.updateById(current);
    }
 
    @Transactional
    public BaseEquipment saveBaseNode(BaseEquipment node) {
        if (!StringUtils.hasText(node.getName()) || node.getNodeLevel() == null) {
            throw new BusinessException("节点名称和层级不能为空");
        }
        LocalDateTime now = LocalDateTime.now();
        node.setUpdateTime(now);
        if (node.getId() == null) {
            node.setCreateTime(now);
            baseEquipmentMapper.insert(node);
        } else {
            baseEquipmentMapper.updateById(node);
        }
        return baseEquipmentMapper.selectById(node.getId());
    }
 
    @Transactional
    public void deleteBaseNode(Long id) {
        assertNoChildren(baseEquipmentMapper.selectCount(Wrappers.<BaseEquipment>lambdaQuery().eq(BaseEquipment::getParentId, id)));
        baseEquipmentMapper.deleteById(id);
    }
 
    public Map<String, Object> menuPermissions(Long roleId) {
        if (roleId == null) {
            throw new BusinessException("请选择角色");
        }
        List<String> roleMenuIds = roleMenuMapper.selectList(Wrappers.<SysRoleMenu>lambdaQuery()
                        .eq(SysRoleMenu::getRoleId, roleId))
                .stream().map(SysRoleMenu::getMenuId).map(String::valueOf).collect(Collectors.toList());
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("roleMenuIds", roleMenuIds);
        result.put("effectiveMenuIds", roleMenuIds);
        return result;
    }
 
    @Transactional
    public void saveMenuPermissions(Long roleId, List<Long> roleMenuIds) {
        if (roleId == null) {
            throw new BusinessException("请选择角色");
        }
        roleMenuMapper.delete(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getRoleId, roleId));
        List<Long> effectiveRoleMenuIds = expandWithAncestors(roleMenuIds);
        for (Long menuId : effectiveRoleMenuIds) {
            SysRoleMenu relation = new SysRoleMenu();
            relation.setRoleId(roleId);
            relation.setMenuId(menuId);
            relation.setCreateTime(LocalDateTime.now());
            roleMenuMapper.insert(relation);
        }
    }
 
    public Map<String, Object> userPage(String keyword, Long deptId, Long roleId, int current, int size) {
        List<Object> args = new ArrayList<>();
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT u.USER_ID, u.USER_NAME, u.NICK_NAME, u.DEPT_ID, d.DEPT_NAME, u.PHONENUMBER, u.STATUS, u.LOGIN_DATE ");
        sql.append("FROM CSICZB_ZB.SYS_USER u LEFT JOIN CSICZB_ZB.SYS_DEPT d ON d.DEPT_ID = u.DEPT_ID ");
        sql.append("WHERE (u.DEL_FLAG = '0' OR u.DEL_FLAG IS NULL) ");
        if (StringUtils.hasText(keyword)) {
            sql.append("AND (u.USER_NAME LIKE ? OR u.NICK_NAME LIKE ?) ");
            String like = "%" + keyword.trim() + "%";
            args.add(like);
            args.add(like);
        }
        if (deptId != null) {
            sql.append("AND u.DEPT_ID = ? ");
            args.add(deptId);
        }
        if (roleId != null) {
            sql.append("AND EXISTS (SELECT 1 FROM LX.T_SYS_ROLE_USER ru WHERE ru.USER_ID = u.USER_ID AND ru.ROLE_ID = ? AND ru.DEL_FLAG = 0) ");
            args.add(roleId);
        }
        sql.append("ORDER BY u.USER_ID");
        List<Map<String, Object>> all = jdbcTemplate.query(sql.toString(), args.toArray(), (rs, rowNum) -> {
            Map<String, Object> row = new LinkedHashMap<>();
            row.put("userId", String.valueOf(rs.getLong("USER_ID")));
            row.put("userName", rs.getString("USER_NAME"));
            row.put("nickName", rs.getString("NICK_NAME"));
            Object dept = rs.getObject("DEPT_ID");
            row.put("deptId", dept == null ? null : String.valueOf(rs.getLong("DEPT_ID")));
            row.put("deptName", rs.getString("DEPT_NAME"));
            row.put("phoneNumber", rs.getString("PHONENUMBER"));
            row.put("status", rs.getString("STATUS"));
            java.sql.Timestamp loginDate = rs.getTimestamp("LOGIN_DATE");
            row.put("loginDate", loginDate == null ? null : loginDate.toLocalDateTime().toString().replace('T', ' '));
            row.put("roles", new ArrayList<Map<String, Object>>());
            return row;
        });
        Map<Long, Map<String, Object>> byId = new HashMap<>();
        for (Map<String, Object> row : all) {
            byId.put(Long.valueOf(String.valueOf(row.get("userId"))), row);
        }
        if (!byId.isEmpty()) {
            List<Map<String, Object>> roleRows = jdbcTemplate.query(
                    "SELECT ru.USER_ID, r.ID, r.NAME, r.CODE, r.ROLE_TYPE FROM LX.T_SYS_ROLE_USER ru JOIN LX.T_SYS_ROLE r ON r.ID = ru.ROLE_ID AND r.DEL_FLAG = 0 WHERE ru.DEL_FLAG = 0 ORDER BY r.SORT_NO",
                    (rs, rowNum) -> {
                        Map<String, Object> role = new LinkedHashMap<>();
                        role.put("userId", String.valueOf(rs.getLong("USER_ID")));
                        role.put("roleId", String.valueOf(rs.getLong("ID")));
                        role.put("roleName", rs.getString("NAME"));
                        role.put("roleCode", rs.getString("CODE"));
                        role.put("roleType", rs.getString("ROLE_TYPE"));
                        return role;
                    });
            for (Map<String, Object> role : roleRows) {
                Map<String, Object> user = byId.get(Long.valueOf(String.valueOf(role.get("userId"))));
                if (user != null) {
                    @SuppressWarnings("unchecked")
                    List<Map<String, Object>> roles = (List<Map<String, Object>>) user.get("roles");
                    roles.add(role);
                }
            }
        }
        int safeSize = size <= 0 ? 20 : size;
        int safeCurrent = current <= 0 ? 1 : current;
        int total = all.size();
        int from = Math.min(total, (safeCurrent - 1) * safeSize);
        int to = Math.min(total, from + safeSize);
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("records", new ArrayList<>(all.subList(from, to)));
        result.put("total", total);
        result.put("current", safeCurrent);
        result.put("size", safeSize);
        result.put("pages", (total + safeSize - 1) / safeSize);
        return result;
    }
 
    public List<Map<String, Object>> depts() {
        return jdbcTemplate.query(
                "SELECT DEPT_ID, DEPT_NAME, PARENT_ID, ORDER_NUM, DEPT_TYPE, LEADER, PHONE, STATUS, DEPT_CODE FROM CSICZB_ZB.SYS_DEPT WHERE (DEL_FLAG = '0' OR DEL_FLAG IS NULL) ORDER BY ORDER_NUM, DEPT_ID",
                (rs, rowNum) -> {
                    Map<String, Object> row = new LinkedHashMap<>();
                    row.put("id", String.valueOf(rs.getLong("DEPT_ID")));
                    row.put("name", rs.getString("DEPT_NAME"));
                    Object parentId = rs.getObject("PARENT_ID");
                    row.put("parentId", parentId == null ? null : String.valueOf(rs.getLong("PARENT_ID")));
                    row.put("orderNum", rs.getObject("ORDER_NUM"));
                    row.put("deptType", rs.getString("DEPT_TYPE"));
                    row.put("leader", rs.getString("LEADER"));
                    row.put("phone", rs.getString("PHONE"));
                    row.put("status", rs.getString("STATUS"));
                    row.put("deptCode", rs.getString("DEPT_CODE"));
                    return row;
                });
    }
 
    public List<String> userRoleIds(Long userId) {
        if (userId == null) {
            return new ArrayList<>();
        }
        return roleUserMapper.selectList(Wrappers.<SysRoleUser>lambdaQuery()
                        .eq(SysRoleUser::getUserId, userId))
                .stream().map(item -> String.valueOf(item.getRoleId())).collect(Collectors.toList());
    }
 
    public Map<String, Object> roleUsers(Long roleId) {
        if (roleId == null || roleMapper.selectById(roleId) == null) {
            throw new BusinessException("角色不存在");
        }
        Set<Long> assignedUserIds = roleUserMapper.selectList(Wrappers.<SysRoleUser>lambdaQuery()
                        .eq(SysRoleUser::getRoleId, roleId))
                .stream().map(SysRoleUser::getUserId).collect(Collectors.toCollection(LinkedHashSet::new));
        List<Map<String, Object>> users = jdbcTemplate.query(
                "SELECT u.USER_ID, u.USER_NAME, u.NICK_NAME, u.DEPT_ID, d.DEPT_NAME, u.STATUS " +
                        "FROM CSICZB_ZB.SYS_USER u LEFT JOIN CSICZB_ZB.SYS_DEPT d ON d.DEPT_ID = u.DEPT_ID " +
                        "WHERE (u.DEL_FLAG = '0' OR u.DEL_FLAG IS NULL) ORDER BY u.USER_ID",
                (rs, rowNum) -> {
                    Long userId = rs.getLong("USER_ID");
                    Map<String, Object> user = new LinkedHashMap<>();
                    user.put("userId", String.valueOf(userId));
                    user.put("userName", rs.getString("USER_NAME"));
                    user.put("nickName", rs.getString("NICK_NAME"));
                    Object deptId = rs.getObject("DEPT_ID");
                    user.put("deptId", deptId == null ? null : String.valueOf(rs.getLong("DEPT_ID")));
                    user.put("deptName", rs.getString("DEPT_NAME"));
                    user.put("status", rs.getString("STATUS"));
                    user.put("assigned", assignedUserIds.contains(userId));
                    return user;
                });
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("records", users);
        result.put("userIds", assignedUserIds.stream().map(String::valueOf).collect(Collectors.toList()));
        result.put("total", users.size());
        return result;
    }
 
    @Transactional
    public void saveRoleUsers(Long roleId, List<Long> userIds) {
        if (roleId == null || roleMapper.selectById(roleId) == null) {
            throw new BusinessException("角色不存在");
        }
        Set<Long> distinct = new LinkedHashSet<>();
        if (userIds != null) {
            distinct.addAll(userIds);
        }
        distinct.remove(null);
        for (Long userId : distinct) {
            Integer exists = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM CSICZB_ZB.SYS_USER WHERE USER_ID = ? AND (DEL_FLAG = '0' OR DEL_FLAG IS NULL)",
                    Integer.class, userId);
            if (exists == null || exists == 0) {
                throw new BusinessException("用户不存在");
            }
        }
        roleUserMapper.delete(Wrappers.<SysRoleUser>lambdaQuery().eq(SysRoleUser::getRoleId, roleId));
        for (Long userId : distinct) {
            SysRoleUser relation = new SysRoleUser();
            relation.setRoleId(roleId);
            relation.setUserId(userId);
            relation.setCreateTime(LocalDateTime.now());
            roleUserMapper.insert(relation);
        }
    }
 
    @Transactional
    public void saveUserRoles(Long userId, List<Long> roleIds) {
        if (userId == null) {
            throw new BusinessException("请选择用户");
        }
        Integer exists = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM CSICZB_ZB.SYS_USER WHERE USER_ID = ? AND (DEL_FLAG = '0' OR DEL_FLAG IS NULL)",
                Integer.class, userId);
        if (exists == null || exists == 0) {
            throw new BusinessException("用户不存在");
        }
        Set<Long> distinct = new LinkedHashSet<>();
        if (roleIds != null) {
            distinct.addAll(roleIds);
        }
        for (Long roleId : distinct) {
            if (roleId != null && roleMapper.selectById(roleId) == null) {
                throw new BusinessException("角色不存在");
            }
        }
        roleUserMapper.delete(Wrappers.<SysRoleUser>lambdaQuery().eq(SysRoleUser::getUserId, userId));
        for (Long roleId : distinct) {
            if (roleId == null) {
                continue;
            }
            SysRoleUser relation = new SysRoleUser();
            relation.setRoleId(roleId);
            relation.setUserId(userId);
            relation.setCreateTime(LocalDateTime.now());
            roleUserMapper.insert(relation);
        }
    }
 
    @Transactional
    public void saveUserRolesBatch(List<Long> userIds, List<Long> roleIds, String mode) {
        Set<Long> distinctUsers = new LinkedHashSet<>();
        if (userIds != null) {
            distinctUsers.addAll(userIds);
        }
        distinctUsers.remove(null);
        if (distinctUsers.isEmpty()) {
            throw new BusinessException("\u8bf7\u9009\u62e9\u7528\u6237");
        }
        Set<Long> distinctRoles = new LinkedHashSet<>();
        if (roleIds != null) {
            distinctRoles.addAll(roleIds);
        }
        distinctRoles.remove(null);
        for (Long roleId : distinctRoles) {
            if (roleMapper.selectById(roleId) == null) {
                throw new BusinessException("\u89d2\u8272\u4e0d\u5b58\u5728");
            }
        }
        boolean append = !"replace".equalsIgnoreCase(mode == null ? "" : mode.trim());
        for (Long userId : distinctUsers) {
            Integer exists = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM CSICZB_ZB.SYS_USER WHERE USER_ID = ? AND (DEL_FLAG = '0' OR DEL_FLAG IS NULL)",
                    Integer.class, userId);
            if (exists == null || exists == 0) {
                throw new BusinessException("\u7528\u6237\u4e0d\u5b58\u5728");
            }
            Set<Long> targetRoleIds = new LinkedHashSet<>();
            if (append) {
                targetRoleIds.addAll(roleUserMapper.selectList(Wrappers.<SysRoleUser>lambdaQuery()
                                .eq(SysRoleUser::getUserId, userId))
                        .stream().map(SysRoleUser::getRoleId).collect(Collectors.toList()));
            }
            targetRoleIds.addAll(distinctRoles);
            roleUserMapper.delete(Wrappers.<SysRoleUser>lambdaQuery().eq(SysRoleUser::getUserId, userId));
            for (Long roleId : targetRoleIds) {
                SysRoleUser relation = new SysRoleUser();
                relation.setRoleId(roleId);
                relation.setUserId(userId);
                relation.setCreateTime(LocalDateTime.now());
                roleUserMapper.insert(relation);
            }
        }
    }
 
    public List<String> roleCodes(String username) {
        Long userId = resolveUserId(username);
        if (userId == null) {
            return new ArrayList<>();
        }
        List<Long> roleIds = roleUserMapper.selectList(Wrappers.<SysRoleUser>lambdaQuery()
                        .eq(SysRoleUser::getUserId, userId))
                .stream().map(SysRoleUser::getRoleId).collect(Collectors.toList());
        if (roleIds.isEmpty()) {
            return new ArrayList<>();
        }
        return roleMapper.selectBatchIds(roleIds).stream()
                .map(SysRole::getCode).filter(StringUtils::hasText).sorted().collect(Collectors.toList());
    }
 
    public Set<Long> effectiveMenuIdsForUser(String username) {
        Set<Long> result = new LinkedHashSet<>();
        if (!StringUtils.hasText(username)) {
            return result;
        }
        if ("admin".equals(username)) {
            listMenus().forEach(menu -> result.add(menu.getId()));
            return result;
        }
        Long userId = resolveUserId(username);
        if (userId == null) {
            return result;
        }
        List<Long> roleIds = roleUserMapper.selectList(Wrappers.<SysRoleUser>lambdaQuery()
                        .eq(SysRoleUser::getUserId, userId))
                .stream().map(SysRoleUser::getRoleId).collect(Collectors.toList());
        if (roleIds.isEmpty()) {
            return result;
        }
        Set<Long> roleMenuIds = new LinkedHashSet<>(roleMenuMapper.selectList(Wrappers.<SysRoleMenu>lambdaQuery()
                        .in(SysRoleMenu::getRoleId, roleIds))
                .stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList()));
        result.addAll(roleMenuIds);
        return result;
    }
 
    public List<SysMenu> menuTreeForUser(String username) {
        Set<Long> allowed = new LinkedHashSet<>(effectiveMenuIdsForUser(username));
        if (allowed.isEmpty() && !"admin".equals(username)) {
            SysMenu dashboard = menuMapper.selectOne(Wrappers.<SysMenu>lambdaQuery()
                    .eq(SysMenu::getUrl, "/dashboard").last("LIMIT 1"));
            if (dashboard != null) {
                allowed.add(dashboard.getId());
            }
        }
        final Set<Long> allowedIds = allowed;
        Set<Long> visibleIds = new LinkedHashSet<>(expandWithAncestors(new ArrayList<>(allowed)));
        List<SysMenu> navigable = listMenus().stream()
                .filter(menu -> menu.getMenuType() == null || menu.getMenuType() != 2)
                .filter(menu -> visibleIds.contains(menu.getId()))
                .collect(Collectors.toList());
        return buildTree(navigable);
    }
 
    public List<String> permissionCodes(String username) {
        Set<Long> menuIds = effectiveMenuIdsForUser(username);
        return listMenus().stream()
                .filter(menu -> menuIds.contains(menu.getId()))
                .map(SysMenu::getPermissions)
                .filter(StringUtils::hasText)
                .distinct()
                .sorted()
                .collect(Collectors.toList());
    }
 
    public Map<String, Object> menuButtons(Long menuId) {
        SysMenu menu = menuMapper.selectById(menuId);
        if (menu == null) {
            throw new BusinessException("菜单不存在");
        }
        List<Map<String, Object>> available = new ArrayList<>();
        for (ButtonPermissionCatalog.ButtonDefinition definition : buttonPermissionCatalog.buttonsFor(menu.getUrl())) {
            Map<String, Object> row = new LinkedHashMap<>();
            row.put("code", definition.getCode());
            row.put("name", definition.getName());
            available.add(row);
        }
        List<String> selected = menuMapper.selectList(Wrappers.<SysMenu>lambdaQuery()
                        .eq(SysMenu::getPid, menuId)
                        .eq(SysMenu::getMenuType, 2))
                .stream().map(SysMenu::getPermissions).filter(StringUtils::hasText).collect(Collectors.toList());
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("menuId", String.valueOf(menuId));
        result.put("menuName", menu.getName());
        result.put("available", available);
        result.put("selected", selected);
        return result;
    }
 
    @Transactional
    public void syncMenuButtons(Long menuId, List<String> codes) {
        SysMenu menu = menuMapper.selectById(menuId);
        if (menu == null) {
            throw new BusinessException("菜单不存在");
        }
        if (menu.getMenuType() == null || menu.getMenuType() != 1) {
            throw new BusinessException("只有菜单类型才能配置按钮");
        }
        List<ButtonPermissionCatalog.ButtonDefinition> definitions = buttonPermissionCatalog.buttonsFor(menu.getUrl());
        Map<String, ButtonPermissionCatalog.ButtonDefinition> definitionMap = new LinkedHashMap<>();
        for (ButtonPermissionCatalog.ButtonDefinition definition : definitions) {
            definitionMap.put(definition.getCode(), definition);
        }
        Set<String> wanted = new LinkedHashSet<>();
        if (codes != null) {
            for (String code : codes) {
                if (StringUtils.hasText(code) && definitionMap.containsKey(code)) {
                    wanted.add(code);
                }
            }
        }
        List<SysMenu> existing = menuMapper.selectList(Wrappers.<SysMenu>lambdaQuery()
                .eq(SysMenu::getPid, menuId).eq(SysMenu::getMenuType, 2));
        Map<String, SysMenu> existingByCode = new HashMap<>();
        for (SysMenu child : existing) {
            existingByCode.put(child.getPermissions(), child);
            if (!wanted.contains(child.getPermissions())) {
                menuMapper.deleteById(child.getId());
                roleMenuMapper.delete(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getMenuId, child.getId()));
                tenantMenuMapper.delete(Wrappers.<SysTenantMenu>lambdaQuery().eq(SysTenantMenu::getMenuId, child.getId()));
            }
        }
        LocalDateTime now = LocalDateTime.now();
        for (int index = 0; index < definitions.size(); index++) {
            ButtonPermissionCatalog.ButtonDefinition definition = definitions.get(index);
            if (!wanted.contains(definition.getCode())) {
                continue;
            }
            SysMenu child = existingByCode.get(definition.getCode());
            if (child == null) {
                child = new SysMenu();
                child.setPid(menuId);
                child.setName(definition.getName());
                child.setPermissions(definition.getCode());
                child.setMenuType(2);
                child.setSortNo((index + 1) * 10);
                child.setVisible(1);
                child.setCreateTime(now);
                child.setUpdateTime(now);
                menuMapper.insert(child);
            } else {
                child.setName(definition.getName());
                child.setSortNo((index + 1) * 10);
                child.setUpdateTime(now);
                menuMapper.updateById(child);
            }
        }
    }
 
    public Page<SysLoginLog> loginLogPage(int current, int size, String keyword, String status, String startDate, String endDate) {
        Page<SysLoginLog> page = new Page<>(current <= 0 ? 1 : current, size <= 0 ? 20 : size);
        LambdaQueryWrapper<SysLoginLog> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.hasText(keyword)) {
            String value = keyword.trim();
            wrapper.and(item -> item.like(SysLoginLog::getUserName, value).or().like(SysLoginLog::getNickName, value));
        }
        if (StringUtils.hasText(status)) {
            wrapper.eq(SysLoginLog::getStatus, status.trim());
        }
        LocalDateTime start = parseStart(startDate);
        LocalDateTime end = parseEnd(endDate);
        if (start != null) {
            wrapper.ge(SysLoginLog::getLoginTime, start);
        }
        if (end != null) {
            wrapper.le(SysLoginLog::getLoginTime, end);
        }
        wrapper.orderByDesc(SysLoginLog::getLoginTime);
        return loginLogMapper.selectPage(page, wrapper);
    }
 
    public Page<SysOperationLog> operationLogPage(int current, int size, String keyword, String module, String operationType, String startDate, String endDate) {
        Page<SysOperationLog> page = new Page<>(current <= 0 ? 1 : current, size <= 0 ? 20 : size);
        LambdaQueryWrapper<SysOperationLog> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.hasText(keyword)) {
            String value = keyword.trim();
            wrapper.and(item -> item.like(SysOperationLog::getUserName, value)
                    .or().like(SysOperationLog::getNickName, value)
                    .or().like(SysOperationLog::getRequestUri, value));
        }
        if (StringUtils.hasText(module)) {
            wrapper.eq(SysOperationLog::getModule, module.trim());
        }
        if (StringUtils.hasText(operationType)) {
            wrapper.eq(SysOperationLog::getOperationType, operationType.trim());
        }
        LocalDateTime start = parseStart(startDate);
        LocalDateTime end = parseEnd(endDate);
        if (start != null) {
            wrapper.ge(SysOperationLog::getCreateTime, start);
        }
        if (end != null) {
            wrapper.le(SysOperationLog::getCreateTime, end);
        }
        wrapper.orderByDesc(SysOperationLog::getCreateTime);
        return operationLogMapper.selectPage(page, wrapper);
    }
 
    public Page<SysErrorLog> errorLogPage(int current, int size, String keyword, String module, String exceptionType, String startDate, String endDate) {
        Page<SysErrorLog> page = new Page<>(current <= 0 ? 1 : current, size <= 0 ? 20 : size);
        LambdaQueryWrapper<SysErrorLog> wrapper = Wrappers.lambdaQuery();
        wrapper.select(SysErrorLog::getId, SysErrorLog::getUserId, SysErrorLog::getUserName,
                SysErrorLog::getNickName, SysErrorLog::getModule, SysErrorLog::getRequestMethod,
                SysErrorLog::getRequestUri, SysErrorLog::getExceptionType, SysErrorLog::getMessage,
                SysErrorLog::getErrorTime);
        if (StringUtils.hasText(keyword)) {
            String value = keyword.trim();
            wrapper.and(item -> item.like(SysErrorLog::getUserName, value)
                    .or().like(SysErrorLog::getNickName, value)
                    .or().like(SysErrorLog::getRequestUri, value)
                    .or().like(SysErrorLog::getExceptionType, value)
                    .or().like(SysErrorLog::getMessage, value));
        }
        if (StringUtils.hasText(module)) {
            wrapper.eq(SysErrorLog::getModule, module.trim());
        }
        if (StringUtils.hasText(exceptionType)) {
            wrapper.like(SysErrorLog::getExceptionType, exceptionType.trim());
        }
        LocalDateTime start = parseStart(startDate);
        LocalDateTime end = parseEnd(endDate);
        if (start != null) {
            wrapper.ge(SysErrorLog::getErrorTime, start);
        }
        if (end != null) {
            wrapper.le(SysErrorLog::getErrorTime, end);
        }
        wrapper.orderByDesc(SysErrorLog::getErrorTime);
        return errorLogMapper.selectPage(page, wrapper);
    }
 
    public SysErrorLog errorLog(Long id) {
        SysErrorLog log = errorLogMapper.selectById(id);
        if (log == null) {
            throw new BusinessException("错误日志不存在");
        }
        return log;
    }
 
    public Long resolveUserId(String username) {
        if (!StringUtils.hasText(username)) {
            return null;
        }
        List<Long> ids = jdbcTemplate.query(
                "SELECT USER_ID FROM CSICZB_ZB.SYS_USER WHERE USER_NAME = ? AND (DEL_FLAG = '0' OR DEL_FLAG IS NULL)",
                new Object[]{username}, (rs, rowNum) -> rs.getLong(1));
        return ids.isEmpty() ? null : ids.get(0);
    }
 
    private List<Long> expandWithAncestors(List<Long> ids) {
        Set<Long> result = new LinkedHashSet<>();
        if (ids == null) {
            return new ArrayList<>(result);
        }
        for (Long id : ids) {
            Long cursor = id;
            int guard = 0;
            while (cursor != null && cursor != 0L && guard++ < 32) {
                if (!result.add(cursor)) {
                    break;
                }
                SysMenu menu = menuMapper.selectById(cursor);
                if (menu == null) {
                    break;
                }
                cursor = menu.getPid();
            }
        }
        return new ArrayList<>(result);
    }
 
    private LocalDateTime parseStart(String value) {
        if (!StringUtils.hasText(value)) {
            return null;
        }
        try {
            return LocalDate.parse(value.trim()).atStartOfDay();
        } catch (Exception ex) {
            return null;
        }
    }
 
    private LocalDateTime parseEnd(String value) {
        if (!StringUtils.hasText(value)) {
            return null;
        }
        try {
            return LocalDate.parse(value.trim()).atTime(23, 59, 59);
        } catch (Exception ex) {
            return null;
        }
    }
 
    public Map<String, Object> threeMemberOverview() {
        List<SysRole> roles = listRoles().stream()
                .filter(item -> Arrays.asList("SYSTEM_ADMIN", "SECURITY_ADMIN", "AUDIT_ADMIN").contains(item.getRoleType()))
                .collect(Collectors.toList());
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("roles", roles);
        result.put("users", Collections.singletonList(row("id", 1L, "name", "admin", "realName", "系统管理员")));
        result.put("assignments", roleUserMapper.selectList(null));
        return result;
    }
 
    private List<SysMenu> flatten(List<SysMenu> menus, Long pid) {
        return menus.stream()
                .filter(item -> pid == null ? item.getPid() == null || item.getPid() == 0L : pid.equals(item.getPid()))
                .sorted(Comparator.comparing(SysMenu::getSortNo, Comparator.nullsLast(Integer::compareTo)))
                .collect(Collectors.toList());
    }
 
    private void sortTree(List<SysMenu> nodes) {
        nodes.sort(Comparator.comparing(SysMenu::getSortNo, Comparator.nullsLast(Integer::compareTo)));
        for (SysMenu node : nodes) {
            sortTree(node.getChildren());
        }
    }
 
    private Map<String, Object> mapProduct(ProductNode node) {
        return mapProduct(node, Collections.emptySet());
    }
 
    private Map<String, Object> mapProduct(ProductNode node, Set<Long> branchIds) {
        Map<String, Object> row = new LinkedHashMap<>();
        row.put("id", String.valueOf(node.getId()));
        row.put("parentId", node.getParentId() == null ? null : String.valueOf(node.getParentId()));
        row.put("nodeLevel", node.getNodeLevel());
        row.put("nodeType", node.getNodeType());
        row.put("layer", node.getLayer());
        row.put("connectGroup", node.getConnectGroup());
        row.put("name", node.getName());
        row.put("code", node.getCode());
        row.put("baseEquipmentId", node.getBaseEquipmentId() == null ? null : String.valueOf(node.getBaseEquipmentId()));
        row.put("project", node.getProject());
        row.put("sortNo", node.getSortNo());
        row.put("remark", node.getRemark());
        row.put("isLeaf", !branchIds.contains(node.getId()));
        row.put("children", new ArrayList<>());
        return row;
    }
 
    private int productNodeLevel(ProductNode node) {
        Integer level = node.getNodeLevel();
        return level == null ? Integer.MAX_VALUE : level;
    }
 
    private String resolveProductLayer(ProductNode node) {
        String layer = ProductNode.layerForType(node.getNodeType());
        if (!StringUtils.hasText(layer)) {
            layer = ProductNode.layerForLevel(node.getNodeLevel());
        }
        if (!StringUtils.hasText(layer)) {
            layer = StringUtils.hasText(node.getLayer()) ? node.getLayer().trim().toLowerCase() : null;
        }
        if (!StringUtils.hasText(layer)) {
            throw new BusinessException("节点层级不能为空");
        }
        return layer;
    }
 
    private String buildConnectGroup(Long parentId) {
        if (parentId == null || parentId == 0L) {
            return "0";
        }
        ProductNode parent = findProductNode(parentId);
        if (parent == null) {
            throw new BusinessException("父节点不存在");
        }
        String prefix = StringUtils.hasText(parent.getConnectGroup()) ? parent.getConnectGroup() : "0";
        return prefix + "," + parent.getId();
    }
 
    private ProductNode findProductNode(Long id) {
        if (id == null) {
            return null;
        }
        List<ProductNode> nodes = productNodeMapper.selectList(Wrappers.<ProductNode>lambdaQuery()
                .eq(ProductNode::getId, id)
                .orderByAsc(ProductNode::getRecordId)
                .last("LIMIT 1"));
        return nodes.isEmpty() ? null : nodes.get(0);
    }
 
    private Map<String, Object> mapBase(BaseEquipment node) {
        Map<String, Object> row = new LinkedHashMap<>();
        row.put("id", String.valueOf(node.getId()));
        row.put("parentId", node.getParentId() == null ? null : String.valueOf(node.getParentId()));
        row.put("nodeLevel", node.getNodeLevel());
        row.put("nodeType", "BASE_" + node.getNodeLevel());
        row.put("name", node.getName());
        row.put("code", node.getCode());
        row.put("sortNo", node.getSortNo());
        row.put("remark", node.getRemark());
        row.put("children", new ArrayList<>());
        return row;
    }
 
    @SuppressWarnings("unchecked")
    private List<Map<String, Object>> children(Map<String, Object> node) {
        return (List<Map<String, Object>>) node.get("children");
    }
 
    private void assertNoChildren(long count) {
        if (count > 0) {
            throw new BusinessException("请先删除下级节点");
        }
    }
 
    private Map<String, Object> row(Object... values) {
        Map<String, Object> row = new LinkedHashMap<>();
        for (int i = 0; i < values.length; i += 2) {
            row.put(String.valueOf(values[i]), values[i + 1]);
        }
        return row;
    }
}