shichongfu
2023-04-25 ce0b49552668d3331055e2b1a1447a743dc54939
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
package com.product.admin.service;
 
import cn.hutool.core.util.IdUtil;
import com.beust.jcommander.internal.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.product.admin.config.CmnConst;
import com.product.admin.config.SystemCode;
import com.product.admin.service.idel.IRolesService;
import com.product.core.cache.DataPoolCacheImpl;
import com.product.core.dao.BaseDao;
import com.product.core.entity.DataTableEntity;
import com.product.core.entity.FieldSetEntity;
import com.product.core.exception.BaseException;
import com.product.core.permission.PermissionService;
import com.product.core.service.support.AbstractBaseService;
import com.product.core.service.support.QueryFilterService;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.core.transfer.Transactional;
import com.product.module.sys.entity.SystemUser;
import com.product.util.BaseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.util.*;
 
 
/**
 * Copyright LX-BASE
 *
 * @Title: RolesService
 * @Project: LX-BASE-SERVER
 * @Date: 2020年6月3日 下午4:40:01
 * @Author: 郑盟
 * @Description: 创建角色权限
 */
@Component
public class RolesService extends AbstractBaseService implements IRolesService {
    @Autowired
    private BaseDao baseDao;
 
    @Autowired
    PermissionService permissionService;
    @Autowired
    public QueryFilterService queryFilterService;
 
    @Autowired
    private UpdateLoginUserInfoService updateLoginUserInfoService;
 
    @Autowired
    public SystemMenusService systemMenusService;
 
    /**
     * 创建权限如果要添加功能许可请将product_sys_function_permission作为FieldSetEntity 子表
     */
    @Transactional
    public String addRole(FieldSetEntity fs) throws BaseException {
        DataTableEntity subDataTable = fs.getSubDataTable(CmnConst.PRODUCT_SYS_FUNCTION_PERMISSION);
        fs.setValue(CmnConst.CREATED_BY, SpringMVCContextHolder.getCurrentUser().getUser_id());
        fs.setValue(CmnConst.CREATED_UTC_DATETIME, new Date());
        fs.setValue(CmnConst.ORG_LEVEL_UUID, SpringMVCContextHolder.getCurrentUser().getOrg_level_uuid());
        String effective_start_date = fs.getString("effective_start_date");
        /*
         * //罗鑫2021年3月1日 开始时间不能大于结束时间 if(BaseUtil.strIsNull(effective_start_date)){
         * throw new BaseException(SystemCode.SYSTEM_VALID_TIME_WE_FAIL.getValue(),
         * SystemCode.SYSTEM_VALID_TIME_WE_FAIL.getText(),this.getClass()
         * ,"public String addRole(FieldSetEntity fs) throws BaseException"); }
         */
        String effective_end_date = fs.getString("effective_end_date");
        if (!BaseUtil.strIsNull(effective_end_date)) {
            if (BaseUtil.temporalComparison(effective_start_date, effective_end_date)) {
                throw new BaseException(SystemCode.SYSTEM_VALID_TIME_FAIL.getValue(), SystemCode.SYSTEM_VALID_TIME_FAIL.getText(), this.getClass(), "public String addRole(FieldSetEntity fs) throws BaseException");
            }
        }
        String roleUUID = baseDao.add(fs, false);
        if (roleUUID != null && subDataTable != null) {
            for (int i = 0; i < subDataTable.getRows(); i++) {
                subDataTable.setFieldValue(i, CmnConst.ROLE_UUID, roleUUID);
                subDataTable.setFieldValue(i, CmnConst.CREATED_BY,
                        SpringMVCContextHolder.getCurrentUser().getUser_id());
                subDataTable.setFieldValue(i, CmnConst.CREATED_UTC_DATETIME, new Date());
            }
            boolean add = baseDao.add(subDataTable);
        }
        return roleUUID;
    }
 
    /**
     * 系统管理员详情
     */
    public FieldSetEntity findRole(FieldSetEntity fs) throws BaseException {
        String uuid = fs.getString("uuid");
        // 郑盟 2020年12月17日 下午14:05
        if (StringUtils.isEmpty(uuid))
            return null;
        FieldSetEntity roleFs = baseDao.getFieldSetEntity("product_sys_role", uuid, true);
        baseDao.listInternationDataTable(roleFs, null);
        DataTableEntity listTable = baseDao.listTable("product_sys_staffs", "role_uuids like '%" + uuid + "%'");
        roleFs.setValue("userNum", listTable.getRows());
        return roleFs;
    }
 
