ny
23 小时以前 b6f169fe43a2b13f351aefc152374fc7f0bc8cb7
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
package jnpf.permission.controller;
 
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jnpf.base.ActionResult;
import jnpf.base.controller.SuperController;
import jnpf.base.vo.DownloadVO;
import jnpf.base.vo.ListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.config.ConfigValueUtil;
import jnpf.constant.FileTypeConstant;
import jnpf.constant.MsgCode;
import jnpf.constant.PermissionConst;
import jnpf.exception.DataException;
import jnpf.file.util.ExcelTool;
import jnpf.model.ExcelColumnAttr;
import jnpf.model.ExcelImportForm;
import jnpf.model.ExcelImportVO;
import jnpf.model.ExcelModel;
import jnpf.permission.RoleApi;
import jnpf.permission.constant.RoleColumnMap;
import jnpf.permission.entity.RoleEntity;
import jnpf.permission.entity.RoleRelationEntity;
import jnpf.permission.entity.UserRelationEntity;
import jnpf.permission.model.check.CheckResult;
import jnpf.permission.model.position.PosConModel;
import jnpf.permission.model.role.*;
import jnpf.permission.model.user.mod.UserIdModel;
import jnpf.permission.service.*;
import jnpf.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
 
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 角色管理
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月26日 上午9:18
 */
@Tag(name = "角色管理", description = "Role")
@RestController
@RequestMapping("/Role")
public class RoleController extends SuperController<RoleService, RoleEntity> implements RoleApi {
 
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleRelationService roleRelationService;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRelationService userRelationService;
 
    @Operation(summary = "获取角色列表")
    @SaCheckPermission(value = {"permission.auth", "permission.role"}, mode = SaMode.OR)
    @GetMapping
    public ActionResult list(RolePagination pagination) {
        pagination.setDataType(1);
        if (StringUtil.isNotEmpty(pagination.getKeyword())) {
            pagination.setDataType(null);
        }
        List<RoleEntity> list = roleService.getList(pagination);
        List<RoleListVO> listVO = new ArrayList<>();
        for (RoleEntity entity : list) {
            // 角色类型展示
            RoleListVO vo = JsonUtil.getJsonToBean(entity, RoleListVO.class);
            if (Objects.equals(entity.getGlobalMark(), 1)) {
                vo.setIsSystem(1);
            }
            listVO.add(vo);
        }
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(listVO, paginationVO);
    }
 
    @Operation(summary = "新建角色")
    @Parameters({
            @Parameter(name = "roleCrForm", description = "角色模型", required = true)
    })
    @SaCheckPermission("permission.role")
    @PostMapping
    @Transactional
    public ActionResult<String> create(@RequestBody @Valid RoleCrForm roleCrForm) {
        RoleEntity entity = JsonUtil.getJsonToBean(roleCrForm, RoleEntity.class);
        if (roleService.isExistByFullName(roleCrForm.getFullName(), null, roleCrForm.getType())) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (roleService.isExistByEnCode(roleCrForm.getEnCode(), null)) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }
 
