刘光辉
9 小时以前 06f314545ac3514d7ce28939920866ae8188d31c
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
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
package jnpf.permission.service.impl;
 
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrPool;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import jnpf.base.ActionResult;
import jnpf.base.ActionResultCode;
import jnpf.base.ModuleApi;
import jnpf.base.ModuleButtonApi;
import jnpf.base.SysConfigApi;
import jnpf.base.SystemApi;
import jnpf.base.UserInfo;
import jnpf.base.entity.ModuleButtonEntity;
import jnpf.base.entity.ModuleEntity;
import jnpf.base.entity.SystemEntity;
import jnpf.base.model.base.SystemApiByIdsModel;
import jnpf.base.model.base.SystemApiModel;
import jnpf.base.model.base.SystemBaeModel;
import jnpf.base.model.button.ButtonModel;
import jnpf.base.model.column.ColumnModel;
import jnpf.base.model.form.ModuleFormModel;
import jnpf.base.model.module.ModuleApiByIdAndMarkModel;
import jnpf.base.model.module.ModuleApiByIdsModel;
import jnpf.base.model.module.ModuleModel;
import jnpf.base.model.module.MenuPermissionQueryModel;
import jnpf.base.model.button.ModuleButtonModel;
import jnpf.base.model.portalmanage.SavePortalAuthModel;
import jnpf.base.model.resource.ResourceModel;
import jnpf.base.service.SuperServiceImpl;
import jnpf.config.ConfigValueUtil;
import jnpf.constant.*;
import jnpf.database.model.dto.PrepSqlDTO;
import jnpf.database.model.query.SuperJsonModel;
import jnpf.database.model.query.SuperQueryJsonModel;
import jnpf.database.sql.util.SqlFrameFastUtil;
import jnpf.database.util.DataSourceUtil;
import jnpf.database.util.DbTypeUtil;
import jnpf.database.util.JdbcUtil;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.DataException;
import jnpf.exception.NoPermiLoginException;
import jnpf.model.BaseSystemInfo;
import jnpf.model.login.UserSystemVO;
import jnpf.model.tenant.TenantAuthorizeModel;
import jnpf.model.visualjson.FieLdsModel;
import jnpf.model.visualjson.config.ConfigModel;
import jnpf.permission.entity.*;
import jnpf.permission.mapper.*;
import jnpf.permission.model.authorize.*;
import jnpf.permission.model.condition.AuthConditionModel;
import jnpf.permission.model.condition.AuthGroup;
import jnpf.permission.model.condition.AuthItem;
import jnpf.permission.model.position.PosConModel;
import jnpf.permission.model.user.UserRelationIds;
import jnpf.permission.service.AuthorizeService;
import jnpf.permission.service.PermissionGroupService;
import jnpf.permission.service.UserService;
import jnpf.permission.util.AuthPermUtil;
import jnpf.permission.util.UserUtil;
import jnpf.util.*;
import jnpf.util.context.RequestContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
 
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 操作权限
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月26日 上午9:18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthorizeServiceImpl extends SuperServiceImpl<AuthorizeMapper, AuthorizeEntity> implements AuthorizeService {
 
    private final DataSourceUtil dataSourceUtils;
    private final CacheKeyUtil cacheKeyUtil;
    private final ConfigValueUtil configValueUtil;
    private final RedisUtil redisUtil;
    private final SysConfigApi sysconfigApi;
    private final ModuleApi moduleApi;
    private final SystemApi systemApi;
    private final UserUtil userUtil;
    private final UserMapper userMapper;
    private final OrganizeMapper organizeMapper;
    private final PositionMapper positionMapper;
    private final RoleMapper roleMapper;
    private final StandingMapper standingMapper;
    private final RoleRelationMapper roleRelationMapper;
    private final UserRelationMapper userRelationMapper;
    private final PermissionGroupService permissionGroupService;
    private final UserService userService;
    private final ModuleButtonApi moduleButtonApi;
 
    @Override
    public UserPermissionProbe.Result probeUserPermission(UserPermissionProbe probe) {
        try {
            if (probe == null || StringUtils.isBlank(probe.getTenantId())
                    || StringUtils.isBlank(probe.getUserId()) || StringUtils.isBlank(probe.getSystemCode())
                    || StringUtils.isBlank(probe.getModuleCode())
                    || StringUtils.isBlank(probe.getModuleCategory())) {
                return denied("INVALID_REQUEST");
            }
            TenantDataSourceUtil.switchTenant(probe.getTenantId());
            List<SystemEntity> targetSystems = permissionTargetCandidates(
                    systemApi.getPermissionTargetCandidates(), "系统");
            List<SystemEntity> matchingSystems = targetSystems.stream()
                    .filter(Objects::nonNull)
                    .filter(this::isActiveSystem)
                    .filter(item -> Objects.equals(probe.getSystemCode(), item.getEnCode()))
                    .collect(Collectors.toList());
            if (matchingSystems.isEmpty()) {
                return denied("SYSTEM_UNAVAILABLE");
            }
            if (matchingSystems.size() > 1) {
                return denied("SYSTEM_AMBIGUOUS");
            }
            SystemEntity targetSystem = matchingSystems.get(0);
            List<ModuleEntity> targetModules = permissionTargetCandidates(
                    moduleApi.getPermissionTargetCandidates(Collections.singletonList(probe.getModuleCode())),
                    "菜单");
            List<ModuleEntity> matchingModules = targetModules.stream()
                    .filter(Objects::nonNull)
                    .filter(this::isActiveModule)
                    .filter(item -> Objects.equals(targetSystem.getId(), item.getSystemId()))
                    .filter(item -> Objects.equals(probe.getModuleCode(), item.getEnCode()))
                    .filter(item -> Objects.equals(probe.getModuleCategory(), item.getCategory()))
                    .collect(Collectors.toList());
            if (matchingModules.isEmpty()) {
                return denied("MODULE_UNAVAILABLE");
            }
            if (matchingModules.size() > 1) {
                return denied("MODULE_AMBIGUOUS");
            }
            String moduleId = matchingModules.get(0).getId();
            UserEntity user = userService.getInfo(probe.getUserId());
            if (user == null || !Objects.equals(user.getEnabledMark(), 1)) {
                return denied("USER_UNAVAILABLE");
            }
            if (Objects.equals(user.getIsAdministrator(), 1)) {
                return allowed("ADMINISTRATOR");
            }
 
            UserRelationIds relationIds = userService.getUserObjectIdList(probe.getUserId());
            if (relationIds == null) {
                return denied("NO_CURRENT_RELATION");
            }
            List<String> positionIds = currentActiveIds(relationIds.getPosition(),
                    positionMapper.getListByIds(normalizeRelationIds(relationIds.getPosition())));
            List<String> organizeIds = currentActiveIds(relationIds.getOrganize(),
                    organizeMapper.getListByIds(normalizeRelationIds(relationIds.getOrganize())));
 
            List<String> roleSourceIds = new ArrayList<>();
            roleSourceIds.add(probe.getUserId());
            roleSourceIds.addAll(organizeIds);
            roleSourceIds.addAll(positionIds);
            List<RoleRelationEntity> roleRelations = roleRelationMapper.getListByObjectId(roleSourceIds, null);
            if (roleRelations == null) {
                throw new IllegalStateException("角色关系查询返回 null");
            }
            List<String> roleIds = roleRelations.stream()
                    .filter(item -> isCurrentRoleSource(item, probe.getUserId(), organizeIds, positionIds))
                    .map(RoleRelationEntity::getRoleId)
                    .filter(StringUtils::isNotBlank)
                    .distinct()
                    .collect(Collectors.toList());
            List<String> activeRoleIds = currentActiveIds(roleIds, roleMapper.getListByIds(roleIds));
 
            List<String> objectIds = new ArrayList<>();
            objectIds.addAll(positionIds);
            objectIds.addAll(activeRoleIds);
            if (objectIds.isEmpty()) {
                return denied("NO_CURRENT_RELATION");
            }
 
            List<AuthorizeEntity> authorizations = this.getListByObjectId(objectIds);
            if (CollUtil.isEmpty(authorizations)) {
                return denied("NO_AUTHORIZATION");
            }
            boolean menuAllowed = authorizations.stream().anyMatch(item ->
                    AuthorizeConst.MODULE.equals(item.getItemType()) && moduleId.equals(item.getItemId()));
            if (!menuAllowed) {
                return denied("MODULE_DENIED");
            }
            if (StringUtils.isBlank(probe.getButtonCode())) {
                return allowed("ALLOWED");
            }
 
            ModuleButtonModel buttonModel = new ModuleButtonModel(Collections.singletonList(moduleId), null);
            List<ModuleButtonEntity> buttons = moduleButtonApi.getListByModuleIds(buttonModel);
            ModuleButtonEntity button = CollUtil.isEmpty(buttons) ? null : buttons.stream()
                    .filter(item -> probe.getButtonCode().equals(item.getEnCode())
                            && Objects.equals(item.getEnabledMark(), 1))
                    .findFirst().orElse(null);
            if (button == null) {
                return denied("BUTTON_UNAVAILABLE");
            }
            boolean buttonAllowed = authorizations.stream().anyMatch(item ->
                    AuthorizeConst.BUTTON.equals(item.getItemType()) && button.getId().equals(item.getItemId()));
            return buttonAllowed ? allowed("ALLOWED") : denied("BUTTON_DENIED");
        } catch (Exception e) {
            log.warn("用户权限探针依赖查询失败", e);
            return denied("DEPENDENCY_FAILURE");
        } finally {
            TenantDataSourceUtil.clearLocalTenantInfo();
        }
    }
 
    private boolean isActiveSystem(SystemEntity system) {
        return system != null
                && Objects.equals(system.getEnabledMark(), 1)
                && (system.getDeleteMark() == null || Objects.equals(system.getDeleteMark(), 0));
    }
 
    private boolean isActiveModule(ModuleEntity module) {
        return StringUtils.isNotBlank(module.getId())
                && Objects.equals(module.getEnabledMark(), 1)
                && (module.getDeleteMark() == null || Objects.equals(module.getDeleteMark(), 0));
    }
 
    private <T> List<T> permissionTargetCandidates(ActionResult<List<T>> result, String targetType) {
        if (result == null || !ActionResultCode.SUCCESS.getCode().equals(result.getCode())
                || result.getData() == null) {
            throw new IllegalStateException(targetType + "权限目标查询失败");
        }
        return result.getData();
    }
 
    private List<String> normalizeRelationIds(List<String> relationIds) {
        if (CollUtil.isEmpty(relationIds)) {
            return Collections.emptyList();
        }
        return relationIds.stream().filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
    }
 
    private List<String> currentActiveIds(List<String> relationIds,
                                          List<? extends PermissionEntityBase> entities) {
        List<String> requestedIds = normalizeRelationIds(relationIds);
        if (requestedIds.isEmpty()) {
            return Collections.emptyList();
        }
        if (entities == null) {
            throw new IllegalStateException("权限关系实体查询返回 null");
        }
        Set<String> activeIds = entities.stream()
                .filter(Objects::nonNull)
                .filter(this::isActivePermissionEntity)
                .map(PermissionEntityBase::getId)
                .filter(requestedIds::contains)
                .collect(Collectors.toSet());
        return requestedIds.stream().filter(activeIds::contains).collect(Collectors.toList());
    }
 
    private boolean isActivePermissionEntity(PermissionEntityBase entity) {
        return Objects.equals(entity.getEnabledMark(), 1)
                && (entity.getDeleteMark() == null || Objects.equals(entity.getDeleteMark(), 0));
    }
 
    private boolean isCurrentRoleSource(RoleRelationEntity relation, String userId,
                                        List<String> organizeIds, List<String> positionIds) {
        if (relation == null) {
            return false;
        }
        if (PermissionConst.USER.equals(relation.getObjectType())) {
            return userId.equals(relation.getObjectId());
        }
        if (PermissionConst.ORGANIZE.equals(relation.getObjectType())) {
            return organizeIds.contains(relation.getObjectId());
        }
        return PermissionConst.POSITION.equals(relation.getObjectType())
                && positionIds.contains(relation.getObjectId());
    }
 
    private UserPermissionProbe.Result allowed(String reasonCode) {
        return new UserPermissionProbe.Result(true, reasonCode);
    }
 
    private UserPermissionProbe.Result denied(String reasonCode) {
        return new UserPermissionProbe.Result(false, reasonCode);
    }
 
    //当前系统权限
    @Override
    public AuthorizeVO getAuthorize(boolean singletonOrg, String currentSystemCode, Integer isBackend) {
        return this.getAuthorize(singletonOrg, currentSystemCode, isBackend, false);
    }
 
    @Override
    public MenuPermissionQueryModel getAuthorizeModules(boolean singletonOrg, String currentSystemCode) {
        long startedAt = System.nanoTime();
        UserInfo userInfo = UserProvider.getUser();
        UserEntity currentUser = userMapper.getInfo(userInfo.getUserId());
        String currentStandingId = RequestContext.isOrignPc() ? currentUser.getStanding() : currentUser.getAppStanding();
        String cacheKey = cacheKeyUtil.getUserAuthorize() + "menu:" + userInfo.getTenantId() + ":" + userInfo.getUserId()
                + ":" + RequestContext.isOrignPc() + ":" + currentStandingId + ":" + currentSystemCode + ":" + singletonOrg;
        MenuPermissionQueryModel cached = getCachedMenuPermission(cacheKey);
        if (cached != null) {
            applyTenantMenuConstraints(cached, userInfo.getTenantId());
            log.info("menuPermission cache hit: systemId={}, admin={}, moduleCount={}, elapsedMs={}",
                    cached.getSystemId(), cached.isAdministrator(), cached.getModuleIds().size(),
                    (System.nanoTime() - startedAt) / 1_000_000);
            return cached;
        }
 
        MenuPermissionQueryModel result = new MenuPermissionQueryModel();
        result.setAdministrator(Boolean.TRUE.equals(userInfo.getIsAdministrator()));
 
        SystemEntity system = systemApi.getInfoByEnCode(currentSystemCode);
        if (system == null) {
            system = systemApi.getInfoById(currentSystemCode);
        }
        if (system == null) {
            throw new NoPermiLoginException(MsgCode.PS032.get());
        }
        result.setSystemId(system.getId());
 
        applyTenantMenuConstraints(result, userInfo.getTenantId());
 
        if (!result.isAdministrator()) {
            List<String> positionIds = userInfo.getPositionIds();
            List<String> roleIds = roleMapper.getListByIds(userInfo.getRoleIds()).stream()
                    .filter(t -> !PermissionConst.ORGANIZE.equals(t.getType()))
                    .map(RoleEntity::getId)
                    .collect(Collectors.toList());
            List<String> objectIds = new ArrayList<>(positionIds);
            objectIds.addAll(roleIds);
            List<AuthorizeEntity> authorizeList = this.baseMapper.getListByObjectIdAndItemTypes(
                    objectIds, Arrays.asList(PermissionConst.STAND, AuthorizeConst.MODULE));
 
            BaseSystemInfo systemInfo = sysconfigApi.getSysConfigInfo();
            List<AuthorizeEntity> standingList = authorizeList.stream()
                    .filter(t -> PermissionConst.STAND.equals(t.getItemType()))
                    .collect(Collectors.toList());
            if (CollUtil.isNotEmpty(standingList) && Objects.equals(systemInfo.getStandingSwitch(), 1)) {
                List<String> standingIds = standingList.stream().map(AuthorizeEntity::getItemId).collect(Collectors.toList());
                String standingId = setCurrentStanding(standingIds, new ArrayList<>());
                if (StringUtil.isNotEmpty(standingId)) {
                    List<String> standingPositions = standingList.stream()
                            .filter(t -> standingId.equals(t.getItemId()) && PermissionConst.POSITION.equals(t.getObjectType()))
                            .map(AuthorizeEntity::getObjectId)
                            .collect(Collectors.toList());
                    List<String> standingRoleIds = roleRelationMapper.getListByObjectId(standingPositions, null).stream()
                            .map(RoleRelationEntity::getRoleId)
                            .collect(Collectors.toList());
                    standingRoleIds.addAll(standingList.stream()
                            .filter(t -> standingId.equals(t.getItemId()) && PermissionConst.ROLE.equals(t.getObjectType()))
                            .map(AuthorizeEntity::getObjectId)
                            .collect(Collectors.toList()));
                    Set<String> activeObjects = new HashSet<>(standingPositions);
                    activeObjects.addAll(standingRoleIds);
                    authorizeList = authorizeList.stream()
                            .filter(t -> activeObjects.contains(t.getObjectId()))
                            .collect(Collectors.toList());
                }
            }
            result.setModuleIds(authorizeList.stream()
                    .filter(t -> AuthorizeConst.MODULE.equals(t.getItemType()))
                    .map(AuthorizeEntity::getItemId)
                    .distinct()
                    .collect(Collectors.toList()));
        }
 
        log.info("menuPermission resolved: systemId={}, admin={}, moduleCount={}, elapsedMs={}",
                result.getSystemId(), result.isAdministrator(), result.getModuleIds().size(),
                (System.nanoTime() - startedAt) / 1_000_000);
        cacheMenuPermission(cacheKey, result);
        return result;
    }
 
    private MenuPermissionQueryModel getCachedMenuPermission(String cacheKey) {
        try {
            Object cachedValue = redisUtil.getString(cacheKey);
            return cachedValue == null ? null : JsonUtil.getJsonToBean(cachedValue.toString(), MenuPermissionQueryModel.class);
        } catch (Exception e) {
            log.warn("menuPermission cache read failed, falling back to database: {}", e.getMessage());
            return null;
        }
    }
 
    private void cacheMenuPermission(String cacheKey, MenuPermissionQueryModel permission) {
        try {
            MenuPermissionQueryModel cacheValue = new MenuPermissionQueryModel();
            cacheValue.setSystemId(permission.getSystemId());
            cacheValue.setAdministrator(permission.isAdministrator());
            cacheValue.setModuleIds(permission.getModuleIds());
            redisUtil.insert(cacheKey, JsonUtil.getObjectToString(cacheValue), 120L);
        } catch (Exception e) {
            log.warn("menuPermission cache write failed: {}", e.getMessage());
        }
    }
 
    private void applyTenantMenuConstraints(MenuPermissionQueryModel permission, String tenantId) {
        permission.setExcludedModuleIds(new ArrayList<>());
        permission.setExcludedUrlAddresses(new ArrayList<>());
        if (!configValueUtil.isMultiTenancy()) {
            return;
        }
        TenantAuthorizeModel tenantAuthorize = TenantDataSourceUtil.getCacheModuleAuthorize(tenantId);
        if (tenantAuthorize == null) {
            return;
        }
        List<String> excludedModuleIds = tenantAuthorize.getModuleIdList();
        List<String> excludedUrlAddresses = tenantAuthorize.getUrlAddressList();
        permission.setExcludedModuleIds(new ArrayList<>(excludedModuleIds == null ? Collections.emptyList() : excludedModuleIds));
        permission.setExcludedUrlAddresses(new ArrayList<>(excludedUrlAddresses == null ? Collections.emptyList() : excludedUrlAddresses));
    }
 
    //全部系统权限
    @Override
    public AuthorizeVO getAuthorizeByUser(boolean singletonOrg) {
        //获取全部应用权限
        return this.getAuthorize(singletonOrg, null, 0, true);
    }
 
    @Override
    public AuthorizeVO getAuthorize(boolean singletonOrg, String currentSystemCode, Integer isBackend, boolean allSystem) {
        return this.getAuthorize(singletonOrg, currentSystemCode, isBackend, allSystem, false);
    }
 
    private AuthorizeVO getAuthorize(boolean singletonOrg, String currentSystemCode, Integer isBackend, boolean allSystem, boolean modulesOnly) {
        boolean isPc = RequestContext.isOrignPc();
        String pcCode = isPc ? JnpfConst.WEB : JnpfConst.APP;
        BaseSystemInfo baseSystemInfo = sysconfigApi.getSysConfigInfo();
        UserInfo userInfo = UserProvider.getUser();
        OtherModel otherModel = new OtherModel();
        List<ModuleModel> moduleList = new ArrayList<>();
        List<ButtonModel> buttonList = new ArrayList<>();
        List<ColumnModel> columnList = new ArrayList<>();
        List<ResourceModel> resourceList = new ArrayList<>();
        List<ModuleFormModel> formsList = new ArrayList<>();
        List<SystemBaeModel> systemList = new ArrayList<>();
        List<String> flowList = new ArrayList<>();
        List<UserSystemVO> standingListVo = new ArrayList<>();
        boolean isAdmin = userInfo.getIsAdministrator();
        String currentSystemId = "";
        SystemEntity info = null;
        if (StringUtil.isNotEmpty(currentSystemCode)) {
            try {
                currentSystemCode = URLDecoder.decode(currentSystemCode, "UTF-8");
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            info = systemApi.getInfoByEnCode(currentSystemCode);
            if (info == null) {
                throw new NoPermiLoginException(MsgCode.PS032.get());
            }
            currentSystemId = info.getId();
        }
 
        List<String> moduleAuthorize = new ArrayList<>();
        List<String> moduleUrlAddressAuthorize = new ArrayList<>();
        if (configValueUtil.isMultiTenancy()) {
            TenantAuthorizeModel tenantAuthorizeModel = TenantDataSourceUtil.getCacheModuleAuthorize(userInfo.getTenantId());
            moduleAuthorize = tenantAuthorizeModel.getModuleIdList();
            moduleUrlAddressAuthorize = tenantAuthorizeModel.getUrlAddressList();
        }
 
        //后台菜单编码列表
        List<String> appComModule = new ArrayList<>();
        appComModule.add(JnpfConst.APP_BACKEND);
        appComModule.addAll(JnpfConst.APP_CONFIG_MODULE);
        appComModule.addAll(JnpfConst.ONLINE_DEV_MODULE);
        if (!isAdmin) {
            //获取用户所有权限
            List<String> objectIds = new ArrayList<>();
            List<String> positionIds = userInfo.getPositionIds();
            List<String> roleIds = roleMapper.getListByIds(userInfo.getRoleIds()).stream()
                    .filter(t -> !PermissionConst.ORGANIZE.equals(t.getType())).map(RoleEntity::getId).collect(Collectors.toList());
            objectIds.addAll(positionIds);
            objectIds.addAll(roleIds);
            List<AuthorizeEntity> authorizeList = this.getListByObjectId(objectIds);
            List<AuthorizeEntity> standingList = authorizeList.stream().filter(t -> PermissionConst.STAND.equals(t.getItemType())).collect(Collectors.toList());
 
            List<String> posAndRoles = new ArrayList<>();
            //非管理员,走身份(standingSwitch)
            if (CollUtil.isNotEmpty(standingList) && Objects.equals(baseSystemInfo.getStandingSwitch(), 1)) {
                //获取身份id列表
                List<String> standingIds = standingList.stream().map(AuthorizeEntity::getItemId).collect(Collectors.toList());
                //设置当前身份
                String standingId = setCurrentStanding(standingIds, standingListVo);
                if (StringUtil.isNotEmpty(standingId)) {
                    //根据当前身份获取角色和岗位
                    List<String> stdPos = standingList.stream().filter(t -> t.getItemId().equals(standingId)
                            && PermissionConst.POSITION.equals(t.getObjectType())).map(AuthorizeEntity::getObjectId).collect(Collectors.toList());
                    //获取当前岗位角色
                    List<String> stdPosRole = roleRelationMapper.getListByObjectId(stdPos, null)
                            .stream().map(RoleRelationEntity::getRoleId).collect(Collectors.toList());
                    List<String> stdRole = standingList.stream().filter(t -> t.getItemId().equals(standingId)
                            && PermissionConst.ROLE.equals(t.getObjectType())).map(AuthorizeEntity::getObjectId).collect(Collectors.toList());
                    posAndRoles.addAll(stdPos);
                    posAndRoles.addAll(stdPosRole);
                    posAndRoles.addAll(stdRole);
                    //重新设置当前用户角色
                    List<RoleEntity> roleList = roleMapper.getListByIds(stdRole);
                    for (RoleEntity roleEntity : roleList) {
                        if (PermissionConst.MANAGER_CODE.equals(roleEntity.getEnCode())) {
                            otherModel.setIsManageRole(true);
                        } else if (PermissionConst.DEVELOPER_CODE.equals(roleEntity.getEnCode())) {
                            otherModel.setIsDevRole(true);
                        } else if (PermissionConst.USER_CODE.equals(roleEntity.getEnCode())) {
                            otherModel.setIsUserRole(true);
                        } else {
                            otherModel.setIsOtherRole(true);
                        }
                    }
                    //通过身份过滤掉多于的权限
                    authorizeList = authorizeList.stream().filter(t -> posAndRoles.contains(t.getObjectId())).collect(Collectors.toList());
                }
            } else {
                //重新设置当前用户角色
                List<RoleEntity> roleList = roleMapper.getListByIds(roleIds);
                for (RoleEntity roleEntity : roleList) {
                    if (PermissionConst.MANAGER_CODE.equals(roleEntity.getEnCode())) {
                        otherModel.setIsManageRole(true);
                    } else if (PermissionConst.DEVELOPER_CODE.equals(roleEntity.getEnCode())) {
                        otherModel.setIsDevRole(true);
                    } else if (PermissionConst.USER_CODE.equals(roleEntity.getEnCode())) {
                        otherModel.setIsUserRole(true);
                    } else {
                        otherModel.setIsOtherRole(true);
                    }
                }
            }
 
            //应用
            List<String> sysMainList = systemApi.getMainList().stream().map(SystemEntity::getId).collect(Collectors.toList());
            List<String> authSysList = authorizeList.stream().filter(t -> t.getItemId().contains(pcCode))
                    .map(t -> t.getItemId().substring(0, t.getItemId().indexOf(pcCode))).collect(Collectors.toList());
            List<String> systemId = authorizeList.stream().filter(t -> AuthorizeConst.SYSTEM.equals(t.getItemType()) &&
                            (Objects.equals(isBackend, 1) || authSysList.contains(t.getItemId()) || sysMainList.contains(t.getItemId())))
                    .map(AuthorizeEntity::getItemId).collect(Collectors.toList());
            if (!systemId.isEmpty()) {
                List<SystemEntity> systemAdmin = systemApi.getListByIds(new SystemApiByIdsModel(systemId, moduleAuthorize, singletonOrg ? 0 : 1));
                //配置了流程和协作的菜单但是没有主系统菜单时,直接添加主系统权限
                List<SystemEntity> mainList = systemAdmin.stream().filter(t -> JnpfConst.MAIN_SYSTEM_CODE.equals(t.getEnCode())).collect(Collectors.toList());
                if (CollUtil.isEmpty(mainList)) {
                    List<SystemEntity> collect = systemAdmin.stream().filter(t -> JnpfConst.WORK_FLOW_CODE.equals(t.getEnCode()) || JnpfConst.TEAMWORK_CODE.equals(t.getEnCode())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(collect)) {
                        systemAdmin.add(systemApi.getInfoByEnCode(JnpfConst.MAIN_SYSTEM_CODE));
                    }
                }
                //app无主应用时获取当前第一个应用
                String finalCurrentSystemId = currentSystemId;
                if (!isPc && (StringUtil.isEmpty(currentSystemCode) || !systemAdmin.stream().anyMatch(t->t.getId().equals(finalCurrentSystemId)))) {
                    info = systemAdmin.stream().filter(t -> !Objects.equals(t.getIsMain(), 1)).findFirst().orElse(null);
                    if (info != null) {
                        currentSystemId = info.getId();
                        currentSystemCode = info.getEnCode();
                    }
                }
                systemList = JsonUtil.getJsonToList(systemAdmin, SystemBaeModel.class);
            }
            List<String> moduleId = authorizeList.stream().filter(t -> AuthorizeConst.MODULE.equals(t.getItemType())).map(AuthorizeEntity::getItemId).collect(Collectors.toList());
            if (!moduleId.isEmpty()) {
                List<String> currSys = new ArrayList<>();
                if (StringUtil.isNotEmpty(currentSystemId) && !allSystem && !Objects.equals(isBackend, 1)) {
                    currSys.add(currentSystemId);
                }
                List<ModuleModel> allSysMenu = this.baseMapper.findModule(moduleId, currSys, moduleAuthorize, moduleUrlAddressAuthorize, singletonOrg ? 0 : 1);
                moduleList = CollUtil.isNotEmpty(currSys) ? allSysMenu.stream().filter(t -> currSys.contains(t.getSystemId())).collect(Collectors.toList()) : allSysMenu;
                //是后台管理-非admin
                if (Objects.equals(isBackend, 1)) {
                    moduleList = allSysMenu.stream().filter(t -> appComModule.contains(t.getEnCode())).collect(Collectors.toList());
                }
                //当前系统是否有流程菜单
                if (StringUtil.isNotEmpty(currentSystemCode)) {
                    if (JnpfConst.MAIN_SYSTEM_CODE.equals(currentSystemCode)) {
                        otherModel.setWorkflowEnabled(allSysMenu.stream().anyMatch(t -> JnpfConst.MODULE_CODE.contains(t.getEnCode()) && pcCode.equals(t.getCategory())) ? 1 : 0);
                    } else {
                        otherModel.setWorkflowEnabled(moduleList.stream().anyMatch(t -> JnpfConst.MODULE_CODE.contains(t.getEnCode()) && pcCode.equals(t.getCategory())) ? 1 : 0);
                    }
                }
            }
            if (!modulesOnly) {
                // 按钮
                List<String> buttonId = authorizeList.stream().filter(t -> AuthorizeConst.BUTTON.equals(t.getItemType())).map(AuthorizeEntity::getItemId).collect(Collectors.toList());
                if (!buttonId.isEmpty()) {
                    buttonList = this.baseMapper.findButton(buttonId);
                }
                // 列表
                List<String> columnId = authorizeList.stream().filter(t -> AuthorizeConst.COLUMN.equals(t.getItemType())).map(AuthorizeEntity::getItemId).collect(Collectors.toList());
                if (!columnId.isEmpty()) {
                    columnList = this.baseMapper.findColumn(columnId);
                }
                // 数据
                List<String> resourceId = authorizeList.stream().filter(t -> AuthorizeConst.RESOURCE.equals(t.getItemType())).map(AuthorizeEntity::getItemId).collect(Collectors.toList());
                if (!resourceId.isEmpty()) {
                    resourceList = this.baseMapper.findResource(resourceId);
                    if (CollUtil.isNotEmpty(posAndRoles)) {
                        resourceList = resourceList.stream().filter(t -> posAndRoles.contains(t.getObjectId())).collect(Collectors.toList());
                    }
                }
                // 表单
                List<String> formId = authorizeList.stream().filter(t -> AuthorizeConst.FROM.equals(t.getItemType())).map(AuthorizeEntity::getItemId).collect(Collectors.toList());
                if (!formId.isEmpty()) {
                    formsList = this.baseMapper.findForms(formId);
                }
                // 流程
                flowList = authorizeList.stream().filter(t -> AuthorizeConst.FLOW.equals(t.getItemType())).map(AuthorizeEntity::getItemId).collect(Collectors.toList());
            }
        } else {
            List<ModuleEntity> moduleAdmin;
            if (modulesOnly && StringUtil.isNotEmpty(currentSystemId)) {
                moduleAdmin = moduleApi.getModuleBySystemIds(new ModuleApiByIdsModel(
                        Collections.singletonList(currentSystemId), moduleAuthorize, moduleUrlAddressAuthorize, singletonOrg ? 0 : 1));
            } else {
                if (!modulesOnly) {
                    buttonList = this.baseMapper.findButtonAdmin(1);
                    columnList = this.baseMapper.findColumnAdmin(1);
                    resourceList = this.baseMapper.findResourceAdmin(1);
                    formsList = this.baseMapper.findFormsAdmin(1);
                }
                List<SystemEntity> systemAdmin = systemApi.findSystemAdmin(new SystemApiModel(moduleAuthorize));
                if (!isPc && StringUtil.isEmpty(currentSystemCode)) {
                    info = systemAdmin.stream().filter(t -> !Objects.equals(t.getIsMain(), 1)).findFirst().orElse(null);
                    if (info != null) {
                        currentSystemId = info.getId();
                        currentSystemCode = info.getEnCode();
                    }
                }
                systemList = JsonUtil.getJsonToList(systemAdmin, SystemBaeModel.class);
                moduleAdmin = moduleApi.findModuleAdmin(new ModuleApiByIdAndMarkModel(singletonOrg ? 0 : 1, null, moduleAuthorize, moduleUrlAddressAuthorize));
            }
            String thisid = currentSystemId;
            List<ModuleModel> allSysMenu = JsonUtil.getJsonToList(moduleAdmin, ModuleModel.class);
 
            if (StringUtil.isNotEmpty(currentSystemId) && !allSystem) {
                moduleList = allSysMenu.stream().filter(t -> Objects.equals(t.getSystemId(), thisid)).collect(Collectors.toList());
            } else {
                moduleList = allSysMenu;
            }
            //当前系统是否有流程菜单
            if (StringUtil.isNotEmpty(currentSystemCode)) {
                if (JnpfConst.MAIN_SYSTEM_CODE.equals(currentSystemCode)) {
                    otherModel.setWorkflowEnabled(allSysMenu.stream().anyMatch(t -> JnpfConst.MODULE_CODE.contains(t.getEnCode()) && pcCode.equals(t.getCategory())) ? 1 : 0);
                } else {
                    otherModel.setWorkflowEnabled(moduleList.stream().anyMatch(t -> JnpfConst.MODULE_CODE.contains(t.getEnCode()) && pcCode.equals(t.getCategory())) ? 1 : 0);
                }
            }
 
            //超管添加身份
            if (!modulesOnly && Objects.equals(baseSystemInfo.getStandingSwitch(), 1)) {
                UserSystemVO admin = new UserSystemVO();
                admin.setId(1 + "");
                admin.setName(MsgCode.OA025.get());
                admin.setCurrentStanding(true);
                admin.setIcon(PermissionConst.SD_ADMIN_ICON);
                standingListVo.add(admin);
            }
            //是后台管理-admin
            if (Objects.equals(isBackend, 1)) {
                List<ModuleEntity> listByEnCode = moduleApi.getListByEnCode(appComModule);
                if (CollUtil.isNotEmpty(moduleAuthorize)) {
                    List<String> finalModuleAuthorize = moduleAuthorize;
                    listByEnCode = listByEnCode.stream().filter(t -> !finalModuleAuthorize.contains(t.getEnCode())
                            && !finalModuleAuthorize.contains(t.getUrlAddress())).collect(Collectors.toList());
                }
                moduleList = JsonUtil.getJsonToList(listByEnCode, ModuleModel.class);
            }
        }
 
        //系统配置-流程开关
        moduleList = moduleList.stream().filter(t ->
                !((!Objects.equals(baseSystemInfo.getFlowSign(), 1) && JnpfConst.WORK_FLOWSIGN.equals(t.getEnCode())) ||
                        (!Objects.equals(baseSystemInfo.getFlowTodo(), 1) && JnpfConst.WORK_FLOWTODO.equals(t.getEnCode())) ||
                        (!Objects.equals(baseSystemInfo.getStandingSwitch(), 1) && JnpfConst.PERMISSION_IDENTITY.equals(t.getEnCode())))
        ).collect(Collectors.toList());
        //应用前台不需要添加菜单数据
        return AuthorizeVO.builder()
                .moduleList(moduleList)
                .buttonList(buttonList)
                .columnList(columnList)
                .resourceList(resourceList)
                .formsList(formsList)
                .systemList(systemList)
                .standingList(standingListVo)
                .currentSystem(info)
                .flowIdList(flowList)
                .otherModel(otherModel)
                .build();
    }
 
    /**
     * 设置当前身份
     *
     * @param standingIds
     * @param standingListVo
     */
    private String setCurrentStanding(List<String> standingIds, List<UserSystemVO> standingListVo) {
        List<StandingEntity> listByIds = standingMapper.getListByIds(standingIds);
        UserEntity info = userMapper.getInfo(UserProvider.getUser().getUserId());
        String currentStanding = "";
        if (RequestContext.isOrignPc()) {
            currentStanding = info.getStanding();
        } else {
            currentStanding = info.getAppStanding();
        }
        for (StandingEntity standing : listByIds) {
            UserSystemVO standingVo = JsonUtil.getJsonToBean(standing, UserSystemVO.class);
            standingVo.setName(standing.getFullName());
            if (StringUtil.isNotEmpty(currentStanding) && currentStanding.equals(standing.getId())) {
                standingVo.setCurrentStanding(true);
            }
            String icon = "";
            switch (standing.getEnCode()) {
                case PermissionConst.MANAGER_CODE:
                    icon = PermissionConst.SD_MANAGER_ICON;
                    break;
                case PermissionConst.DEVELOPER_CODE:
                    icon = PermissionConst.SD_DEVELOPER_ICON;
                    break;
                case PermissionConst.USER_CODE:
                    icon = PermissionConst.SD_USER_ICON;
                    break;
                default:
                    icon = PermissionConst.SD_EXPERIENCER_ICON;
                    break;
            }
            standingVo.setIcon(icon);
            standingListVo.add(standingVo);
        }
        if (CollUtil.isEmpty(standingListVo)) {
            return null;
        }
        UserSystemVO currStand = standingListVo.stream().filter(t -> t.isCurrentStanding()).findFirst().orElse(null);
        if (currStand == null) {
            UserSystemVO userSystemVO = standingListVo.stream().filter(t -> PermissionConst.USER_CODE.equals(t.getEnCode()))
                    .findFirst().orElse(standingListVo.get(0));
            userSystemVO.setCurrentStanding(true);
            if (RequestContext.isOrignPc()) {
                info.setStanding(userSystemVO.getId());
            } else {
                info.setAppStanding(userSystemVO.getId());
            }
            userMapper.updateById(info);
            currentStanding = userSystemVO.getId();
        } else {
            currentStanding = currStand.getId();
        }
        return currentStanding;
    }
 
    @Override
    @DSTransactional
    public void saveItemAuth(SavePortalAuthModel portalAuthModel) {
        List<String> ids = portalAuthModel.getIds();
        String id = portalAuthModel.getId();
        String type = portalAuthModel.getType();
        String userId = UserProvider.getLoginUserId();
        // 原始授权角色
        List<AuthorizeEntity> list = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            AuthorizeEntity authorizeEntity = new AuthorizeEntity();
            authorizeEntity.setId(RandomUtil.uuId());
            authorizeEntity.setItemType(type);
            authorizeEntity.setItemId(ids.get(i));
            authorizeEntity.setObjectType(portalAuthModel.getObjectType());
            authorizeEntity.setObjectId(id);
            authorizeEntity.setSortCode((long) i);
            authorizeEntity.setCreatorTime(new Date());
            authorizeEntity.setCreatorUserId(userId);
            list.add(authorizeEntity);
        }
        QueryWrapper<AuthorizeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthorizeEntity::getItemType, type);
        queryWrapper.lambda().eq(AuthorizeEntity::getObjectId, id);
        this.remove(queryWrapper);
        list.forEach(this::save);
        List<String> userIds = new ArrayList<>();
        String objectType = portalAuthModel.getObjectType();
        if (PermissionConst.ORGANIZE.equals(objectType) || PermissionConst.POSITION.equals(objectType)) {
            userIds.addAll(userRelationMapper.getListByObjectId(id).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList()));
        }
        if (PermissionConst.ROLE.equals(objectType)) {
            userIds.addAll(roleRelationMapper.getListByRoleId(id, PermissionConst.USER).stream().map(RoleRelationEntity::getObjectId).collect(Collectors.toList()));
        }
        userUtil.delCurUser(MsgCode.PS010.get(), userIds);
    }
 
    @Override
    public String save(AuthorizeDataUpForm form) {
        String errStr = "";
        try {
            UserInfo userInfo = UserProvider.getUser();
            String objectType = form.getObjectType();
            String objectId = form.getObjectId();
 
            List<AuthorizeEntity> objectList = new ArrayList<>();
            List<AuthorizeEntity> authorizeList = new ArrayList<>();
            PosConModel posConModel = null;
            // 设置权限归属对象
            if (PermissionConst.ORGANIZE.equals(objectType)) {
                setEntity(new String[]{objectId}, PermissionConst.ORGANIZE, objectList, true);
            }
            if (PermissionConst.POSITION.equals(objectType)) {
                setEntity(new String[]{objectId}, PermissionConst.POSITION, objectList, true);
                PositionEntity info = positionMapper.getInfo(objectId);
                if (Objects.equals(info.getIsCondition(), 1)) {
                    posConModel = JsonUtil.getJsonToBean(info.getConditionJson(), PosConModel.class);
                    posConModel.init();
                }
            }
            if (PermissionConst.ROLE.equals(objectType)) {
                setEntity(new String[]{objectId}, PermissionConst.ROLE, objectList, true);
                RoleEntity info = roleMapper.getInfo(objectId);
                if (Objects.equals(info.getIsCondition(), 1)) {
                    posConModel = JsonUtil.getJsonToBean(info.getConditionJson(), PosConModel.class);
                    posConModel.init();
                }
            }
 
            if (PermissionConst.PERMISSION_GROUP.equals(objectType)) {
                setEntity(new String[]{objectId}, PermissionConst.PERMISSION_GROUP, objectList, true);
            }
 
            List<SystemEntity> sysList = systemApi.getList();
            List<String> mainSysIds = sysList.stream().filter(t -> Objects.equals(t.getIsMain(), 1)).map(SystemEntity::getId).collect(Collectors.toList());
 
            if (form.getModule() != null) {
                List<String> menuList = Arrays.asList(form.getModule());
                List<ModuleEntity> menuEntityList = moduleApi.getModuleByIds(new ModuleApiByIdsModel(menuList));
                Set<String> array = new HashSet<>(menuList);
                //超出权限基数的截取
                if (posConModel != null && posConModel.getNumFlag()) {
                    //移除非菜单数据,用于基数计算
                    List<String> menuIds = menuEntityList.stream().map(ModuleEntity::getId).collect(Collectors.toList());
                    array = menuList.stream().filter(menuIds::contains).collect(Collectors.toSet());
                    List<String> listByObjectId = this.getListByObjectId(objectId, PermissionConst.MODULE).stream().map(AuthorizeEntity::getItemId).collect(Collectors.toList());
                    listByObjectId.removeAll(mainSysIds);
                    if (!listByObjectId.isEmpty() && menuList.size() == listByObjectId.size() && menuList.containsAll(listByObjectId)) {
                        return "";
                    }
 
                    //数据库存储权限实际菜单数量
                    List<String> dbMenuIds = moduleApi.getModuleByIds(new ModuleApiByIdsModel(listByObjectId))
                            .stream().filter(t -> !Objects.equals(t.getType(), 1)).map(ModuleEntity::getId).collect(Collectors.toList());
                    //修改的时候权限包含原来的全部权限-并且原权限已达基数。
                    if (!listByObjectId.isEmpty() && dbMenuIds.size() >= posConModel.getPermissionNum() && menuList.containsAll(dbMenuIds)) {
                        throw new DataException(MsgCode.SYS144.get());
                    }
 
                    //权限基数的时候只算实际菜单
                    List<String> collect = menuEntityList.stream().filter(t -> !Objects.equals(t.getType(), 1)).map(ModuleEntity::getId).collect(Collectors.toList());
                    List<String> collect1 = menuList.stream().filter(collect::contains).collect(Collectors.toList());
                    int num = collect1.size() - posConModel.getPermissionNum();
                    if (num > 0) {
                        errStr = MsgCode.SYS145.get();
                        List<String> newIds = collect1.subList(0, posConModel.getPermissionNum());
                        newIds.addAll(getParentMenu(menuEntityList, new HashSet<>(newIds)));
                        array = new HashSet<>(newIds);
                    }
                }
                Set<String> systemIds = new HashSet<>();
                Set<String> moduleIds = new HashSet<>(array);
                for (ModuleEntity item : menuEntityList) {
                    if (array.contains(item.getId())) {
                        moduleIds.add(item.getSystemId());
                        systemIds.add(item.getSystemId());
                        if (mainSysIds.contains(item.getSystemId())) {
                            moduleIds.add(CodeConst.XTCD);
                        } else {
                            moduleIds.add(CodeConst.YYCD);
                            if (JnpfConst.WEB.equals(item.getCategory())) {
                                moduleIds.add(item.getSystemId() + JnpfConst.WEB);
                            }
                            if (JnpfConst.APP.equals(item.getCategory())) {
                                moduleIds.add(item.getSystemId() + JnpfConst.APP);
                            }
                        }
                    }
                }
                form.setModule(moduleIds.toArray(new String[0]));
                form.setSystemIds(systemIds.toArray(new String[0]));
                setEntity(form.getSystemIds(), AuthorizeConst.SYSTEM, authorizeList, false);
            }
 
            // 设置权限模块
            setEntity(form.getButton(), AuthorizeConst.BUTTON, authorizeList, false);
            setEntity(form.getModule(), AuthorizeConst.MODULE, authorizeList, false);
            setEntity(form.getColumn(), AuthorizeConst.COLUMN, authorizeList, false);
            setEntity(form.getResource(), AuthorizeConst.RESOURCE, authorizeList, false);
            setEntity(form.getForm(), AuthorizeConst.FROM, authorizeList, false);
 
            //删除角色相关信息 移除下级权限
            List<OrganizeEntity> allOrgList = organizeMapper.getList(true);
            List<PositionEntity> allPosList = positionMapper.getList(true);
            List<String> objectIdAll = objectList.stream().map(AuthorizeEntity::getObjectId).collect(Collectors.toList());
            //移除关联子数据
            deleteAllAuth(form, allOrgList, allPosList);
            //移除权限缓存
            this.removeAuthByUserOrMenu(null, Arrays.asList(form.getModule()));
            //移除权限
            String ids = String.join(",", objectIdAll);
            JdbcUtil.creUpDe(new PrepSqlDTO(XSSEscape.escapeEmpty(SqlFrameFastUtil.AUTHOR_DEL.replace("{authorizeIds}", ids))).withConn(dataSourceUtils, null));
 
            //权限变更提示
            List<String> userIds = new ArrayList<>();
            List<String> listIds = new ArrayList<>();
            if (PermissionConst.ORGANIZE.equals(objectType)) {
                List<String> orgIds = allOrgList.stream().filter(t -> t.getOrganizeIdTree().contains(objectId))
                        .map(OrganizeEntity::getId).collect(Collectors.toList());
                List<String> posIds = allPosList.stream().filter(t -> listIds.contains(t.getOrganizeId())).map(PositionEntity::getId).collect(Collectors.toList());
                listIds.addAll(orgIds);
                listIds.addAll(posIds);
            }
            if (PermissionConst.POSITION.equals(objectType)) {
                List<String> positionIds = allPosList.stream().filter(t -> StringUtil.isNotEmpty(t.getPositionIdTree()) && t.getPositionIdTree().contains(objectId))
                        .map(PositionEntity::getId).collect(Collectors.toList());
                listIds.addAll(positionIds);
            }
            if (PermissionConst.ROLE.equals(objectType)) {
                List<RoleRelationEntity> listByRoleId = roleRelationMapper.getListByRoleId(objectId, null);
                for (RoleRelationEntity rre : listByRoleId) {
                    if (PermissionConst.ORGANIZE.equals(rre.getObjectType())) {
                        List<String> orgIds = allOrgList.stream().filter(t -> t.getOrganizeIdTree().contains(rre.getObjectId()))
                                .map(OrganizeEntity::getId).collect(Collectors.toList());
                        List<String> posIds = allPosList.stream().filter(t -> listIds.contains(t.getOrganizeId())).map(PositionEntity::getId).collect(Collectors.toList());
                        listIds.addAll(orgIds);
                        listIds.addAll(posIds);
                    } else if (PermissionConst.POSITION.equals(rre.getObjectType())) {
                        List<String> positionIds = allPosList.stream().filter(t -> t.getPositionIdTree().contains(rre.getObjectId()))
                                .map(PositionEntity::getId).collect(Collectors.toList());
                        listIds.addAll(positionIds);
                    } else {
                        userIds.addAll(listByRoleId.stream().map(RoleRelationEntity::getObjectId).collect(Collectors.toList()));
                    }
                }
            }
            if (!listIds.isEmpty()) {
                List<UserRelationEntity> listByObjectIdAll = userRelationMapper.getListByObjectIdAll(listIds);
                userIds.addAll(listByObjectIdAll.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList()));
            }
 
            // 插入数据
            String sql = DbTypeUtil.checkOracle(dataSourceUtils) || DbTypeUtil.checkPostgre(dataSourceUtils) ?
                    SqlFrameFastUtil.INSERT_AUTHORIZE2 : SqlFrameFastUtil.INSERT_AUTHORIZE;
 
            String columnKey = StringUtils.EMPTY;
            String columnPlceholder = StringUtils.EMPTY;
            String columnValue = TenantDataSourceUtil.getTenantColumn();
            if (StringUtil.isNotEmpty(columnValue)) {
                columnKey = StrPool.COMMA + configValueUtil.getMultiTenantColumn();
                columnPlceholder = ",?";
            }
            sql = sql.replace("%COLUMN_KEY%", columnKey).replace("%COLUMN_PLACEHOLDER%", columnPlceholder);
            PrepSqlDTO dto = new PrepSqlDTO(sql).withConn(dataSourceUtils, null);
            for (int i = 0; i < objectList.size(); i++) {
                for (AuthorizeEntity entityItem : authorizeList) {
                    List<Object> data = new LinkedList<>();
                    data.add(RandomUtil.uuId());
                    data.add(entityItem.getItemType());
                    data.add(entityItem.getItemId());
                    data.add(objectList.get(i).getObjectType());
                    data.add(objectList.get(i).getObjectId());
                    data.add(i);
                    data.add(DateUtil.getNow());
                    data.add(userInfo.getUserId());
                    if (StringUtil.isNotEmpty(columnValue)) {
                        data.add(columnValue);
                    }
                    dto.addMultiData(data);
                }
            }
            JdbcUtil.creUpDeBatchOneSql(dto);
 
            userUtil.delCurUser(MsgCode.PS010.get(), userIds);
        } catch (DataException e1) {
            e1.printStackTrace();
            log.error("权限报错:" + e1.getMessage());
            throw new DataException(e1.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("权限报错:" + e.getMessage());
        }
        return errStr;
    }
 
    private Set<String> getParentMenu(List<ModuleEntity> allMenu, Set<String> childIds) {
        Set<String> newIds = new HashSet<>();
        if (CollUtil.isNotEmpty(childIds)) {
            for (ModuleEntity menu : allMenu) {
                if (childIds.contains(menu.getId()) && !"-1".equals(menu.getParentId())) {
                    newIds.add(menu.getParentId());
                }
            }
            if (CollUtil.isNotEmpty(newIds)) {
                newIds.addAll(getParentMenu(allMenu, newIds));
            }
            newIds.addAll(childIds);
        }
        return newIds;
    }
 
    /**
     * 删除子权限
     *
     * @param form
     * @param allOrgList
     * @param allPosList
     */
    private void deleteAllAuth(AuthorizeDataUpForm form, List<OrganizeEntity> allOrgList, List<PositionEntity> allPosList) {
        List<RoleRelationEntity> roleRealationList = roleRelationMapper.selectList(new QueryWrapper<>());
        List<AuthorizeEntity> allAuthList = this.list(new QueryWrapper<>());
        Map<String, List<AuthorizeEntity>> allAuthMap = allAuthList.stream().collect(Collectors.groupingBy(AuthorizeEntity::getObjectId));
        //表单提交的列表
        List<String> systemSave = form.getSystemIds() == null ? Collections.emptyList() : Arrays.asList(form.getModule());
        List<String> moduleSave = form.getModule() == null ? Collections.emptyList() : Arrays.asList(form.getModule());
        List<String> buttonSave = form.getButton() == null ? Collections.emptyList() : Arrays.asList(form.getButton());
        List<String> columnSave = form.getColumn() == null ? Collections.emptyList() : Arrays.asList(form.getColumn());
        List<String> resourceSave = form.getResource() == null ? Collections.emptyList() : Arrays.asList(form.getResource());
        List<String> formSave = form.getForm() == null ? Collections.emptyList() : Arrays.asList(form.getForm());
 
        //递归获取
        List<String> deleteAllAuth = AuthPermUtil.getDelAllAuth(AuthorizeSaveParam
                .builder().objectId(form.getObjectId()).objectType(form.getObjectType()).allOrgList(allOrgList).allPosList(allPosList).allAuthMap(allAuthMap)
                .roleRealationList(roleRealationList)
                .systemSave(systemSave).moduleSave(moduleSave).buttonSave(buttonSave).columnSave(columnSave).resourceSave(resourceSave).formSave(formSave)
                .build());
        if (CollUtil.isNotEmpty(deleteAllAuth)) {
            QueryWrapper<AuthorizeEntity> qw = new QueryWrapper<>();
            if (deleteAllAuth.size() > 1000) {
                List<List<String>> lists = Lists.partition(deleteAllAuth, 1000);
                for (List<String> list : lists) {
                    qw.lambda().in(AuthorizeEntity::getId, list).or();
                }
            } else {
                qw.lambda().in(AuthorizeEntity::getId, deleteAllAuth);
            }
            this.remove(qw);
        }
    }
 
    /**
     * 权限
     */
    private void setEntity(String[] ids, String type, List<AuthorizeEntity> entityList, boolean objectFlag) {
        if (ids != null) {
            for (String id : ids) {
                AuthorizeEntity entity = new AuthorizeEntity();
                if (objectFlag) {
                    entity.setObjectType(type);
                    entity.setObjectId(id);
                } else {
                    entity.setItemType(type);
                    entity.setItemId(id);
                }
                entityList.add(entity);
            }
        }
    }
 
    @Override
    public List<AuthorizeEntity> getListByUserId(boolean isAdmin, String userId, boolean standingfilter) {
        if (!isAdmin) {
            QueryWrapper<UserRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(UserRelationEntity::getUserId, userId);
            queryWrapper.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.POSITION);
            List<UserRelationEntity> list = userRelationMapper.selectList(queryWrapper);
            List<String> userRelationList = list.stream().map(u -> u.getObjectId()).collect(Collectors.toList());
            userRelationList.add(userId);
            List<String> roleList = roleRelationMapper.getListByObjectId(userRelationList, null)
                    .stream().map(RoleRelationEntity::getRoleId).collect(Collectors.toList());
            userRelationList.addAll(roleList);
 
            //如果开启身份,根据身份过滤部分权限
            List<AuthorizeEntity> listByObjectId = this.getListByObjectId(userRelationList);
            List<AuthorizeEntity> standingList = listByObjectId.stream().filter(t -> PermissionConst.STAND.equals(t.getItemId())).collect(Collectors.toList());
            BaseSystemInfo baseSystemInfo = sysconfigApi.getSysConfigInfo();
            if (standingfilter && Objects.equals(baseSystemInfo.getStandingSwitch(), 1) && !standingList.isEmpty()) {
                UserEntity info = userMapper.getInfo(userId);
                List<AuthorizeEntity> authorizeByItem = this.getAuthorizeByItem(PermissionConst.STAND, info.getStanding());
                List<String> collect = authorizeByItem.stream().map(AuthorizeEntity::getObjectId).collect(Collectors.toList());
                userRelationList = userRelationList.stream().filter(collect::contains).collect(Collectors.toList());
            }
 
            if (CollUtil.isEmpty(userRelationList)) {
                return Collections.emptyList();
            }
            QueryWrapper<AuthorizeEntity> wrapper = new QueryWrapper<>();
            wrapper.lambda().in(AuthorizeEntity::getObjectId, userRelationList);
            return this.list(wrapper);
        } else {
            return Collections.emptyList();
        }
    }
 
    @Override
    public List<AuthorizeEntity> getListByPosOrRoleId(String objectId, String objectType) {
        QueryWrapper<AuthorizeEntity> wrapper = new QueryWrapper<>();
        if (PermissionConst.POSITION.equals(objectType)) {
            List<String> posId = userRelationMapper.getListByObjectId(objectId, objectType).stream().map(u -> u.getObjectId()).collect(Collectors.toList());
            List<String> posRoleList = roleRelationMapper.getListByObjectId(posId, null)
                    .stream().map(RoleRelationEntity::getRoleId).collect(Collectors.toList());
            posId.addAll(posRoleList);
            wrapper.lambda().in(AuthorizeEntity::getObjectId, posId);
        } else {
            wrapper.lambda().eq(AuthorizeEntity::getObjectId, objectId);
            wrapper.lambda().eq(AuthorizeEntity::getObjectType, PermissionConst.ROLE);
        }
        return this.list(wrapper);
    }
 
    @Override
    @DS("")
    public List<SuperJsonModel> getConditionSql(String moduleId, String systemCode) {
        List<SuperJsonModel> list = new ArrayList<>();
        UserInfo userInfo = UserProvider.getUser();
        String reidsKey = cacheKeyUtil.getUserAuthorize() + moduleId + "_" + userInfo.getUserId();
        long time = (long) 60 * 5;
        AuthorizeVO model;
        if (redisUtil.exists(reidsKey)) {
            model = JsonUtil.getJsonToBean(redisUtil.getString(reidsKey).toString(), AuthorizeVO.class);
        } else {
            model = this.getAuthorize(false, systemCode, 0);
            redisUtil.insert(reidsKey, JsonUtil.getObjectToString(model), time);
        }
        if (model == null) {
            return new ArrayList<>();
        }
        List<ResourceModel> resourceListAll = model.getResourceList().stream().filter(m -> m.getModuleId().equals(moduleId)).collect(Collectors.toList());
        //先遍历一次 查找其中有没有全部方案
        boolean isAll = resourceListAll.stream().filter(item -> "jnpf_alldata".equals(item.getEnCode()) || item.getEnCode().startsWith("jnpf_alldata")).count() > 0;
        //未分配权限方案
        if (isAll || Boolean.TRUE.equals(userInfo.getIsAdministrator())) {
            SuperJsonModel superJsonModel = new SuperJsonModel();
            list.add(superJsonModel);
            return list;
        }
        Map<String, List<ResourceModel>> authorizeMap = resourceListAll.stream().filter(t -> StringUtil.isNotEmpty(t.getObjectId())).collect(Collectors.groupingBy(ma -> ma.getObjectId()));
        int num = 0;
        //方案
        for (Map.Entry<String, List<ResourceModel>> entry : authorizeMap.entrySet()) {
            String key = entry.getKey();
            List<ResourceModel> resourceList = authorizeMap.get(key);
            boolean authorizeLogic = num == 0;
            for (ResourceModel item : resourceList) {
                AuthConditionModel authConditionModel = JsonUtil.getJsonToBean(item.getConditionJson(), AuthConditionModel.class);
                String matchLogic = authConditionModel.getMatchLogic();
                List<SuperQueryJsonModel> conditionList = new ArrayList<>();
                //分组
                for (AuthGroup group : authConditionModel.getConditionList()) {
                    String logic = group.getLogic();
                    List<FieLdsModel> groupList = new ArrayList<>();
                    //条件
                    for (AuthItem fieldItem : group.getGroups()) {
 
                        FieLdsModel fieLdsModel = JsonUtil.getJsonToBean(fieldItem, FieLdsModel.class);
                        String itemField = fieldItem.getField();
                        String table = fieldItem.getTableName();
                        String vModel = "";
                        if (itemField.contains("_jnpf_")) {
                            vModel = itemField.split("_jnpf_")[1];
                        } else if (itemField.toLowerCase().startsWith("tablefield")) {
                            vModel = itemField.split("-")[1];
                        } else {
                            vModel = itemField;
                        }
                        ConfigModel config = fieLdsModel.getConfig();
                        String jnpfKey = fieldItem.getJnpfKey();
                        if (AuthorizeConditionEnum.CURRENTTIME.getCondition().equals(jnpfKey)) {
                            jnpfKey = AuthorizeConst.DATE_PICKER;
                        }
                        config.setJnpfKey(jnpfKey);
                        config.setTableName(table);
                        fieLdsModel.setConfig(config);
                        fieLdsModel.setSymbol(fieldItem.getSymbol());
                        fieLdsModel.setVModel(vModel);
                        fieLdsModel.setId(itemField);
                        fieLdsModel.setFieldValue(fieldItem.getFieldValue());
                        groupList.add(fieLdsModel);
                    }
                    //搜索条件
                    SuperQueryJsonModel queryJsonModel = new SuperQueryJsonModel();
                    queryJsonModel.setGroups(groupList);
                    queryJsonModel.setLogic(logic);
                    conditionList.add(queryJsonModel);
                }
                if (!conditionList.isEmpty()) {
                    SuperJsonModel superJsonModel = new SuperJsonModel();
                    superJsonModel.setMatchLogic(matchLogic);
                    superJsonModel.setConditionList(conditionList);
                    superJsonModel.setAuthorizeLogic(authorizeLogic);
                    list.add(superJsonModel);
                }
            }
            num += list.isEmpty() ? 0 : 1;
        }
        return list;
    }
 
    @Override
    public void removeAuthByUserOrMenu(List<String> userIds, List<String> menuIds) {
        userIds = userIds == null ? new ArrayList<>() : userIds;
        menuIds = menuIds == null ? new ArrayList<>() : menuIds;
        if (!userIds.isEmpty() || !menuIds.isEmpty()) {
            Set<String> deleteKeys = new HashSet<>();
            Set<String> userAuthorizeKeys = redisUtil.findKeysContaining(cacheKeyUtil.getUserAuthorize() + "*");
            for (String cacheKey : userAuthorizeKeys) {
                boolean isMatch = !menuIds.isEmpty() && cacheKey.startsWith(cacheKeyUtil.getUserAuthorize() + "menu:");
                for (String user : userIds) {
                    if (cacheKey.contains(user)) {
                        isMatch = true;
                        break;
                    }
                }
                if (!isMatch) {
                    for (String menuId : menuIds) {
                        if (cacheKey.contains(menuId)) {
                            isMatch = true;
                            break;
                        }
                    }
                }
                if (isMatch) {
                    deleteKeys.add(cacheKey);
                }
            }
            if (!deleteKeys.isEmpty()) {
                redisUtil.remove(deleteKeys);
            }
        }
    }
 
    @Override
    public List<AuthorizeEntity> getListByObjectId(List<String> objectId) {
        return this.baseMapper.getListByObjectId(objectId);
    }
 
    @Override
    public List<AuthorizeEntity> getListByRoleId(String roleId) {
        return this.baseMapper.getListByRoleId(roleId);
    }
 
    @Override
    public List<AuthorizeEntity> getListByObjectId(String objectId, String itemType) {
        return this.baseMapper.getListByObjectId(objectId, itemType);
    }
 
    @Override
    public List<AuthorizeEntity> getListByObjectAndItem(String itemId, String objectType) {
        return this.baseMapper.getListByObjectAndItem(itemId, objectType);
    }
 
    @Override
    public List<AuthorizeEntity> getListByObjectAndItemIdAndType(String itemId, String itemType) {
        return this.baseMapper.getListByObjectAndItemIdAndType(itemId, itemType);
    }
 
    @Override
    @DSTransactional
    public void saveObjectAuth(SavePortalAuthModel portalAuthModel) {
        this.baseMapper.saveObjectAuth(portalAuthModel);
    }
 
    @Override
    public List<AuthorizeEntity> getAuthorizeByItem(String itemType, String itemId) {
        return this.baseMapper.getAuthorizeByItem(itemType, itemId);
    }
 
    @Override
    public List<AuthorizeEntity> getListByRoleIdsAndItemType(List<String> roleIds, String itemType) {
        return this.baseMapper.getListByRoleIdsAndItemType(roleIds, itemType);
    }
 
    @Override
    public void setPermissionGroup(String objectId, String objectType) {
        if (PermissionConst.PERMISSION_GROUP.equals(objectType)) {
            PermissionGroupEntity info = permissionGroupService.info(objectId);
            if (info != null && StringUtil.isNotEmpty(info.getPermissionMember())) {
                String[] split = info.getPermissionMember().split(",");
                //根据ids获取上级,赋予新的权限
                List<String> userIdList = permissionGroupService.setAuthByIds(objectId, Arrays.asList(split));
                //岗位组织获取用户刷新权限
                userUtil.delCurUser(null, userIdList);
                //移除权限缓存
                this.removeAuthByUserOrMenu(userIdList, null);
            }
        }
    }
}