    /**
     * 系统管理员列表
     */
    public DataTableEntity listRole(FieldSetEntity fse) throws BaseException {
        String queryFilter = "";
        if (!BaseUtil.dataTableIsEmpty(fse.getSubDataTable("systemSeniorQueryString"))) {
            queryFilter = queryFilterService.getQueryFilter(fse);
        }
        String dataFilter = permissionService.getDataFilter("c." + CmnConst.ORG_LEVEL_UUID);
        if (!StringUtils.isEmpty(dataFilter)) {
            if (!StringUtils.isEmpty(queryFilter)) {
                queryFilter = " and " + queryFilter;
            }
            dataFilter = " WHERE " + dataFilter + queryFilter;
        } else {
            dataFilter = "";
            String manager_type = returnManagerType();
            if ("1".equals(manager_type)) {
                dataFilter = " WHERE c.org_level_uuid='00000000-0000-0000-0000-000000000000'";
                if (!StringUtils.isEmpty(queryFilter)) {
                    queryFilter = " and " + queryFilter;
                }
            } else {
                if (!StringUtils.isEmpty(queryFilter)) {
                    queryFilter = " where " + queryFilter;
                }
            }
        }
        return roleDt(dataFilter, queryFilter, fse);
    }
 
    private String returnManagerType() {
        SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
        String manager_type = null;
        if (currentUser != null && currentUser.getCurrentManager() != null) {
            manager_type = currentUser.getCurrentManager().getString(CmnConst.MANAGER_TYPE);
        }
        return manager_type;
    }
 
    private DataTableEntity roleDt(String dataFilter, String queryFilter, FieldSetEntity fse) {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT ");
        sql.append(" c.*, ");
        sql.append(" ( ");
        sql.append(" (select count(*) num ");
        sql.append(" from product_sys_staffs  f ");
        sql.append(" where  concat(',',role_uuids,',') like concat('%,',c.uuid,',%')) ");
        sql.append(" + ");
        sql.append(" (select count(*) num ");
        sql.append(" from product_sys_org_manager ");
        sql.append(" where concat(',',role_uuids,',') like concat('%,',c.uuid,',%')) ");
        sql.append(" )userNum ");
        sql.append(" FROM product_sys_role c ");
        sql.append(dataFilter).append(queryFilter);
        // 只有超级管理员才能看到 管理员所有的角色 cheng 2021年12月22日17:11:59
        if (1 == SpringMVCContextHolder.getCurrentUser().getUserType()) {
            sql.append(" and uuid in ");
        } else {
            sql.append(" and uuid not in ");
        }
        sql.append("('175b7de5-0d13-45f9-ba10-eaec67b73f90-notchange','a8e2a6ac-a507-47da-851b-9ac61541cd5a-notchange','bb3d5d27-8c05-49c1-bdb2-c743a53863e0-notchange','eabb00f3-2118-4165-967b-a7d88f472f67-notchange')");
        sql.append(" ORDER BY c.sequence ASC ");
        DataTableEntity roleDt = baseDao.listInternationDataTable(
                baseDao.listTable(sql.toString(), new Object[]{}, fse.getInteger("pagesize"), fse.getInteger("cpage")),
                null);
        baseDao.loadPromptData(roleDt);
        return roleDt;
    }
 
    @Autowired
    RouterService routerService;
 
    public void updateRoleCache() {
        DataPoolCacheImpl.getInstance().cacheDataByTable("product_sys_page_button_v");
        DataPoolCacheImpl.getInstance().cacheDataByTable("product_sys_function_buttons");
        routerService.refreshRouter();
    }
 
 
    /**
     * 更新角色权限
     */
    @Transactional
    public boolean updateRole(FieldSetEntity fs) throws BaseException {
        DataTableEntity subDataTable = fs.getSubDataTable("product_sys_function_permission");
        Map<String, DataTableEntity> subData = fs.getSubData();
        subData.remove("product_sys_function_permission");
        fs.setSubData(subData);
        fs.setValue(CmnConst.UPDATED_BY, SpringMVCContextHolder.getCurrentUser().getUser_id());
        fs.setValue(CmnConst.UPDATED_UTC_DATETIME, new Date());
        String effective_start_date = fs.getString("effective_start_date");
        //罗鑫2021年3月1日 开始时间不能大于结束时间
        if (BaseUtil.strIsNull(effective_start_date)) {
            throw new BaseException(SystemCode.SYSTEM_VALID_TIME_WE_FAIL.getValue(), SystemCode.SYSTEM_VALID_TIME_WE_FAIL.getText(), this.getClass(), "public boolean updateRole(FieldSetEntity fs) throws BaseException");
        }
        if (StringUtils.isEmpty(fs.getString("effective_end_date"))) {
            fs.remove("effective_end_date");
        } else {
            String effective_end_date = fs.getString("effective_end_date");
            if (BaseUtil.temporalComparison(effective_start_date, effective_end_date)) {
                throw new BaseException(SystemCode.SYSTEM_VALID_TIME_FAIL.getValue(), SystemCode.SYSTEM_VALID_TIME_FAIL.getText(), this.getClass(), "public boolean updateRole(FieldSetEntity fs) throws BaseException");
            }
        }
        if (StringUtils.isEmpty(fs.getString("effective_start_date"))) {
            fs.remove("effective_start_date");
        }
        boolean update = baseDao.update(fs);
        if (update && subDataTable != null) {
            for (int i = 0; i < subDataTable.getRows(); i++) {
                subDataTable.setFieldValue(i, CmnConst.ROLE_UUID, fs.getString("uuid"));
                subDataTable.setFieldValue(i, CmnConst.CREATED_BY,
                        SpringMVCContextHolder.getCurrentUser().getUser_id());
                subDataTable.setFieldValue(i, CmnConst.CREATED_UTC_DATETIME, new Date());
                // 杜洪波 updatetime 2020年12月8日15时23分 移除uuid,防止新增变修改
                subDataTable.getFieldSetEntity(i).remove(CmnConst.UUID);
            }
            boolean updatePermission = updatePermission(subDataTable);
            // xupengcheng updateTime 2020年11月28日14:10:13 更新使用该角色菜单
            updateLoginUserInfoService.updateUserInfoByUpdateRole(new String[]{fs.getUUID()}, false);
            return updatePermission;
        } else if (subDataTable == null) {
            baseDao.delete("product_sys_function_permission", "role_uuid=?", new String[]{fs.getString("uuid")});
            return update;
        } else {
            return update;
        }
    }
 