        //约束判断
        PosConModel posConModel = new PosConModel();
        if (PermissionConst.USER.equals(entity.getType()) && Objects.equals(entity.getIsCondition(), 1)) {
            posConModel = JsonUtil.getJsonToBean(entity.getConditionJson(), PosConModel.class);
            posConModel.init();
            String errStr = posConModel.checkCondition(entity.getId());
            if (StringUtil.isNotEmpty(errStr)) {
                return ActionResult.fail(errStr);
            }
            if (posConModel.getPrerequisiteFlag()) {
                for (String item : posConModel.getPrerequisite()) {
                    RoleEntity itemInfo = roleService.getInfo(item);
                    //先决只能1级
                    if (Objects.equals(itemInfo.getIsCondition(), 1)) {
                        PosConModel itemModel = JsonUtil.getJsonToBean(itemInfo.getConditionJson(), PosConModel.class);
                        itemModel.init();
                        if (itemModel.getPrerequisiteFlag()) {
                            return ActionResult.fail(MsgCode.SYS143.get());
                        }
                    }
                }
            }
        }
        roleService.create(entity);
        roleService.linkUpdate(entity.getId(), posConModel);
        return ActionResult.success(MsgCode.SU001.get());
    }
 
    @Operation(summary = "更新角色")
    @Parameters({
            @Parameter(name = "roleUpForm", description = "角色模型", required = true),
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @SaCheckPermission("permission.role")
    @PutMapping("/{id}")
    @Transactional
    public ActionResult<String> update(@RequestBody @Valid RoleUpForm roleUpForm, @PathVariable("id") String id) throws DataException {
        RoleEntity info = roleService.getInfo(id);
        if (info == null) {
            return ActionResult.fail(MsgCode.FA001.get());
        }
        RoleEntity entity = JsonUtil.getJsonToBean(roleUpForm, RoleEntity.class);
        entity.setId(id);
        if (roleService.isExistByFullName(roleUpForm.getFullName(), id, roleUpForm.getType())) {
            return ActionResult.fail(MsgCode.EXIST001.get());
        }
        if (roleService.isExistByEnCode(roleUpForm.getEnCode(), id)) {
            return ActionResult.fail(MsgCode.EXIST002.get());
        }
        PosConModel posConModel = new PosConModel();
        //约束判断
        if (PermissionConst.USER.equals(entity.getType()) && Objects.equals(entity.getIsCondition(), 1)) {
            posConModel = JsonUtil.getJsonToBean(entity.getConditionJson(), PosConModel.class);
            posConModel.init();
            String errStr = posConModel.checkCondition(entity.getId());
            if (StringUtil.isNotEmpty(errStr)) {
                return ActionResult.fail(errStr);
            }
            //修改角色的时候,角色有人的话,互斥角色(选择的角色下的人一个都不能重叠),先决角色(选择的角色下的人必须包含当前角色人员)
            Set<String> userIds = roleRelationService.getListByRoleId(entity.getId(), PermissionConst.USER)
                    .stream().map(RoleRelationEntity::getObjectId).collect(Collectors.toSet());
            //获取全部的先决列表。用于判断当前是否开启先决(存在就不能开启)
            List<RoleEntity> list = roleService.getList(true, PermissionConst.USER, null);
            Map<String, RoleEntity> roleMap = list.stream().collect(Collectors.toMap(t -> t.getId(), t -> t));
            if (posConModel.getMutualExclusionFlag()) {
                for (String item : posConModel.getMutualExclusion()) {
                    Set<String> itemUserIds = roleRelationService.getListByRoleId(item, PermissionConst.USER)
                            .stream().map(RoleRelationEntity::getObjectId).collect(Collectors.toSet());
                    Set<String> commonIds = new HashSet<>(userIds);
                    commonIds.retainAll(itemUserIds);
                    if (!commonIds.isEmpty()) {
                        return ActionResult.fail(MsgCode.SYS137.get());
                    }
                    //当前角色A添加互斥角色B,B里的先决不能有A,如果有会导致添加成功后B角色的先决和互斥冲突
                    RoleEntity itemEntity = roleMap.get(item);
                    if (itemEntity != null && StringUtil.isNotEmpty(itemEntity.getConditionJson())) {
                        PosConModel tm = JsonUtil.getJsonToBean(itemEntity.getConditionJson(), PosConModel.class);
                        tm.init();
                        if (tm.getPrerequisite() != null && tm.getPrerequisite().contains(id)) {
                            return ActionResult.fail(MsgCode.SYS142.get());
                        }
                    }
                }
            }
            if (posConModel.getPrerequisiteFlag()) {
                //获取全部的先决列表。用于判断当前是否开启先决(存在就不能开启)
                Set<String> allPrePos = new HashSet<>();
                for (RoleEntity t : list) {
                    if (Objects.equals(t.getIsCondition(), 1)) {
                        PosConModel tm = JsonUtil.getJsonToBean(t.getConditionJson(), PosConModel.class);
                        tm.init();
                        if (tm.getPrerequisiteFlag()) {
                            allPrePos.addAll(tm.getPrerequisite());
                        }
                    }
                }
                if (allPrePos.contains(id)) {
                    return ActionResult.fail(MsgCode.SYS143.get());
                }
 
                //用户冲突--当前角色里的用户要判断先决包含先决的所有角色
                if (CollectionUtil.isNotEmpty(userIds)) {
                    for (String userId : userIds) {
                        Set<String> roleIds = roleRelationService.getListByObjectId(userId, PermissionConst.USER)
                                .stream().map(RoleRelationEntity::getRoleId).collect(Collectors.toSet());
                        //用户冲突,先决修改失败
                        if (!roleIds.containsAll(posConModel.getPrerequisite())) {
                            return ActionResult.fail(MsgCode.SYS138.get());
                        }
                    }
                }
 
                //先决只能1级--选中的先决自己不能是先决
                for (String item : posConModel.getPrerequisite()) {
                    RoleEntity itemInfo = roleService.getInfo(item);
                    if (Objects.equals(itemInfo.getIsCondition(), 1)) {
                        PosConModel itemModel = JsonUtil.getJsonToBean(itemInfo.getConditionJson(), PosConModel.class);
                        itemModel.init();
                        if (itemModel.getPrerequisiteFlag()) {
                            return ActionResult.fail(MsgCode.SYS143.get());
                        }
                    }
                }
            }
        }
        boolean flag = roleService.update(id, entity);
        if (!flag) {
            return ActionResult.fail(MsgCode.FA002.get());
        }
        roleService.linkUpdate(id, posConModel);
        return ActionResult.success(MsgCode.SU004.get());
    }
 
 
    @Operation(summary = "获取角色信息")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @SaCheckPermission("permission.role")
    @GetMapping("/{id}")
    public ActionResult<RoleInfoVO> getInfo(@PathVariable("id") String id) throws DataException {
        RoleEntity entity = roleService.getInfo(id);
        RoleInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, RoleInfoVO.class);
        //判断当前角色是否已经是先决角色
        Set<String> allPrePos = new HashSet<>();
        List<RoleEntity> list = roleService.getList(false, PermissionConst.USER, 0);
        for (RoleEntity t : list) {
            if (Objects.equals(t.getIsCondition(), 1)) {
                PosConModel tm = JsonUtil.getJsonToBean(t.getConditionJson(), PosConModel.class);
                tm.init();
                if (tm.getPrerequisiteFlag()) {
                    allPrePos.addAll(tm.getPrerequisite());
                }
            }
        }
        if (allPrePos.contains(id)) {
            vo.setIsPrePosition(true);
        }
        return ActionResult.success(vo);
    }
 
    @Operation(summary = "删除角色")
    @Parameters({
            @Parameter(name = "id", description = "主键值", required = true)
    })
    @SaCheckPermission("permission.role")
    @DeleteMapping("/{id}")
    public ActionResult<String> delete(@PathVariable("id") String id) {
        RoleEntity entity = roleService.getInfo(id);
        if (entity != null) {
            //刷新角色关联用户
            List<String> userIds = new ArrayList<>();
            if (PermissionConst.USER.equals(entity.getType())) {
                List<RoleRelationEntity> userList = roleRelationService.getListByRoleId(id, PermissionConst.USER);
                userIds.addAll(userList.stream().map(RoleRelationEntity::getObjectId).collect(Collectors.toList()));
            }
            if (PermissionConst.POSITION.equals(entity.getType())) {
                List<RoleRelationEntity> posList = roleRelationService.getListByRoleId(id, PermissionConst.POSITION);
                List<UserRelationEntity> userList = userRelationService.getListByObjectIdAll(posList.stream().map(RoleRelationEntity::getObjectId).collect(Collectors.toList()));
                userIds.addAll(userList.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList()));
            }
            roleService.delete(entity);
            if (CollectionUtil.isNotEmpty(userIds)) {
                userService.delCurUser(null, userIds);
            }
            return ActionResult.success(MsgCode.SU003.get());
        }
        return ActionResult.fail(MsgCode.FA003.get());
    }
 
    //+++++++++++++++++++++++++++++++++其他接口++++++++++++++++++++++++++++++++++++++++++++++++
 
    @Operation(summary = "角色下拉框列表")
    @GetMapping("/Selector")
    public ActionResult<ListVO<RoleSelectorVO>> listAll(@RequestParam(name = "type", required = false) String type,
                                                        @RequestParam(name = "isSystem", required = false) Integer isSystem) {
        List<RoleEntity> list = roleService.getList(true, type, isSystem);
        List<RoleSelectorVO> modelList = JsonUtil.getJsonToList(list, RoleSelectorVO.class);
        for (RoleSelectorVO vo : modelList) {
            vo.setIcon(PermissionConst.ROLE_ICON);
        }
        ListVO vo = new ListVO();
        vo.setList(modelList);
        return ActionResult.success(vo);
    }
 
    @Operation(summary = "获取角色下拉框(自定义范围)")
    @Parameters({
            @Parameter(name = "idModel", description = "ids", required = true)
    })
    @PostMapping("/RoleCondition")
    public ActionResult<List<RoleSelectorVO>> roleCondition(@RequestBody UserIdModel idModel) {
        List<RoleEntity> list = roleService.getListByIds(idModel.getIds());
        list = list.stream().filter(t -> !Objects.equals(t.getGlobalMark(), 1)).collect(Collectors.toList());
        List<RoleSelectorVO> modelList = JsonUtil.getJsonToList(list, RoleSelectorVO.class);
        for (RoleSelectorVO vo : modelList) {
            vo.setIcon(PermissionConst.ROLE_ICON);
        }
        return ActionResult.success(modelList);
    }
 
    @Operation(summary = "模板下载")
    @SaCheckPermission("permission.role")
    @GetMapping("/TemplateDownload")
    public ActionResult<DownloadVO> TemplateDownload() {
        RoleColumnMap columnMap = new RoleColumnMap();
        String excelName = columnMap.getExcelName();
        Map<String, String> keyMap = columnMap.getColumnByType(0);
        List<ExcelColumnAttr> models = columnMap.getFieldsModel(false);
        List<Map<String, Object>> list = columnMap.getDefaultList();
        Map<String, String[]> optionMap = getOptionMap();
        ExcelModel excelModel = ExcelModel.builder().models(models).selectKey(new ArrayList<>(keyMap.keySet())).optionMap(optionMap).build();
        DownloadVO vo = ExcelTool.getImportTemplate(configValueUtil.getTemporaryFilePath(), excelName, keyMap, list, excelModel);
        return ActionResult.success(vo);
    }
 
    /**
     * 上传Excel
     *
     * @return
     */
    @Operation(summary = "上传导入Excel")
    @SaCheckPermission("permission.role")
    @PostMapping("/Uploader")
    public ActionResult<Object> Uploader() {
        return ExcelTool.uploader();
    }
 
    /**
     * 导入预览
     *
     * @return
     */
    @Operation(summary = "导入预览")
    @SaCheckPermission("permission.role")
    @GetMapping("/ImportPreview")
    public ActionResult<Map<String, Object>> ImportPreview(String fileName) throws Exception {
        // 导入字段
        RoleColumnMap columnMap = new RoleColumnMap();
        Map<String, String> keyMap = columnMap.getColumnByType(0);
        Map<String, Object> headAndDataMap = ExcelTool.importPreview(configValueUtil.getTemporaryFilePath(), fileName, keyMap);
        return ActionResult.success(headAndDataMap);
    }
 
 
    /**
     * 导出异常报告
     *
     * @return
     */
    @Operation(summary = "导出异常报告")
    @SaCheckPermission("permission.role")
    @PostMapping("/ExportExceptionData")
    public ActionResult<DownloadVO> ExportExceptionData(@RequestBody ExcelImportForm visualImportModel) {
        String temporaryFilePath = configValueUtil.getTemporaryFilePath();
        List<Map<String, Object>> dataList = visualImportModel.getList();
        RoleColumnMap columnMap = new RoleColumnMap();
        String excelName = columnMap.getExcelName();
        Map<String, String> keyMap = columnMap.getColumnByType(0);
        List<ExcelColumnAttr> models = columnMap.getFieldsModel(true);
        ExcelModel excelModel = ExcelModel.builder().optionMap(getOptionMap()).models(models).build();
        DownloadVO vo = ExcelTool.exportExceptionReport(temporaryFilePath, excelName, keyMap, dataList, excelModel);
        return ActionResult.success(vo);
    }
 
    /**
     * 导入数据
     *
     * @return
     */
    @Operation(summary = "导入数据")
    @SaCheckPermission("permission.role")
    @PostMapping("/ImportData")
    public ActionResult<ExcelImportVO> ImportData(@RequestBody ExcelImportForm visualImportModel) throws Exception {
        List<Map<String, Object>> listData = new ArrayList<>();
        List<Map<String, Object>> headerRow = new ArrayList<>();
        if (visualImportModel.isType()) {
            ActionResult result = ImportPreview(visualImportModel.getFileName());
            if (result == null) {
                throw new Exception(MsgCode.FA018.get());
            }
            if (result.getCode() != 200) {
                throw new Exception(result.getMsg());
            }
            if (result.getData() instanceof Map) {
                Map<String, Object> data = (Map<String, Object>) result.getData();
                listData = (List<Map<String, Object>>) data.get("dataRow");
                headerRow = (List<Map<String, Object>>) data.get("headerRow");
            }
        } else {
            listData = visualImportModel.getList();
        }
        List<RoleEntity> addList = new ArrayList<RoleEntity>();
        List<Map<String, Object>> failList = new ArrayList<>();
        Map<String, List<List<String>>> addOrganizeIdMap = new HashMap<>();
        // 对数据做校验
        this.validateImportData(listData, addList, addOrganizeIdMap, failList);
 
        //正常数据插入
        for (RoleEntity each : addList) {
            roleService.create(each);
        }
        ExcelImportVO importModel = new ExcelImportVO();
        importModel.setSnum(addList.size());
        importModel.setFnum(failList.size());
        importModel.setResultType(failList.size() > 0 ? 1 : 0);
        importModel.setFailResult(failList);
        importModel.setHeaderRow(headerRow);
        return ActionResult.success(importModel);
    }
 
    private void validateImportData(List<Map<String, Object>> listData, List<RoleEntity> addList, Map<String, List<List<String>>> addOrganizeIdMap, List<Map<String, Object>> failList) {
        RoleColumnMap columnMap = new RoleColumnMap();
        Map<String, String> keyMap = columnMap.getColumnByType(0);
        QueryWrapper<RoleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().isNull(RoleEntity::getDeleteMark);
        queryWrapper.lambda().orderByAsc(RoleEntity::getSortCode).orderByDesc(RoleEntity::getCreatorTime);
        List<RoleEntity> allPositionList = roleService.list(queryWrapper);
        Map<String, Object> allOrgsTreeName = organizeService.getAllOrgsTreeName();
        for (int i = 0, len = listData.size(); i < len; i++) {
            Map<String, Object> eachMap = listData.get(i);
            Map<String, Object> realMap = JsonUtil.getJsonToBean(eachMap, Map.class);
            StringJoiner errInfo = new StringJoiner(",");
            int globalMark = "组织".equals(eachMap.get("globalMark")) ? 0 : 1;
            List<List<String>> organizeIdList = null;
            for (String column : keyMap.keySet()) {
                Object valueObj = eachMap.get(column);
                String value = valueObj == null ? null : String.valueOf(valueObj);
                String columnName = keyMap.get(column);
 
                switch (column) {
                    case "fullName":
                        if (StringUtil.isEmpty(value)) {
                            errInfo.add(columnName + "不能为空");
                            break;
                        }
                        if (value.length() > 50) {
                            errInfo.add(columnName + "值超出最多输入字符限制");
                        }
                        //值不能含有特殊符号
                        if (!RegexUtils.checkSpecoalSymbols(value)) {
                            errInfo.add(columnName + "值不能含有特殊符号");
                        }
                        //库里重复
                        int finalGlobalMark = globalMark;
                        long fullNameCount = allPositionList.stream().filter(t -> t.getFullName().equals(value) && t.getGlobalMark().equals(finalGlobalMark)).count();
                        if (fullNameCount > 0) {
                            errInfo.add(columnName + "值已存在");
                            break;
                        }
                        //表格内重复
                        fullNameCount = addList.stream().filter(t -> t.getFullName().equals(value) && t.getGlobalMark().equals(finalGlobalMark)).count();
                        if (fullNameCount > 0) {
                            errInfo.add(columnName + "值已存在");
                            break;
                        }
                        break;
                    case "enCode":
                        if (StringUtil.isEmpty(value)) {
                            errInfo.add(columnName + "不能为空");
                            break;
                        }
                        if (value.length() > 50) {
                            errInfo.add(columnName + "值超出最多输入字符限制");
                        }
                        if (!RegexUtils.checkEnCode(value)) {
                            errInfo.add(columnName + "只能输入英文、数字和小数点且小数点不能放在首尾");
                        }
                        //库里重复
                        long enCodeCount = allPositionList.stream().filter(t -> t.getEnCode().equals(value)).count();
                        if (enCodeCount > 0) {
                            errInfo.add(columnName + "值已存在");
                            break;
                        }
                        //表格内重复
                        enCodeCount = addList.stream().filter(t -> t.getEnCode().equals(value)).count();
                        if (enCodeCount > 0) {
                            errInfo.add(columnName + "值已存在");
                            break;
                        }
                        break;
                    case "globalMark":
                        if (StringUtil.isEmpty(value)) {
                            errInfo.add(columnName + "不能为空");
                            break;
                        }
                        if ("全局".equals(value)) {
                            globalMark = 1;
                        } else if ("组织".equals(value)) {
                            globalMark = 0;
                        } else {
                            errInfo.add(columnName + "值不正确");
                            break;
                        }
                        realMap.put("globalMark", globalMark);
                        break;
                    case "organizeId":
                        if (globalMark == 0) {
                            if (StringUtil.isEmpty(value)) {
                                errInfo.add("所属组织" + "不能为空");
                                break;
                            }
                        }
                        if (globalMark == 1) {
                            realMap.put("organizeId", null);
                            break;
                        }
                        if (StringUtil.isEmpty(value)) {
                            break;
                        }
                        CheckResult organizeIdCheckResult = this.checkOrganizes(value, allOrgsTreeName);
                        if (!organizeIdCheckResult.isPass()) {
                            errInfo.add(organizeIdCheckResult.getErrorMsg());
                            break;
                        }
                        organizeIdList = (List<List<String>>) organizeIdCheckResult.getValue();
                        break;
                    case "sortCode":
                        if (StringUtil.isEmpty(value)) {
                            realMap.put("sortCode", 0);
                            break;
                        }
                        Long numValue = 0l;
                        try {
                            numValue = Long.parseLong(value);
                        } catch (Exception e) {
                            errInfo.add(columnName + "值不正确");
                            break;
                        }
                        if (numValue < 0) {
                            errInfo.add(columnName + "值不能小于0");
                            break;
                        }
                        if (numValue > 1000000) {
                            errInfo.add(columnName + "值不能大于999999");
                            break;
                        }
                        break;
                    case "enabledMark":
                        if (StringUtil.isEmpty(value)) {
                            errInfo.add(columnName + "不能为空");
                            break;
                        }
                        if ("启用".equals(value)) {
                            realMap.put("enabledMark", 1);
                        } else if ("禁用".equals(value)) {
                            realMap.put("enabledMark", 0);
                        } else {
                            errInfo.add(columnName + "值不正确");
                        }
                        break;
                    default:
                        break;
                }
 
            }
            if (errInfo.length() == 0) {
                RoleEntity roleEntity = JsonUtil.getJsonToBean(realMap, RoleEntity.class);
                roleEntity.setCreatorTime(new Date());
                roleEntity.setId(RandomUtil.uuId());
                addList.add(roleEntity);
                if (organizeIdList != null && !organizeIdList.isEmpty() && roleEntity.getGlobalMark() == 0) {
                    addOrganizeIdMap.put(roleEntity.getId(), organizeIdList);
                }
            } else {
                eachMap.put("errorsInfo", errInfo.toString());
                failList.add(eachMap);
            }
        }
    }
 
    /**
     * 导出Excel
     *
     * @return
     */
    @Operation(summary = "导出Excel")
    @SaCheckPermission("permission.role")
    @GetMapping("/ExportData")
    public ActionResult ExportData(RolePagination pagination) throws IOException {
        if (StringUtil.isEmpty(pagination.getSelectKey())) {
            return ActionResult.fail(MsgCode.IMP011.get());
        }
        List<RoleEntity> list = roleService.getList(pagination);
 
        // todo 导出数据
        List<Map<String, Object>> realList = new ArrayList<>();
 
        String[] keys = !StringUtil.isEmpty(pagination.getSelectKey()) ? pagination.getSelectKey() : new String[0];
        RoleColumnMap posColumnMap = new RoleColumnMap();
        String excelName = posColumnMap.getExcelName();
        List<ExcelColumnAttr> models = posColumnMap.getFieldsModel(false);
        Map<String, String> keyMap = posColumnMap.getColumnByType(null);
        Map<String, String[]> optionMap = new HashMap<>();
        ExcelModel excelModel = ExcelModel.builder().selectKey(Arrays.asList(keys)).models(models).optionMap(optionMap).build();
        DownloadVO vo = ExcelTool.creatModelExcel(configValueUtil.getTemporaryFilePath(), excelName, keyMap, realList, excelModel);
        return ActionResult.success(vo);
    }
 
    private CheckResult checkOrganizes(String organizeNames, Map<String, Object> allOrgsTreeName) {
        String[] organizeNameArray = organizeNames.split(",");
        List<String> errorOrganizeNameList = new ArrayList<>();
        List<List<String>> successOrganizeIdList = new ArrayList<>();
        for (String organizeName : organizeNameArray) {
            String organizeId = null;
            boolean find = false;
            for (String key : allOrgsTreeName.keySet()) {
                Object o = allOrgsTreeName.get(key);
                if (organizeName.equals(o.toString())) {
                    find = true;
                    successOrganizeIdList.add(Arrays.asList(key.split(",")));
                    break;
                }
            }
            if (!find) {
                errorOrganizeNameList.add(organizeName);
            }
        }
        if (errorOrganizeNameList.isEmpty()) {
            return new CheckResult(true, null, successOrganizeIdList);
        } else if (organizeNameArray.length == 1) {
            return new CheckResult(false, "找不到该所属组织", null);
        } else {
            return new CheckResult(false, "找不到该所属组织(" + String.join("、", errorOrganizeNameList) + ")", null);
        }
    }
 
    /**
     * 获取下拉框
     *
     * @return
     */
    private Map<String, String[]> getOptionMap() {
        Map<String, String[]> optionMap = new HashMap<>();
        //角色类型
        optionMap.put("globalMark", new String[]{"全局", "组织"});
        optionMap.put("enabledMark", new String[]{"启用", "禁用"});
        return optionMap;
    }
 
 
    //以下是接口---------------------------------
    @Override
    @GetMapping("/getInfoById/{id}")
    public RoleEntity getInfoById(@PathVariable("id") String id) {
        return roleService.getInfo(id);
    }
 
    @Override
    @PostMapping("/getListByIds")
    public List<RoleEntity> getListByIds(@RequestBody List<String> roleIds) {
        return roleService.getListByIds(roleIds, null, false);
    }
 
    @Override
    @GetMapping("/getCurRolesByOrgId")
    public List<RoleEntity> getCurRolesByOrgId() {
        return roleService.getCurRolesByOrgId();
    }
 
    @Override
    @GetMapping("/getListAll")
    public List<RoleEntity> getListAll() {
        return roleService.getList(false,null,null);
    }
 
    @Override
    @GetMapping("/getRoleMap")
    public Map<String, Object> getRoleMap(@RequestParam ("type")String type) {
        if ("id-fullName".equals(type)){
            return roleService.getRoleMap();
        } else {
            return roleService.getRoleNameAndIdMap();
        }
    }
 
    @Override
    @GetMapping("/getUserRoles")
    public List<RoleEntity> getUserRoles(@RequestParam ("userId")String userId) {
        return roleService.getUserRoles(userId);
    }
 
    @Override
    @GetMapping("/roleUserCount")
    public Map<String, Integer> roleUserCount() {
        Map<String, Integer> map = new HashMap<>();
        List<RoleEntity> list = roleService.getList(true, PermissionConst.USER, null);
        List<RoleRelationEntity> listByRoleId = roleRelationService.getListByRoleId("", PermissionConst.USER);
        Map<String, List<RoleRelationEntity>> roleGroup = listByRoleId.stream().collect(Collectors.groupingBy(RoleRelationEntity::getRoleId));
        for (RoleEntity role : list) {
            map.put(role.getFullName(), CollectionUtil.isEmpty(roleGroup.get(role.getId())) ? 0 : roleGroup.get(role.getId()).size());
        }
        return map;
    }
}