    /**
     * 更新关联role 的功能许可
     */
    public boolean updatePermission(DataTableEntity dt) throws BaseException {
        // 郑盟 2020年12月17日 下午14:05
        if (!StringUtils.isEmpty(dt.getString(0, CmnConst.ROLE_UUID))) {
            boolean delete = baseDao.delete("product_sys_function_permission", "role_uuid=?",
                    new String[]{dt.getString(0, CmnConst.ROLE_UUID)});
            if (!delete)
                return false;
            return baseDao.add(dt);
        }
        return false;
    }
 
    /**
     * 更新关联role 的功能许可
     */
    @Transactional
    public boolean delectRole(String uuid) throws BaseException {
        boolean delete = baseDao.delete(CmnConst.PRODUCT_SYS_ROLE, "uuid=?", new String[]{uuid});
        // xupengcheng updateTime 2020年11月28日14:10:13 更新使用该角色菜单
        updateLoginUserInfoService.updateUserInfoByUpdateRole(new String[]{uuid}, true);
        return delete;
    }
 
    /**
     * 超级管理员创建 角色 || 超级管理员创建客户 根据需求封装 产品、模块、功能、按钮 子父级关系 type 0 产品、模块、功能、按钮 1
     * 产品、模块、功能 2 产品、模块
     * <p>
     * funtype 1、业务功能 2、系统功能 3、所有功能
     */
    public DataTableEntity listFunctionRoleForClients(int type, String role_uuids) throws BaseException {
        SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
        String manager_type = null;
        if (currentUser != null && currentUser.getCurrentManager() != null) {
            manager_type = currentUser.getCurrentManager().getString("manager_type");
        }
        String roles = returnRoles(role_uuids);
        String[] roles_arr = roles.split(",");
        //不是超级管理员 并且 不是系统管理员则 开启 权限获取数据 否则获取 所有 数据
        boolean accessControl = !"1".equals(manager_type) && !"4".equals(manager_type);
        if (type == 2) {
            //产品、模块
            DataTableEntity data = getData(2);
            return treeProduct(data);
        } else if (type == 1) {
            //产品、模块、功能
            DataTableEntity data = getFunctionPermissionByRole(roles_arr, null, false, accessControl);
            return getTree(treeModule(data), 2);
        } else if (type == 0) {
            DataTableEntity data = getFunctionPermissionByRole(roles_arr, null, true, accessControl);
            return getTree(treeModule(data), 2);
        }
        return new DataTableEntity();
    }
 
    /**
     * 单位管理员或隐藏管理员创建 角色 根据需求封装 产品、模块、功能、按钮 子父级关系 type 0 产品、模块、功能、按钮 1 产品、模块、功能 2
     * 产品、模块
     * <p>
     * funtype 1、业务功能 2、系统功能 3、所有功能
     */
    public DataTableEntity listFunctionRole(int type, String role_uuids, int funtype) throws BaseException {
        SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
        String manager_type = null;
        if (currentUser != null && currentUser.getCurrentManager() != null) {
            manager_type = currentUser.getCurrentManager().getString("manager_type");
        }
        String roles = returnRoles(role_uuids);
        boolean accessControl = !"1".equals(manager_type) && !"4".equals(manager_type);
        if (type == 2) {
            //产品、模块
            DataTableEntity data = getData(2);
            return treeProduct(data);
        } else if (type == 1) {
            //产品、模块、功能
            DataTableEntity data = getFunctionPermissionByRole(roles.split(","), !accessControl ? String.valueOf(funtype) : "", false, accessControl);
            return getTree(treeModule(data), 2);
        } else if (type == 0) {
            DataTableEntity data = getFunctionPermissionByRole(roles.split(","), !accessControl ? String.valueOf(funtype) : "", true, accessControl);
            return getTree(treeModule(data), 2);
        }
 
        return null;
    }
 
 
    /**
     * 33 根据角色查找功能
     *
     * @return 返回 function_uuid , button_uuid, role_uuid ,org_level_uuid ,uuid
     * @throws BaseException
     */
    public DataTableEntity functionsByRoleUuid(String role_uuids) throws BaseException {
        String[] role_uuids_arr = role_uuids.split(",");
        String sql = "select  function_uuid , button_uuid, role_uuid,uuid from product_sys_function_permission where "
                + BaseUtil.buildQuestionMarkFilter("role_uuid", role_uuids_arr.length, true) + "";
        return baseDao.listTable(sql, role_uuids_arr);
    }
 
    /**
     * 根据用户uuid 查询角色功能
     *
     * @param user
     * @return 返回 function_uuid , button_uuid, role_uuid ,org_level_uuid ,uuid
     * @throws BaseException
     */
    public DataTableEntity functionsByUser(SystemUser user) throws BaseException {
        if (user.getCurrentStaff() != null) {
            return functionsByRoleUuid(user.getCurrentStaff().getString("role_uuids"));
        } else if (user.getCurrentManager() != null) {
            String role_uuid = user.getCurrentManager().getString("role_uuids");
            return functionsByRoleUuid(role_uuid);
        } else {
            return null;
        }
    }
 
 
    private String returnRoles(String role_uuids) {
        SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
        String roles = null;
        if (StringUtils.isEmpty(role_uuids)) {
            if (currentUser != null && currentUser.getCurrentManager() != null) {
                roles = currentUser.getCurrentManager().getString("role_uuids");
            } else {
                throw new BaseException(SystemCode.SYSTEM_NOTOBTAINEDROLE_FAIL.getValue(),
                        SystemCode.SYSTEM_NOTOBTAINEDROLE_FAIL.getText(), this.getClass(), "listFunctionRole");
            }
        } else {
            roles = role_uuids;
        }
        return roles;
    }
 
 
    /**
     * 系统管理员创建客户 || 单位管理员或隐藏管理员创建单位角色时的功能权限过滤 客户 单位管理员 或 隐藏管理员才会有 ,系统管理员为空
     */
    public DataTableEntity listFunctionRoleForClients(String role_uuid, String client_role_uuid, boolean isButton)
            throws BaseException {
        String functionType = getFunctionType(role_uuid, client_role_uuid);
        if (StringUtils.isEmpty(role_uuid) && StringUtils.isEmpty(client_role_uuid) && !SpringMVCContextHolder.getCurrentUser().isManager()) {
            return new DataTableEntity();
        }
        //luoxin  去掉客户限制
        else {
            if (!StringUtils.isEmpty(client_role_uuid)) {
                // 超级管理员所在客户的 角色(虚拟)角色表中没有此条数据
                if (1 == SpringMVCContextHolder.getCurrentUser().getUserType()) {
                    role_uuid = "";
                } else {
                    // 去除客户权限设定 cheng  2022年3月1日10:43:53
//                    role_uuid = client_role_uuid;
                }
            }
        }
        if (role_uuid == null) {
            role_uuid = "";
        }
 
        DataTableEntity functionPermissionByRole = getFunctionPermissionByRole(role_uuid.split(","), functionType, isButton, !StringUtils.isEmpty(role_uuid));
        DataTableEntity tree = getTree(getTree(functionPermissionByRole, 1), 2);
        return tree;
    }
 
    /**
     * 获取对应角色的功能类型
     *
     * @param role_uuid
     * @param client_role_uuid
     * @return
     */
    private String getFunctionType(String role_uuid, String client_role_uuid) {
        SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
        if (currentUser.getCurrentManager() != null) {
            if (currentUser.getCurrentManager().getString("manager_type") != null
                    && currentUser.getCurrentManager().getInteger("manager_type") == 2 // 单位管理员
                    || currentUser.getCurrentManager().getInteger("manager_type") == 3)// 隐藏管理员
            {
                return "1,5";
            } else if (currentUser.getCurrentManager().getInteger("manager_type") == 4) {
                // 系统管理员,创建客户时,只显示
                // 业务功能和业务后台功能
                return "1,5";
            } else {
                if (!StringUtils.isEmpty(role_uuid)) {
                    // 超级管理员,修改管理员角色,加载管理功能 2=系统管理功能、3=系统功能、4=客户后台功能
                    String functon_type = "2,3,4";
                    if (StringUtils.equalsAny(role_uuid, "bb3d5d27-8c05-49c1-bdb2-c743a53863e0-notchange", "eabb00f3-2118-4165-967b-a7d88f472f67-notchange", "a8e2a6ac-a507-47da-851b-9ac61541cd5a-notchange")) {
                        functon_type += ",5";
                    }
                    return functon_type;
                } else if (!StringUtils.isEmpty(client_role_uuid)) {
                    // 查看客户的功能权限,只显示业务功能
                    return "1,5";
                } else {
                    // 超级管理员,查看全部功能模块
                    return "";
                }
            }
        }
        return null;
    }
 
    /**
     * 系统管理员创建客户 || 单位管理员或隐藏管理员创建单位角色时的功能权限过滤 客户 单位管理员 或 隐藏管理员才会有 ,系统管理员为空
     */
    public DataTableEntity listFunctionRoleForClients() throws BaseException {
        return listFunctionRoleForClients(null, null, true);
    }
 
 
    /**
     * 获取数据
     *
     * @param type 1 = 产品  2 = 模块 3 = 功能
     * @return
     */
    private DataTableEntity getData(int type) {
        if (1 == type) {
            return baseDao.listTable(CmnConst.PRODUCT_SYS_PRODUCTS);
        } else if (2 == type) {
            DataTableEntity dt = DataPoolCacheImpl.getInstance().getCacheData("所有模块按编码分组");
            if (!BaseUtil.dataTableIsEmpty(dt)) {
                return dt.clones();
            }
        } else if (3 == type) {
            DataTableEntity dt = DataPoolCacheImpl.getInstance().getCacheData("所有功能");
            if (!BaseUtil.dataTableIsEmpty(dt)) {
 
                return dt.clones();
            }
        }
        return null;
    }
 
 
    private DataTableEntity getFunctionPermissionByRole(String[] roleUuids, String functionType, boolean isButton, boolean accessControl) {
        //返回的功能结果集
        DataTableEntity functionResult = new DataTableEntity();
        DataPoolCacheImpl dataPoolCache = DataPoolCacheImpl.getInstance();
        Map<String, Set<String>> permissionMap = Maps.newHashMap();
        List<FieldSetEntity> functionList = Lists.newArrayList();
        if (accessControl) {
            if (roleUuids == null) {
                return functionResult;
            }
            for (int i = 0; i < roleUuids.length; i++) {
                String roleUuid = roleUuids[i];
                //根据角色获取对应权限
                DataTableEntity dt = dataPoolCache.getCacheData("功能权限按角色分组", new String[]{roleUuid});
                if (!BaseUtil.dataTableIsEmpty(dt)) {
                    functionList.addAll(dt.getData());
                }
            }
            for (int i = 0; i < functionList.size(); i++) {
                FieldSetEntity fs = functionList.get(i);
                if (fs == null) {
                    continue;
                }
                //功能uuid
                String function_uuid = fs.getString(CmnConst.FUNCTION_UUID);
                //按钮uuid
                String button_uuid = fs.getString(CmnConst.BUTTON_UUID);
                if (StringUtils.isEmpty(button_uuid)) {
                    continue;
                }
                Set<String> buttonUuids = permissionMap.get(function_uuid);
                if (buttonUuids == null) {
                    buttonUuids = Sets.newHashSet();
                    permissionMap.put(function_uuid, buttonUuids);
                }
                if (isButton) {
                    //将按钮uuid放入集合中
                    buttonUuids.addAll(Arrays.asList(button_uuid.split(",")));
                }
            }
            //遍历有权限的功能
            permissionMap.forEach((k, v) -> {
                //根据功能uuid获取功能详情
                DataTableEntity functionDataTable = dataPoolCache.getCacheData("所有功能", new String[]{k});
                if (!BaseUtil.dataTableIsEmpty(functionDataTable)) {
                    FieldSetEntity functionFieldSet = functionDataTable.getFieldSetEntity(0);
                    String function_type = functionFieldSet.getString("function_type_uuid");
                    if (!StringUtils.isEmpty(functionType) && ("," + functionType + ",").indexOf("," + function_type + ",") < 0) {
                        //功能类型过滤
                        return;
                    }
                    //根据功能uuid获取所有按钮
                    DataTableEntity buttonDataTable = dataPoolCache.getCacheData("所有按钮按功能分组", new String[]{k});
                    functionDataTable = functionDataTable.clones();
                    dataProcessing(functionDataTable, null);
                    List<FieldSetEntity> buttons = Lists.newArrayList();
 
                    if (!BaseUtil.dataTableIsEmpty(buttonDataTable)) {
                        if (accessControl) {
                            List<FieldSetEntity> finalButtons = buttons;
                            v.forEach(buttonUuid -> {
                                //遍历有权限的功能按钮集合 根据功能uuid取出功能详情
                                List<FieldSetEntity> fieldSetEntity = buttonDataTable.getFieldSetEntity(buttonUuid);
                                if (fieldSetEntity != null && fieldSetEntity.get(0) != null) {
                                    finalButtons.add(fieldSetEntity.get(0).clones());
                                }
                            });
                        } else {
                            buttons.addAll(buttonDataTable.getData());
                        }
                    }
                    if (!buttons.isEmpty()) {
                        DataTableEntity templateData = new DataTableEntity();
                        templateData.setData(buttons);
 
                        dataProcessing(templateData, null);
                        //按钮排序
                        buttons.sort((a, b) -> {
                            if (a == null || b == null || StringUtils.isEmpty(a.getString(CmnConst.SEQUENCE)) || StringUtils.isEmpty(b.getString(CmnConst.SEQUENCE))) {
                                return -1;
                            }
 
                            return a.getString(CmnConst.SEQUENCE).compareTo(b.getString(CmnConst.SEQUENCE));
                        });
                        List<FieldSetEntity> fieldSetEntities = new ArrayList<>();
                        FieldSetEntity clientType = new FieldSetEntity();
                        clientType.setTableName("client_type");
                        clientType.setValue("names", "Web");
                        clientType.setValue("type", 5);
                        clientType.setValue("icon", "el-icon-monitor");
                        clientType.setValue("uuid", IdUtil.randomUUID() + "_Web");
                        fieldSetEntities.add(clientType);
                        clientType = clientType.clones();
                        clientType.setValue("uuid", IdUtil.randomUUID() + "_App");
                        clientType.setValue("icon", "el-icon-mobile");
                        clientType.setValue("names", "App");
                        fieldSetEntities.add(clientType);
                        buttons.forEach(f -> {
                            FieldSetEntity fieldSetEntity = fieldSetEntities.get(0);
                            DataTableEntity sub = fieldSetEntities.get("App".equals(f.getString("client_type_uuid")) ? 1 : 0).getSubDataTable(f.getTableName());
                            boolean isAdd = false;
                            if (sub == null) {
                                sub = new DataTableEntity();
                                isAdd = true;
                            }
                            sub.addFieldSetEntity(f);
                            if (isAdd) {
                                fieldSetEntity.addSubDataTable(sub);
                            }
                        });
                        buttons = fieldSetEntities;
                    }
 
                    //克隆功能缓存对象 避免脏数据
                    functionFieldSet = functionFieldSet.clones();
                    if (isButton) {
                        DataTableEntity buttonResult = new DataTableEntity();
                        buttonResult.setData(buttons);
                        Map<String, DataTableEntity> subData = functionFieldSet.getSubData();
                        if (subData == null) {
                            subData = new TreeMap<>();
                            functionFieldSet.setSubData(subData);
                        }
                        subData.put(this.childrenKey, buttonResult);
                    }
                    functionResult.addFieldSetEntity(functionFieldSet);
 
                }
            });
 
        } else {
            //所有功能
            DataTableEntity data = getData(3);
            if (!BaseUtil.dataTableIsEmpty(data)) {
                dataProcessing(data, null);
                for (int i = 0; i < data.getRows(); i++) {
                    FieldSetEntity fs = data.getFieldSetEntity(i);
                    String function_type = fs.getString("function_type_uuid");
                    if (!StringUtils.isEmpty(functionType) && ("," + functionType + ",").indexOf("," + function_type + ",") < 0) {
                        //功能类型过滤
                        data.removeFieldSetEntity(i);
                        i--;
                        continue;
                    }
                    DataTableEntity buttonDataTable = dataPoolCache.getCacheData("所有按钮按功能分组", new String[]{fs.getUUID()});
                    if (BaseUtil.dataTableIsEmpty(buttonDataTable)) {
                        // 没有找到功能按钮 防止功能下按钮为空时 空指针异常
                        data.removeFieldSetEntity(i);
                        i--;
                        continue;
                    }
                    buttonDataTable = buttonDataTable.clones();
                    dataProcessing(buttonDataTable, null);
                    List<FieldSetEntity> fieldSetEntities = new ArrayList<>();
                    FieldSetEntity clientType = new FieldSetEntity();
                    clientType.setTableName(this.childrenKey);
                    clientType.setValue("names", "Web");
                    clientType.setValue("type", 5);
                    clientType.setValue("uuid", IdUtil.randomUUID() + "_Web");
                    clientType.setValue("icon", "el-icon-monitor");
                    fieldSetEntities.add(clientType);
                    clientType = clientType.clones();
                    clientType.setValue("uuid", IdUtil.randomUUID() + "_App");
                    clientType.setValue("icon", "el-icon-mobile");
                    clientType.setValue("names", "App");
                    fieldSetEntities.add(clientType);
                    buttonDataTable.getData().forEach(f -> {
                        int index = "App".equals(f.getString("client_type_uuid")) ? 1 : 0;
                        FieldSetEntity fieldSetEntity = fieldSetEntities.get(index);
                        DataTableEntity sub = fieldSetEntity.getSubDataTable(this.childrenKey);
                        boolean isAdd = false;
                        if (sub == null) {
                            sub = new DataTableEntity();
                            isAdd = true;
                        }
                        sub.addFieldSetEntity(f);
                        if (isAdd) {
                            Map<String, DataTableEntity> subData = fieldSetEntity.getSubData();
                            if (subData == null) {
                                subData = new HashMap<>();
                            }
                            subData.put(this.childrenKey, sub);
                            fieldSetEntity.setSubData(subData);
                        }
                    });
                    Map<String, DataTableEntity> subData = fs.getSubData();
                    if (subData == null) {
                        subData = new TreeMap<>();
                        fs.setSubData(subData);
                    }
                    buttonDataTable = new DataTableEntity();
                    for (FieldSetEntity fieldSetEntity : fieldSetEntities) {
                        buttonDataTable.addFieldSetEntity(fieldSetEntity);
                    }
                    if (buttonDataTable.getRows() >= 1 && (buttonDataTable.getFieldSetEntity(0).getSubData() == null || buttonDataTable.getFieldSetEntity(0).getSubData().isEmpty())) {
                        buttonDataTable.removeFieldSetEntity(0);
                    }
                    if (buttonDataTable.getRows() >= 2 && (buttonDataTable.getFieldSetEntity(1).getSubData() == null || buttonDataTable.getFieldSetEntity(1).getSubData().isEmpty())) {
                        buttonDataTable.removeFieldSetEntity(1);
                    }
 
                    if (buttonDataTable != null && buttonDataTable.getRows() > 0) {
                        subData.put(this.childrenKey, buttonDataTable);
                    }
                }
            }
            functionResult.setData(data.getData());
        }
        if (functionResult.getData() != null && !functionResult.getData().isEmpty()) {
            //功能排序
            functionResult.getData().sort((a, b) -> {
                if (a == null || b == null) {
                    return -1;
                }
                return a.getString(CmnConst.TRICODE).compareTo(b.getString(CmnConst.TRICODE));
            });
        }
        return functionResult;
    }
 
    public DataTableEntity getModuleFunctions() {
        return getTree(getData(3), 1);
    }
 
    /**
     * 获取树形数据
     *
     * @param data 数据
     * @param type 0 = 按钮 1 = 功能 2=模块
     * @return
     */
    private DataTableEntity getTree(DataTableEntity data, int type) {
        Map<String, FieldSetEntity> result = Maps.newHashMap();
        if (2 == type) {
            //模块找产品
            return treeProduct(data);
        } else if (1 == type) {
            //功能找模块
            return treeModule(data);
        }
 
        return null;
    }
 
    private final String childrenKey = "sub";
 
    private DataTableEntity treeModule(DataTableEntity data) {
//        getFunctionPermissionByRole(SpringMVCContextHolder.getCurrentUser().getRoles().split(","));
        // data = 功能数据
        DataTableEntity modules = getData(2);
 
        //模块map 模块code作为key
        Map<String, FieldSetEntity> codeModuleMap = Maps.newLinkedHashMap();
        dataProcessing(modules, codeModuleMap);
 
        //功能map 功能code作为key
        Map<String, FieldSetEntity> codeFunctionMap = Maps.newLinkedHashMap();
        dataProcessing(data, codeFunctionMap);
        Map<String, FieldSetEntity> tempMap = Maps.newHashMap();
        Set<String> codeSet = Sets.newHashSet();
        codeFunctionMap.forEach((tricode, v) -> {
            String parentCode = v.getString(CmnConst.TRICODE_PARENT);
            FieldSetEntity value = v;
 
            while (parentCode != null && parentCode.indexOf('-') > -1) {
                //上级
                FieldSetEntity parentFieldSet = codeModuleMap.get(parentCode);
                if (parentFieldSet != null) {
                    Map<String, DataTableEntity> subData = parentFieldSet.getSubData();
                    if (subData == null) {
                        subData = new TreeMap<>();
                        parentFieldSet.setSubData(subData);
                    }
                    DataTableEntity subDataTable = parentFieldSet.getSubDataTable(this.childrenKey);
                    if (subDataTable == null) {
                        subDataTable = new DataTableEntity();
                    }
                    subDataTable.addFieldSetEntity(value);
                    subData.put(this.childrenKey, subDataTable);
                    parentCode = parentFieldSet.getString(CmnConst.TRICODE_PARENT);
                    if (codeSet.contains(parentFieldSet.getString(CmnConst.TRICODE))) {
                        break;
                    }
                    if (parentCode != null && parentCode.indexOf('-') > -1) {
                        codeSet.add(parentFieldSet.getString(CmnConst.TRICODE));
                    }
                    value = parentFieldSet;
 
                } else {
                    FieldSetEntity fs = tempMap.get(parentCode);
                    if (fs != null) {
                        DataTableEntity subDataTable = fs.getSubDataTable(this.childrenKey);
                        subDataTable.addFieldSetEntity(fs);
                    }
                    parentCode = null;
                }
            }
        });
        DataTableEntity result = new DataTableEntity();
        codeModuleMap.values().forEach(v -> {
            String tricode = v.getString(CmnConst.TRICODE);
            if (!codeSet.contains(tricode)) {
                DataTableEntity subDataTable = v.getSubDataTable(this.childrenKey);
                if (!BaseUtil.dataTableIsEmpty(subDataTable)) {
                    result.addFieldSetEntity(v);
                }
            }
 
        });
        return result;
    }
 
    /**
     * 模块上级
     *
     * @param data
     * @return
     */
    private DataTableEntity treeProduct(DataTableEntity data) {
        DataTableEntity product = getData(1);
        //模块map 模块code作为key
        Map<String, FieldSetEntity> codeModuleMap = Maps.newHashMap();
        //模块map 模块上级code作为key
        dataProcessing(data, codeModuleMap);
        // 产品map 产品code作为key
        Map<String, FieldSetEntity> codeProductMap = Maps.newHashMap();
        dataProcessing(product, codeProductMap);
        for (Map.Entry<String, FieldSetEntity> currentData : codeModuleMap.entrySet()) {
            // v =模块数据 FieldSetEntity
            FieldSetEntity v = currentData.getValue();
            // k =模块编码
            String k = currentData.getKey();
            // 上级编码 可以是产品也可以是模块的编码
            String parentCode = v.getString(CmnConst.TRICODE_PARENT);
            //层级 如果层级大于1说明当前 v 的上级为模块
            int level = k.split("-").length - 1;
            if (level > 1) {
                //获取上级模块 根据上级编码
                FieldSetEntity parentFieldSet = codeModuleMap.get(parentCode);
                if (parentFieldSet != null) {
                    //取出子级
                    Map<String, DataTableEntity> subData = parentFieldSet.getSubData();
                    if (subData == null) {
                        subData = new TreeMap<>();
                        parentFieldSet.setSubData(subData);
                    }
                    DataTableEntity subDataTable = parentFieldSet.getSubDataTable(this.childrenKey);
                    if (subDataTable == null) {
                        //子级为空 new 对象
                        subDataTable = new DataTableEntity();
                    }
                    subDataTable.addFieldSetEntity(v);
                    //将子级放入父级
//                    parentFieldSet.addSubDataTable(subDataTable);
                    subData.put(this.childrenKey, subDataTable);
                    continue;
 
                }
            } else {
                //获取上级产品 根据上级编码
                FieldSetEntity fieldSetEntity = codeProductMap.get(parentCode);
                if (fieldSetEntity != null) {
                    Map<String, DataTableEntity> subData = fieldSetEntity.getSubData();
                    if (subData == null) {
                        subData = new TreeMap<>();
                    }
                    fieldSetEntity.setSubData(subData);
                    DataTableEntity subDataTable = fieldSetEntity.getSubDataTable(this.childrenKey);
                    if (subDataTable == null) {
                        subDataTable = new DataTableEntity();
                    }
                    subDataTable.addFieldSetEntity(v);
                    fieldSetEntity.addSubDataTable(subDataTable);
                    subData.put(this.childrenKey, subDataTable);
                }
            }
        }
        DataTableEntity result = new DataTableEntity();
        codeProductMap.values().forEach(v -> {
            DataTableEntity subDataTable = v.getSubDataTable(this.childrenKey);
            if (!BaseUtil.dataTableIsEmpty(subDataTable)) {
                result.addFieldSetEntity(v);
                v.getSubData().remove(CmnConst.PRODUCT_SYS_FUNCTIONS);
            }
        });
        return result;
    }
 
    /**
     * 数据处理 根据表名
     *
     * @param dt
     */
    private void dataProcessing(DataTableEntity dt, Map<String, FieldSetEntity> codeMap) {
        if (!BaseUtil.dataTableIsEmpty(dt)) {
            //表名
            Object tableName = dt.getTableName();
            if (tableName == null) {
                return;
            }
            //name 字段名称
            String field;
            //数据类型 1=产品 2=模块 3=功能 4=按钮
            Integer type = null;
            //数据图标
            String svg = null;
            DataPoolCacheImpl dataPoolCache = null;
            if (CmnConst.PRODUCT_SYS_PRODUCTS.equals(tableName)) {
                field = CmnConst.PRODUCT_NAME;
                type = 1;
                svg = "product";
            } else if (CmnConst.PRODUCT_SYS_FUNCTIONS.equals(tableName)) {
                field = CmnConst.FUNCTION_NAME;
            } else if (CmnConst.PRODUCT_SYS_FUNCTION_BUTTONS.equals(tableName)) {
                field = CmnConst.BUTTON_TITLE;
                type = 4;
                svg = "btn";
                dataPoolCache = DataPoolCacheImpl.getInstance();
            } else {
                return;
            }
            Map<String, String> functionCode = Maps.newHashMap();
            for (int i = 0; i < dt.getRows(); i++) {
                dt.setFieldValue(i, "names", dt.getString(i, field));
                if (null == type) {
                    String data_type = dt.getString(i, "data_type");
//                    dt.setFieldValue(i,"uuid1",dt.getString(i,CmnConst.TRICODE_PARENT));
                    if ("1".equals(data_type)) {
                        type = 3;
                        svg = "fuc";
                    } else if ("2".equals(data_type)) {
                        type = 2;
                        svg = "module";
                    } else {
                        continue;
                    }
                }
                if (dataPoolCache != null) {
                    //将功能编码添加到按钮的父级字段中
                    String function_uuid = dt.getString(i, CmnConst.FUNCTION_UUID);
                    if (functionCode.get(function_uuid) == null) {
                        DataTableEntity d = dataPoolCache.getCacheData("所有功能", new String[]{function_uuid});
                        if (!BaseUtil.dataTableIsEmpty(dt)) {
                            String tricode = d.getString(0, "tricode");
                            functionCode.put(function_uuid, tricode);
                        }
                    }
                    String parentCode = functionCode.get(function_uuid);
                    if (!StringUtils.isEmpty(parentCode)) {
                        dt.setFieldValue(i, CmnConst.PARENT_CODE, parentCode);
                    }
                }
                dt.setFieldValue(i, "type", type);
                dt.setFieldValue(i, "svg", svg);
                if (!StringUtils.isEmpty(dt.getString(i, CmnConst.TRICODE)) && codeMap != null) {
                    codeMap.put(dt.getString(i, CmnConst.TRICODE), dt.getFieldSetEntity(i));
                }
 
            }
        }
    }
}