UserRoleServiceImpl.java 88.4 KB
Newer Older
frank.xa.zhang's avatar
frank.xa.zhang committed
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 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
package pwc.taxtech.atms.service.impl;

import org.apache.commons.lang3.BooleanUtils;
import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import pwc.taxtech.atms.common.CommonConstants;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.common.OperateLogType;
import pwc.taxtech.atms.common.OperationAction;
import pwc.taxtech.atms.common.OperationModule;
import pwc.taxtech.atms.common.RoleSourceEnum;
import pwc.taxtech.atms.common.UserStatus;
import pwc.taxtech.atms.common.message.LogMessage;
import pwc.taxtech.atms.common.message.UserMessage;
import pwc.taxtech.atms.constant.DimensionConstant;
import pwc.taxtech.atms.constant.UserConstant;
import pwc.taxtech.atms.dpo.DimensionValueOrgDto;
import pwc.taxtech.atms.dpo.OrganizationDto;
import pwc.taxtech.atms.dpo.RoleInfo;
import pwc.taxtech.atms.dpo.UserDto;
import pwc.taxtech.atms.dpo.UserOrgDto;
import pwc.taxtech.atms.dpo.UserOrgRoleDto;
import pwc.taxtech.atms.dpo.UserRoleQuery;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.UpdateLogParams;
import pwc.taxtech.atms.dto.organization.DimensionRoleDto;
import pwc.taxtech.atms.dto.organization.OrgCustomDto;
import pwc.taxtech.atms.dto.organization.OrgRoleDto;
import pwc.taxtech.atms.dto.organization.OrgRoleDtoList;
import pwc.taxtech.atms.dto.organization.SimpleRoleDto;
import pwc.taxtech.atms.dto.role.RoleDto;
import pwc.taxtech.atms.dto.user.DimensionUser;
import pwc.taxtech.atms.dto.user.NameDto;
import pwc.taxtech.atms.dto.user.OrganizationRoleInfo;
import pwc.taxtech.atms.dto.user.UpdateParam;
import pwc.taxtech.atms.dto.user.UserAndUserRoleSaveDto;
import pwc.taxtech.atms.dto.user.UserOrganizationDto;
import pwc.taxtech.atms.dto.user.UserRoleDimensionValueDto;
import pwc.taxtech.atms.dto.user.UserRoleDisplayInfo;
import pwc.taxtech.atms.dto.user.UserRoleQueryDto;
import pwc.taxtech.atms.entity.*;
import pwc.taxtech.atms.entity.UserRoleExample.Criteria;
import pwc.taxtech.atms.exception.ApplicationException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserRoleServiceImpl extends AbstractService {

    @Autowired
    private PermissionServiceImpl permissionService;

    @Autowired
    private OrganizationServiceImpl organizationService;

    @Autowired
    private UserServiceImpl userService;

    public OrgRoleDtoList getUserRoleByUserId(String userId) {
        OrgRoleDtoList result = new OrgRoleDtoList();
        List<OrganizationRoleInfo> orgRoleInfoList = new ArrayList<>();
        if (!StringUtils.hasText(userId)) {
            return result;
        }

        // 原始角色
        List<RoleInfo> orignialUserRole = getOriginalRole(userId);

        // 维度附加角色
        List<UserOrgRoleDto> userDimensionValueRoleList = getUserDimensionValueRoleList();

        // 机构继承维度
        List<UserDimensionValueOrg> userDimensionValueOrgList = getUserDimensionValueOrgList();

        // 机构的附加角色
        List<UserOrgRoleDto> userOrganizationRoleList = getUserOrganizationRoleList();

        // 获取维度的基本数据
        List<UserRoleDimensionValueDto> basicQuery = getUserRoleDimensionValueBasic();

        // 维度的数据,可以是继承userRole的原始角色,也可以是附加的角色
        // 获取某个维度值下面的机构的用户角色
        List<UserRoleDimensionValueDto> dimensionOrgList = basicQuery.stream().filter(s -> userId.equals(s.getUserId()))
                .map(x -> CommonUtils.copyProperties(x, new UserRoleDimensionValueDto())).distinct()
                .collect(Collectors.toList());

        // 1. 维度上的角色
        for (UserRoleDimensionValueDto g : dimensionOrgList) {
            // 机构在维度上是否可以被继承,或者被访问
            UserDimensionValueOrg userDimensionValurOrg = userDimensionValueOrgList.stream()
                    .filter(uvg -> uvg.getUserDimensionValueId() != null && uvg.getOrganizationId() != null
                            && uvg.getUserDimensionValueId().equals(g.getId())
                            && uvg.getOrganizationId().equals(g.getOrganizationId()))
                    .findFirst().orElse(null);
            // 如果没有设置值,默认可以继承
            boolean isHeritable = userDimensionValurOrg == null
                    || BooleanUtils.isTrue(userDimensionValurOrg.getIsHeritable());
            if (!isHeritable) {
                continue;
            }
            // 不管允许不允许继承,都显示角色列表
            OrganizationRoleInfo orgRoleInfo = CommonUtils.copyProperties(g, new OrganizationRoleInfo());
            orgRoleInfo.setId(CommonUtils.getUUID());
            orgRoleInfo.setRoleList(new ArrayList<>());

            List<RoleInfo> roleInfoList = new ArrayList<>();

            // 1.1 继承原始角色
            if (BooleanUtils.isTrue(g.getHasOriginalRole()) && orignialUserRole != null
                    && !orignialUserRole.isEmpty()) {
                for (RoleInfo r : orignialUserRole) {
                    if (!roleInfoList.stream().anyMatch(s -> s.getId() != null && s.getId().equals(r.getId()))) {
                        roleInfoList.add(generateRoleInfo(r.getId(), r.getName(), RoleSourceEnum.Unknown.value()));
                    }
                }
            }

            // 1.2 维度的附加角色
            List<UserOrgRoleDto> userDimensionValueRole = userDimensionValueRoleList.stream()
                    .filter(udv -> udv.getId() != null && udv.getId().equals(g.getId())).collect(Collectors.toList());
            for (UserOrgRoleDto r : userDimensionValueRole) {
                if (!roleInfoList.stream().anyMatch(s -> s.getId() != null && s.getId().equals(r.getRoleId()))) {
                    roleInfoList.add(generateRoleInfo(r.getRoleId(), r.getRoleName(), RoleSourceEnum.Unknown.value()));
                }
            }
            orgRoleInfo.setRoleList(roleInfoList);
            orgRoleInfoList.add(orgRoleInfo);
        }
        // end.维度上的角色

        // 2 机构角色
        // 用户在机构可以添加原始角色,或者附加角色
        List<Map<String, Object>> userOrgList = myUserMapper.selectUserOrganizationMapByUserId(userId);

        for (Map<String, Object> userOrg : userOrgList) {
            boolean isAccessible = BooleanUtils.isTrue((Boolean) userOrg.get("isAccessible"));
            boolean hasOriginalRole = BooleanUtils.isTrue((Boolean) userOrg.get("hasOriginalRole"));

            List<RoleInfo> roleInfoList = new ArrayList<>();
            // 2.1 添加机构的附加原始角色
            if (hasOriginalRole && orignialUserRole != null && !orignialUserRole.isEmpty()) {
                for (RoleInfo r : orignialUserRole) {
                    if (!roleInfoList.stream().anyMatch(s -> s.getId() != null && s.getId().equals(r.getId()))) {
                        roleInfoList.add(generateRoleInfo(r.getId(), r.getName(), RoleSourceEnum.Unknown.value()));
                    }
                }
            }

            orgRoleInfoList.add(generateOrganizationRoleInfo(userOrg.get("organizationID").toString(),
                    userOrg.get("organizationName").toString(), DimensionConstant.OriginalRoleDimensionValueId,
                    DimensionConstant.OriginalRole, hasOriginalRole, isAccessible, roleInfoList, userId));
            List<RoleInfo> roleInfoList1 = new ArrayList<>();

            // 2.2 机构的附加(额外)角色,特殊权限
            List<UserOrgRoleDto> specialOrgRoleList = userOrganizationRoleList.stream()
                    .filter(urd -> urd.getId() != null && urd.getId().equals(userOrg.get("id")))
                    .collect(Collectors.toList());

            if (!specialOrgRoleList.isEmpty()) {

                for (UserOrgRoleDto r : specialOrgRoleList) {
                    if (!roleInfoList1.stream().anyMatch(s -> s.getId() != null && s.getId().equals(r.getRoleId()))) {
                        roleInfoList1
                                .add(generateRoleInfo(r.getRoleId(), r.getRoleName(), RoleSourceEnum.Unknown.value()));
                    }
                }

                orgRoleInfoList.add(generateOrganizationRoleInfo(userOrg.get("organizationId").toString(),
                        userOrg.get("organizationName").toString(), DimensionConstant.ExtraOrgDimensionValueId,
                        DimensionConstant.ExtraOrgDimensionValueName, hasOriginalRole, isAccessible, roleInfoList1,
                        userId));
            }
        }

        // 机构上的角色
        List<OrgRoleDto> retList = new ArrayList<>();

        List<Map<String, String>> groupOrgRoleList = orgRoleInfoList.stream().map(this::rotateOrganizationRoleInfoToMap)
                .distinct().collect(Collectors.toList());
        for (Map<String, String> gr : groupOrgRoleList) {
            OrgRoleDto row = new OrgRoleDto();
            row.setOrgId(gr.get("organizationId"));
            row.setOrgName(gr.get("organizationName"));

            List<RoleInfo> roleList = new ArrayList<>();

            List<OrganizationRoleInfo> orgRoleList = orgRoleInfoList.stream().filter(
                    s -> s.getOrganizationId() != null && s.getOrganizationId().equals(gr.get("organizationId")))
                    .collect(Collectors.toList());
            if (orgRoleList.stream().anyMatch(x -> !BooleanUtils.isTrue(x.getIsAccessible()))) {
                row.setIsAccessible(false);
            } else {
                row.setIsAccessible(true);
            }

            for (OrganizationRoleInfo orgRole : orgRoleList) {
                for (RoleInfo role : orgRole.getRoleList()) {
                    if (!roleList.stream().anyMatch(x -> x.getId() != null && x.getId().equals(role.getId()))) {
                        roleList.add(role);
                    }
                }
            }
            row.setRoleList(roleList);
            retList.add(row);
        }

        result.setOrgRoleInfoList(orgRoleInfoList);
        result.setOrgDtoList(retList);

        return result;
    }

    private List<RoleInfo> getOriginalRole(String userId) {
        return userMapper.selectUserRoleInfoById(userId);
    }

    private List<UserOrgRoleDto> getUserDimensionValueRoleList() {
        return userMapper.selectUserDimensionValueRole();
    }

    private List<UserDimensionValueOrg> getUserDimensionValueOrgList() {
        return userDimensionValueOrgMapper.selectByExample(new UserDimensionValueOrgExample());
    }

    private List<UserOrgRoleDto> getUserOrganizationRoleList() {
        return userMapper.selectUserOrganizationRole();
    }

    /**
     * 维度值下的用户角色列表,跟机构有绑定
     */
    private List<UserRoleDimensionValueDto> getUserRoleDimensionValueBasic() {
        List<DimensionValueOrgDto> basicQuery = getDimensionValueOrgDtoList();
        List<Map<String, Object>> userRoleDimensionValue = myUserMapper.selectUserDimensionValueMap();
        List<UserRoleDimensionValueDto> query = new ArrayList<>();
        for (DimensionValueOrgDto p : basicQuery) {
            List<Map<String, Object>> uList = userRoleDimensionValue.stream()
                    .filter(x -> p.getDimensionId() != null && p.getDimensionId().equals(x.get("dimensionId"))
                            && p.getDimensionValueId() != null
                            && p.getDimensionValueId().equals(x.get("dimensionValueId")))
                    .collect(Collectors.toList());
            if (uList.isEmpty()) {
                query.add(generateUserRoleDimensionValueDto(p, new HashMap<>()));
                continue;
            }
            for (Map<String, Object> u : uList) {
                query.add(generateUserRoleDimensionValueDto(p, u));
            }
        }
        return query;
    }

    private UserRoleDimensionValueDto generateUserRoleDimensionValueDto(DimensionValueOrgDto p, Map<String, Object> u) {
        UserRoleDimensionValueDto userRoleDimensionValueDto = new UserRoleDimensionValueDto();
        userRoleDimensionValueDto.setOrganizationId(p.getOrganizationId());
        userRoleDimensionValueDto.setOrganizationName(p.getOrganizationName());
        userRoleDimensionValueDto.setId(Strings.sBlank(u.get("id")));
        userRoleDimensionValueDto.setDimensionValueId(Strings.sBlank(u.get("dimensionValueId")));
        userRoleDimensionValueDto.setDimensionValueName(p.getDimensionValue());
        userRoleDimensionValueDto.setDimensionId(Strings.sBlank(u.get("dimensionId")));
        userRoleDimensionValueDto.setDimensionName(p.getDimensionName());
        userRoleDimensionValueDto.setUserId(Strings.sBlank(u.get("userId")));
        userRoleDimensionValueDto.setUserName(Strings.sBlank(u.get("userName")));
        userRoleDimensionValueDto.setIsAccessible(BooleanUtils.isTrue((Boolean) u.get("isAccessible")));
        userRoleDimensionValueDto.setHasOriginalRole(BooleanUtils.isTrue((Boolean) u.get("hasOriginalRole")));
        return userRoleDimensionValueDto;
    }

    private Map<String, String> rotateOrganizationRoleInfoToMap(OrganizationRoleInfo organizationRoleInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("organizationId", organizationRoleInfo.getOrganizationId());
        map.put("organizationName", organizationRoleInfo.getOrganizationName());
        return map;
    }

    private List<DimensionValueOrgDto> getDimensionValueOrgDtoList() {
        return organizationService.getDimensionValueOrgDtoList();
    }

    public UserAndUserRoleSaveDto getSingleUserByUserId(String userId) {
        UserAndUserRoleSaveDto userDto = new UserAndUserRoleSaveDto();
        User user = userMapper.selectByPrimaryKey(userId);
        if (user != null) {
            userDto = CommonUtils.copyProperties(user, new UserAndUserRoleSaveDto());
            // get role list by user
            List<Map<String, String>> query = myUserMapper.selectUserRoleListByUserId(userId).stream().distinct()
                    .collect(Collectors.toList());
            List<String> arrUserRole = new ArrayList<>();
            List<String> arrUserRoleName = new ArrayList<>();
            if (!query.isEmpty()) {
                for (Map<String, String> userRole : query) {
                    arrUserRole.add(userRole.get("roleId"));
                    arrUserRoleName.add(userRole.get("roleName"));
                }
            }
            userDto.setRoleIds(arrUserRole);
            userDto.setRoleNames(arrUserRoleName);
            // get org name
            Organization org = organizationMapper.selectByPrimaryKey(user.getOrganizationId());
            if (org != null) {
                userDto.setOrgName(org.getName());
            }
        }
        return userDto;
    }

    public List<UserRoleDisplayInfo> getAllUserRoleList(String serviceTypeId) {
        List<UserRoleQuery> query = userRoleMapper.selectUserRoleQueryByServiceTypeIdAll(serviceTypeId);
        List<UserRoleDisplayInfo> userRoleDtoList = new ArrayList<>();
        List<UserRoleQueryDto> userList = query.stream().map(u -> CommonUtils.copyProperties(u, new UserRoleQueryDto()))
                .distinct().collect(Collectors.toList());
        for (UserRoleQueryDto item : userList) {
            UserRoleDisplayInfo dto = new UserRoleDisplayInfo();
            dto.setId(item.getUserId());
            dto.setUserId(item.getUserId());
            dto.setUserName(item.getUserName());
            dto.setOrganizationId(item.getOrgId());
            dto.setOrganizationName(item.getOrgName());
            dto.setEmail(item.getEmail());
            dto.setStatus(item.getStatus() ? 1 : 0);

            List<UserRoleQuery> roleList = query.stream().filter(s -> Objects.equals(s.getUserId(), item.getUserId()))
                    .distinct().collect(Collectors.toList());

            // 构造每个用户的角色列表
            List<RoleInfo> roleInfoList = new ArrayList<>();
            for (UserRoleQuery r : roleList) {
                if (!roleInfoList.stream().anyMatch(s -> Objects.equals(s.getId(), r.getRoleId()))) {
                    RoleInfo roleInfo = new RoleInfo();
                    roleInfo.setId(r.getRoleId());
                    roleInfo.setName(r.getRoleName());
                    roleInfo.setRoleSource(RoleSourceEnum.OriginalLevel.value());

                    roleInfoList.add(roleInfo);
                }
            }
            dto.setRoleInfoList(roleInfoList);
            userRoleDtoList.add(dto);
        }
        return userRoleDtoList;
    }

    public List<UserRole> findAllUserRoles() {
        UserRoleExample userRoleExample = new UserRoleExample();
        return userRoleMapper.selectByExample(userRoleExample);
    }

    public UserRoleDisplayInfo getUserRoleListByUserId(String userId) {
        List<UserRoleDisplayInfo> allUserList = getAllUserRoleList("2");
        return allUserList.stream().filter(s -> s.getUserId() != null && s.getUserId().equals(userId)).findFirst()
                .orElse(new UserRoleDisplayInfo());
    }

    /**
     * 某个机构下的所有权限 任何一个不可访问,就不可访问,任何的维度,和附加
     */
    public UserOrganizationDto getUserRoleByOrgId(String userId, String orgId) {
        UserOrganizationDto userOrganizationDto = new UserOrganizationDto();
        userOrganizationDto.setDimensionUserList(new ArrayList<>());
        DimensionUser dimensionUser = null;
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return userOrganizationDto;
        }
        Organization org = organizationMapper.selectByPrimaryKey(orgId);
        if (org == null) {
            return userOrganizationDto;
        }
        // 整个机构是否可访问
        List<Boolean> allIsAccessibleList = new ArrayList<>();
        userOrganizationDto.setUserName(user.getUserName());
        userOrganizationDto.setOrganizationName(org.getName());

        // 原始角色
        List<RoleInfo> orignialUserRole = getOriginalRole(userId);

        // 维度附加角色
        List<UserOrgRoleDto> userDimensionValueRoleList = getUserDimensionValueRoleList();

        // 机构继承维度
        List<UserDimensionValueOrg> userDimensionValueOrgList = getUserDimensionValueOrgList();

        // 机构的附加角色
        List<UserOrgRoleDto> userOrganizationRoleList = getUserOrganizationRoleList();

        // 获取维度的基本数据
        List<UserRoleDimensionValueDto> basicQuery = getUserRoleDimensionValueBasic();

        // 用户机构表
        List<UserOrganization> userOrganizationList = getUserOrganizationList();
        // 维度的数据,可以是继承userRole的原始角色,也可以是附加的角色
        // 获取某个维度值下面的机构的用户角色
        List<UserRoleDimensionValueDto> dimensionOrgList = basicQuery.stream()
                .filter(s -> Objects.equals(orgId, s.getOrganizationId()) && Objects.equals(userId, s.getUserId()))
                .map(s -> CommonUtils.copyProperties(s, new UserRoleDimensionValueDto())).distinct()
                .collect(Collectors.toList());
        // 维度上的角色
        for (UserRoleDimensionValueDto d : dimensionOrgList) {
            // 机构在维度上是否可以被继承,或者被访问
            UserDimensionValueOrg userDimensionValurOrg = userDimensionValueOrgList.stream()
                    .filter(uvg -> Objects.equals(d.getId(), uvg.getUserDimensionValueId())
                            && Objects.equals(d.getOrganizationId(), uvg.getOrganizationId()))
                    .findFirst().orElse(null);
            // 如果没有设置值,默认可以继承
            boolean isHeritable = userDimensionValurOrg == null
                    || BooleanUtils.isTrue(userDimensionValurOrg.getIsHeritable());
            // 任何一个维度上不可访问,且机构继承这个维度,那么这个机构就不可访问
            if (isHeritable && !BooleanUtils.isTrue(d.getIsAccessible())) {
                allIsAccessibleList.add(false); // 不可访问
            }
            // 不管允许不允许继承,都显示角色列表
            dimensionUser = CommonUtils.copyProperties(d, new DimensionUser());
            dimensionUser.setId(CommonUtils.getUUID());
            dimensionUser.setIsHeritable(isHeritable);
            dimensionUser.setRoleList(new ArrayList<>());

            List<NameDto> roleInfoList = new ArrayList<>();

            // 1.1 继承原始角色
            if (BooleanUtils.isTrue(d.getHasOriginalRole()) && orignialUserRole != null
                    && !orignialUserRole.isEmpty()) {
                for (RoleInfo r : orignialUserRole) {
                    if (!roleInfoList.stream().anyMatch(s -> Objects.equals(s.getId(), r.getId()))) {
                        roleInfoList.add(generateNameDto(r.getId(), r.getName(), RoleSourceEnum.Unknown.value()));
                    }
                }
            }

            // 1.2 维度的附加角色
            List<UserOrgRoleDto> userDimensionValueRole = userDimensionValueRoleList.stream()
                    .filter(udv -> Objects.equals(udv.getId(), d.getId())).collect(Collectors.toList());
            for (UserOrgRoleDto r : userDimensionValueRole) {
                if (!roleInfoList.stream().anyMatch(s -> Objects.equals(s.getId(), r.getId()))) {
                    roleInfoList.add(generateNameDto(r.getRoleId(), r.getRoleName(), RoleSourceEnum.Unknown.value()));
                }
            }

            dimensionUser.setRoleList(roleInfoList);
            userOrganizationDto.getDimensionUserList().add(dimensionUser);
        }
        // 用户在机构可以添加原始角色,或者附加角色
        UserOrganization userOrg = userOrganizationList.stream()
                .filter(ur -> Objects.equals(orgId, ur.getOrganizationId()) && Objects.equals(userId, ur.getUserId()))
                .findFirst().orElse(null);
        if (userOrg != null) {
            boolean isAccessible = BooleanUtils.isTrue(userOrg.getIsAccessible());
            boolean hasOriginalRole = BooleanUtils.isTrue(userOrg.getHasOriginalRole());
            if (!isAccessible) {
                allIsAccessibleList.add(false); // 用户机构不可访问,这是最高优先级
            }
            // 是否可以继承原始角色
            userOrganizationDto.setHasOriginalRole(hasOriginalRole);

            // 2.1 添加机构的附加原始角色
            if (hasOriginalRole) {
                List<NameDto> roleInfoList = new ArrayList<>();

                if (orignialUserRole != null && !orignialUserRole.isEmpty()) {
                    for (RoleInfo r : orignialUserRole) {
                        if (!roleInfoList.stream().anyMatch(s -> Objects.equals(s.getId(), r.getId()))) {
                            roleInfoList.add(generateNameDto(r.getId(), r.getName(), RoleSourceEnum.Unknown.value()));
                        }
                    }
                }
                userOrganizationDto.getDimensionUserList()
                        .add(generateDimensionUser(DimensionConstant.OriginalRoleDimensionValueId,
                                DimensionConstant.OriginalRole, hasOriginalRole, isAccessible, roleInfoList, userId,
                                user.getUserName()));
            }
            List<NameDto> roleInfoList1 = new ArrayList<>();

            // 2.2 机构的附加(额外)角色,特殊权限
            List<UserOrgRoleDto> specialOrgRoleList = userOrganizationRoleList.stream()
                    .filter(urd -> Objects.equals(urd.getId(), userOrg.getId())).collect(Collectors.toList());
            if (!specialOrgRoleList.isEmpty()) {
                for (UserOrgRoleDto r : specialOrgRoleList) {
                    if (!roleInfoList1.stream().anyMatch(s -> Objects.equals(s.getId(), r.getId()))) {
                        roleInfoList1
                                .add(generateNameDto(r.getRoleId(), r.getRoleName(), RoleSourceEnum.Unknown.value()));
                    }
                }
                userOrganizationDto.getDimensionUserList()
                        .add(generateDimensionUser(DimensionConstant.ExtraOrgDimensionValueId,
                                DimensionConstant.ExtraOrgDimensionValueName, hasOriginalRole, isAccessible,
                                roleInfoList1, userId, user.getUserName()));
            }
        }
        if (!allIsAccessibleList.isEmpty()) {
            // 这儿的可访问是需要计算的
            userOrganizationDto.setIsAccessible(false);
        } else {
            userOrganizationDto.setIsAccessible(true);
        }
        List<String> roleIdList = new ArrayList<>();
        // 加上权限
        // 维度上的,继承的可访问的
        List<DimensionUser> dimensionRoleList = userOrganizationDto.getDimensionUserList().stream()
                .filter(s -> !DimensionConstant.ExtraOrgDimensionId.equals(s.getDimensionId())
                        && BooleanUtils.isTrue(s.getIsHeritable()) && BooleanUtils.isTrue(s.getIsAccessible()))
                .collect(Collectors.toList());
        for (DimensionUser item : dimensionRoleList) {
            List<String> temp = item.getRoleList().stream().map(NameDto::getId).collect(Collectors.toList());
            roleIdList.addAll(temp);
        }
        // 机构上的,继承的原始的,和附加的
        List<DimensionUser> orgRoleList = userOrganizationDto.getDimensionUserList().stream()
                .filter(s -> DimensionConstant.ExtraOrgDimensionId.equals(s.getDimensionId())
                        && BooleanUtils.isTrue(s.getIsAccessible()))
                .collect(Collectors.toList());
        for (DimensionUser item : orgRoleList) {
            List<String> temp = item.getRoleList().stream().map(NameDto::getId).collect(Collectors.toList());
            roleIdList.addAll(temp);
        }
        roleIdList = roleIdList.stream().distinct().collect(Collectors.toList());
        userOrganizationDto.setPermissionTreeList(permissionService.getIvhTreePermissionsByRoleIdList(roleIdList, "2"));
        return userOrganizationDto;
    }

    private List<UserOrganization> getUserOrganizationList() {
        return myUserMapper.selectUserOrganizationByUserId();
    }

    private OrganizationRoleInfo generateOrganizationRoleInfo(String organizationId, String organizationName,
                                                              String dimensionValueId, String dimensionValueName, Boolean hasOriginalRole, Boolean isAccessible,
                                                              List<RoleInfo> roleInfoList, String userId) {
        OrganizationRoleInfo orgRoleInfo = new OrganizationRoleInfo();
        orgRoleInfo.setId(CommonUtils.getUUID());
        orgRoleInfo.setOrganizationId(organizationId);
        orgRoleInfo.setOrganizationName(organizationName);
        orgRoleInfo.setDimensionId(DimensionConstant.ExtraOrgDimensionId);
        orgRoleInfo.setDimensionName(DimensionConstant.ExtraOrgDimensionName);
        orgRoleInfo.setDimensionValueId(dimensionValueId);
        orgRoleInfo.setDimensionValueName(dimensionValueName);
        orgRoleInfo.setHasOriginalRole(hasOriginalRole);
        orgRoleInfo.setIsAccessible(isAccessible);
        orgRoleInfo.setRoleList(roleInfoList);
        orgRoleInfo.setUserId(userId);
        return orgRoleInfo;
    }

    private DimensionUser generateDimensionUser(String dimensionValueId, String dimensionValueName,
                                                Boolean hasOriginalRole, Boolean isAccessible, List<NameDto> roleInfoList, String userId, String userName) {
        DimensionUser dimensionUser = new DimensionUser();
        dimensionUser.setId(CommonUtils.getUUID());
        dimensionUser.setDimensionId(DimensionConstant.ExtraOrgDimensionId);
        dimensionUser.setDimensionName(DimensionConstant.ExtraOrgDimensionName);// 附加机构的特殊角色
        dimensionUser.setDimensionValueId(dimensionValueId);// 附加原始角色维度值Id
        dimensionUser.setDimensionValueName(dimensionValueName);// 附加原始角色
        dimensionUser.setHasOriginalRole(hasOriginalRole);
        dimensionUser.setIsAccessible(isAccessible);
        dimensionUser.setRoleList(roleInfoList);
        dimensionUser.setUserId(userId);
        dimensionUser.setUserName(userName);
        return dimensionUser;
    }

    private NameDto generateNameDto(String id, String name, Integer roleSource) {
        NameDto roleInfo = new NameDto();
        roleInfo.setId(id);
        roleInfo.setName(name);
        roleInfo.setRoleSource(roleSource);
        return roleInfo;
    }

    private RoleInfo generateRoleInfo(String id, String name, Integer roleSource) {
        RoleInfo roleInfo = new RoleInfo();
        roleInfo.setId(id);
        roleInfo.setName(name);
        roleInfo.setRoleSource(roleSource);
        return roleInfo;
    }

    public List<DimensionRoleDto> getOrgBuAreaIndustryUser(String userId) {
        List<DimensionUser> list = getUserDimensionValueRole(userId);
        return list.stream().map(this::rotateDimensionUserToDimensionRoleDto).collect(Collectors.toList());
    }

    private DimensionRoleDto rotateDimensionUserToDimensionRoleDto(DimensionUser dimensionUser) {
        DimensionRoleDto dimensionRoleDto = CommonUtils.copyProperties(dimensionUser, new DimensionRoleDto());
        List<SimpleRoleDto> simpleRoleDtos = new ArrayList<>();
        if (dimensionUser.getRoleList() != null) {
            simpleRoleDtos = dimensionUser.getRoleList().stream().map(d -> {
                SimpleRoleDto simpleRoleDto = new SimpleRoleDto();
                simpleRoleDto.setRoleId(d.getId());
                simpleRoleDto.setRoleName(d.getName());
                simpleRoleDto.setRoleSource(d.getRoleSource());
                return simpleRoleDto;
            }).collect(Collectors.toList());
        }
        dimensionRoleDto.setRoleList(simpleRoleDtos);
        return dimensionRoleDto;
    }

    private List<DimensionUser> getUserDimensionValueRole(String userId) {
        List<DimensionUser> retlist = new ArrayList<>();
        // 维度的附加角色
        List<UserOrgRoleDto> userDimensionValueRoleList = getUserDimensionValueRoleList();
        // 原始角色
        List<RoleInfo> orignialUserRole = getOriginalRole(userId);
        List<UserRoleDimensionValueDto> diemensionValueList = getUserRoleDimensionValue().stream()
                .filter(x -> userId != null && userId.equals(x.getUserId()))
                .map(this::reserveNecessaryUserRoleDimensionValueDtoFieldForDistinct).distinct()
                .collect(Collectors.toList());
        for (UserRoleDimensionValueDto dv : diemensionValueList) {
            DimensionUser userRole = new DimensionUser();
            List<NameDto> roleInfoList = new ArrayList<>();
            if (dv != null) {
                userRole = CommonUtils.copyProperties(dv, userRole);
                // 2.1 添加原始角色
                if (BooleanUtils.isTrue(dv.getHasOriginalRole()) && orignialUserRole != null
                        && !orignialUserRole.isEmpty()) {
                    for (RoleInfo r : orignialUserRole) {
                        if (!roleInfoList.stream().anyMatch(s -> s.getId() != null && s.getId().equals(r.getId()))) {
                            roleInfoList
                                    .add(generateNameDto(r.getId(), r.getName(), RoleSourceEnum.OriginalLevel.value()));
                        }
                    }
                }
                // 2.2 附加(额外)角色,特殊权限
                List<UserOrgRoleDto> specialOrgRoleList = userDimensionValueRoleList.stream()
                        .filter(urd -> urd.getId() != null && urd.getId().equals(dv.getId()))
                        .collect(Collectors.toList());
                if (!specialOrgRoleList.isEmpty()) {
                    for (UserOrgRoleDto r : specialOrgRoleList) {
                        roleInfoList.add(
                                generateNameDto(r.getRoleId(), r.getRoleName(), RoleSourceEnum.DimensionLevel.value()));
                    }
                }
            }
            userRole.setRoleList(roleInfoList);
            retlist.add(userRole);
        }
        return retlist;
    }

    private UserRoleDimensionValueDto reserveNecessaryUserRoleDimensionValueDtoFieldForDistinct(
            UserRoleDimensionValueDto x) {
        UserRoleDimensionValueDto y = new UserRoleDimensionValueDto();
        y.setId(x.getId());
        y.setIsAccessible(x.getIsAccessible());
        y.setHasOriginalRole(x.getHasOriginalRole());
        y.setDimensionId(x.getDimensionId());
        y.setDimensionName(x.getDimensionName());
        y.setDimensionValueId(x.getDimensionValueId());
        y.setDimensionValueName(x.getDimensionValueName());
        return y;
    }

    private UserRoleDimensionValueDto reserveNecessaryUserOrgRelatedFieldForDistinct(UserRoleDimensionValueDto x) {
        UserRoleDimensionValueDto y = new UserRoleDimensionValueDto();
        y.setId(x.getId());
        y.setIsAccessible(x.getIsAccessible());
        y.setHasOriginalRole(x.getHasOriginalRole());
        y.setDimensionId(x.getDimensionId());
        y.setDimensionValueId(x.getDimensionValueId());
        y.setUserId(x.getUserId());
        y.setUserName(x.getUserName());
        y.setOrganizationId(x.getOrganizationId());
        y.setOrganizationName(x.getOrganizationName());
        return y;
    }

    /**
     * 维度、用户和机构无关的join连接
     */
    private List<UserRoleDimensionValueDto> getUserRoleDimensionValue() {
        // 在Dimension表中,机构层级的DimensionId=c61a5bd6-a996-4952-9869-d053966537e8
        // 在Dimension表中,事业部的DimensionId=c61a5bd6-a996-4952-9869-d053995237e5
        List<DimensionValueOrgDto> basicQuery = myUserMapper
                .selectUserRoleDimensionValueByDimensionId(DimensionConstant.BusinessUnitId);
        List<UserDimensionValue> userRoleDimensionValue = userDimensionValueMapper
                .selectByExample(new UserDimensionValueExample());
        List<UserRoleDimensionValueDto> query = new ArrayList<>();
        for (DimensionValueOrgDto p : basicQuery) {
            List<UserDimensionValue> uList = userRoleDimensionValue.stream()
                    .filter(u -> p.getDimensionId() != null && p.getDimensionId().equals(u.getDimensionId())
                            && p.getDimensionValueId() != null
                            && p.getDimensionValueId().equals(u.getDimensionValueId()))
                    .collect(Collectors.toList());
            if (uList.isEmpty()) {
                query.add(generateUserRoleDimensionValueDto(p, new UserDimensionValue()));
                continue;
            }
            for (UserDimensionValue u : uList) {
                query.add(generateUserRoleDimensionValueDto(p, u));
            }
        }
        return query;
    }

    private UserRoleDimensionValueDto generateUserRoleDimensionValueDto(DimensionValueOrgDto p, UserDimensionValue u) {
        UserRoleDimensionValueDto userRoleDimensionValueDto = new UserRoleDimensionValueDto();
        userRoleDimensionValueDto.setOrganizationId(p.getOrganizationId());
        userRoleDimensionValueDto.setOrganizationName(p.getOrganizationName());
        userRoleDimensionValueDto.setId(Strings.sBlank(u.getId()));
        userRoleDimensionValueDto.setDimensionValueId(Strings.sBlank(u.getDimensionValueId()));
        userRoleDimensionValueDto.setDimensionValueName(p.getDimensionValue());
        userRoleDimensionValueDto.setDimensionId(Strings.sBlank(u.getDimensionId()));
        userRoleDimensionValueDto.setDimensionName(p.getDimensionName());
        userRoleDimensionValueDto.setUserId(Strings.sBlank(u.getUserId()));
        userRoleDimensionValueDto.setIsAccessible(BooleanUtils.isTrue(u.getIsAccessible()));
        userRoleDimensionValueDto.setHasOriginalRole(BooleanUtils.isTrue(u.getHasOriginalRole()));
        return userRoleDimensionValueDto;
    }

    @SuppressWarnings("rawtypes")
    public OperationResultDto enableOrDisableUser(UpdateParam updateParam) {
        logger.debug("UserRoleServiceImpl enableOrDisableUser");
        OperationResultDto operationResultDto = new OperationResultDto();
        try {
            if (updateParam == null || !StringUtils.hasText(updateParam.getUserId())) {
                throw new ApplicationException("primary key can't be null");
            }
            User query = userMapper.selectByPrimaryKey(updateParam.getUserId());
            if (query == null) {
                throw new ApplicationException("can't find user with userId: " + updateParam.getUserId());
            }
            User userOriginal = CommonUtils.copyProperties(query, new User());
            if (UserConstant.DISABLE_TYPE.equals(updateParam.getUpdateType())) {
                query.setStatus(UserStatus.InActive.value());
                UserRoleExample userRoleExample = new UserRoleExample();
                Criteria criteria = userRoleExample.createCriteria();
                criteria.andUserIdEqualTo(updateParam.getUserId());
                criteria.andProjectIdIsNotNull();
                List<UserRole> userRoleList = userRoleMapper.selectByExample(userRoleExample);
                if (!userRoleList.isEmpty()) {
                    operationResultDto.setResult(false);
                    operationResultDto.setResultMsg(UserMessage.ExistsProjectCannotDisable);
                    return operationResultDto;
                }
            } else {
                query.setStatus(UserStatus.Active.value());
            }
            userMapper.updateByPrimaryKey(query);
            updateDataAddLog(userOriginal, query, OperationModule.User.value(), LogMessage.UpdateUser,
                    userOriginal.getUserName(), "operation content", OperateLogType.OperationLogUser.value());
            operationResultDto.setResult(true);
            return operationResultDto;
        } catch (Exception e) {
            logger.error("Error happens: {}", e);
            logger.error("Start to rollback...");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            operationResultDto.setResult(false);
            operationResultDto.setResultMsg(UserMessage.DisableUserFailed);
            return operationResultDto;
        }
    }

    private void updateDataAddLog(Object originalObj, Object updateObj, Integer operationModule, String comment,
                                  String operationObject, String operationContent, Integer logType) {
        UpdateLogParams updateLogParams = new UpdateLogParams();
        updateLogParams.setOperationObject(operationObject);
        updateLogParams.setOriginalState(originalObj);
        updateLogParams.setOperationContent(operationContent);
        updateLogParams.setUpdateState(updateObj);
        updateLogParams.setOperationUser(authUserHelper.getCurrentAuditor().get());
        updateLogParams.setOperationModule(operationModule);
        updateLogParams.setOperationAction(OperationAction.Update.value());
        updateLogParams.setOperateLogType(logType);
        updateLogParams.setComment(comment);
        operationLogService.updateDataAddLog(updateLogParams);
    }

    @SuppressWarnings("rawtypes")
    public OperationResultDto deleteUserRoleOrg(List<UserRoleDimensionValueDto> list) {
        logger.debug("UserRoleServiceImpl deleteUserRoleOrg");
        if (list == null) {
            throw new ApplicationException(CommonConstants.JSONNULLOBJECT);
        }
        OperationResultDto operationResultDto = new OperationResultDto<>();
        UserRoleDimensionValueDto first = list.isEmpty() ? null : list.get(0);
        if (first != null) {
            // 1. 删除机构上
            UserOrganizationExample userOrganizationExample = new UserOrganizationExample();
            pwc.taxtech.atms.entity.UserOrganizationExample.Criteria criteria = userOrganizationExample
                    .createCriteria();
            criteria.andUserIdEqualTo(first.getUserId());
            criteria.andOrganizationIdEqualTo(first.getOrganizationId());
            List<UserOrganization> userOrganizationValueList = userOrganizationMapper
                    .selectByExample(userOrganizationExample);
            for (UserOrganization userOrganization : userOrganizationValueList) {
                logger.debug("Delete user organizaion with id [ {} ]", userOrganization.getId());
                userOrganizationMapper.deleteByPrimaryKey(userOrganization.getId());
            }
            addOrDeleteDataAddLog(getOrgDtoById(first.getOrganizationId()).getName(),
                    getUserDtoById(first.getUserId()).getUserName(), OperationModule.UserOrganization.value(),
                    OperationAction.Delete.value(), "");
        }
        List<UserRoleDimensionValueDto> dimensionList = list.stream()
                .filter(s -> !DimensionConstant.ExtraOrgDimensionId.equals(s.getDimensionId()))
                .collect(Collectors.toList());
        for (UserRoleDimensionValueDto item : dimensionList) {
            // 2.删除维度上的
            updateUserDimensionNonAccess(item);
        }
        operationResultDto.setResult(true);
        return operationResultDto;
    }

    public UserDto getUserDtoById(String userId) {
        User query = userMapper.selectByPrimaryKey(userId);
        return query == null ? new UserDto() : CommonUtils.copyProperties(query, new UserDto());
    }

    public OrganizationDto getOrgDtoById(String orgId) {
        Organization query = organizationMapper.selectByPrimaryKey(orgId);
        return query == null ? new OrganizationDto() : CommonUtils.copyProperties(query, new OrganizationDto());
    }

    private void addOrDeleteDataAddLog(String orgName, String operateUserName, Integer module, Integer action,
                                       String comment) {
        UpdateLogParams updateLogParams = new UpdateLogParams();
        updateLogParams.setComment(comment);
        updateLogParams.setOperateLogType(OperateLogType.OperationLogUser.value());
        updateLogParams.setOperationModule(module);
        updateLogParams.setOperationContent(orgName);
        updateLogParams.setOperationAction(action);
        updateLogParams.setOperationObject(operateUserName);
        updateLogParams.setUpdateState("");
        updateLogParams.setOriginalState("");
        operationLogService.addOrDeleteDataAddLog(updateLogParams);
    }

    /**
     * 机构在维度上的,设置可继承或者不可继承
     */
    @SuppressWarnings("rawtypes")
    public OperationResultDto updateUserDimensionNonAccess(UserRoleDimensionValueDto r) {
        OperationResultDto operationResultDto = new OperationResultDto<>();
        if (r == null) {
            operationResultDto.setResult(true);
            return operationResultDto;
        }
        OrgCustomDto dimension = organizationService.getDimensionValueName(r.getDimensionId(), r.getDimensionValueId());
        String dimensionName = dimension.getDimensionName();
        String dimensionValueName = dimension.getDimensionValueName();
        String operateUserName = getUserDtoById(r.getUserId()).getUserName();
        String orgName = getOrgDtoById(r.getOrganizationId()).getName();

        List<UserDimensionValueOrg> userDimensionValueOrgList = getUserDimensionValueOrgList();
        // 机构在维度上的,设置可继承或者不可继承
        UserDimensionValueExample userDimensionValueExample = new UserDimensionValueExample();
        pwc.taxtech.atms.entity.UserDimensionValueExample.Criteria criteria = userDimensionValueExample
                .createCriteria();
        criteria.andUserIdEqualTo(r.getUserId());
        criteria.andDimensionIdEqualTo(r.getDimensionId());
        criteria.andDimensionValueIdEqualTo(r.getDimensionValueId());
        List<UserDimensionValue> userDimensionList = userDimensionValueMapper
                .selectByExample(userDimensionValueExample);
        for (UserDimensionValue udv : userDimensionList) {
            List<UserDimensionValueOrg> oldList = userDimensionValueOrgList.stream()
                    .filter(p -> udv.getId() != null && udv.getId().equals(p.getUserDimensionValueId())
                            && p.getOrganizationId() != null && p.getOrganizationId().equals(r.getOrganizationId()))
                    .collect(Collectors.toList());
            if (oldList != null && !oldList.isEmpty()) {
                for (UserDimensionValueOrg m : oldList) {
                    UserDimensionValueOrg newObject = CommonUtils.copyProperties(m, new UserDimensionValueOrg());
                    newObject.setIsHeritable(BooleanUtils.isTrue(r.getIsHeritable()));
                    userDimensionValueOrgMapper.updateByPrimaryKey(newObject);

                    // 添加日志
                    updateDataAddLog(m, newObject, OperationModule.UserDimensionValueOrg.value(), "", operateUserName,
                            dimensionName + CommonConstants.DashSignSeparator + dimensionValueName
                                    + CommonConstants.DashSignSeparator + orgName + CommonConstants.DashSignSeparator
                                    + operateUserName,
                            OperateLogType.OperationLogUser.value());
                }
            } else {
                // 没有就添加一条
                UserDimensionValueOrg userRole = new UserDimensionValueOrg();
                userRole.setId(CommonUtils.getUUID());
                userRole.setUserDimensionValueId(udv.getId());
                userRole.setOrganizationId(r.getOrganizationId());
                userRole.setIsHeritable(BooleanUtils.isTrue(r.getIsHeritable()));
                userDimensionValueOrgMapper.insert(userRole);

                // 添加日志
                addOrDeleteDataAddLog(
                        dimensionName + CommonConstants.DashSignSeparator + dimensionValueName
                                + CommonConstants.DashSignSeparator + orgName + CommonConstants.DashSignSeparator
                                + operateUserName,
                        operateUserName, OperationModule.UserDimensionValueOrg.value(), OperationAction.New.value(),
                        "");
            }
        }
        operationResultDto.setResult(true);
        return operationResultDto;
    }

    public List<UserRoleDisplayInfo> getUserRoleByDimensionValueId(String parentDimensionId, String dimensionValueId) {
        List<UserRoleDisplayInfo> retlist = new ArrayList<>();
        // 用户在维度可以添加原始角色,或者附加角色
        List<UserDimensionValue> diemensionValueList = findUserDimensionValueByDimensionRelatedId(parentDimensionId,
                dimensionValueId, null);
        List<UserOrgRoleDto> userDimensionValueRoleList = getUserDimensionValueRoleList();

        for (UserDimensionValue item : diemensionValueList) {
            // 原始角色
            List<RoleInfo> orignialUserRole = getOriginalRole(item.getUserId());
            User userObject = findUserByStatusAndId(UserStatus.Active.value(), item.getUserId());
            String userName = userObject == null ? "" : userObject.getUserName();
            UserRoleDisplayInfo ur = new UserRoleDisplayInfo();
            ur.setUserId(item.getUserId());
            ur.setUserName(userName);
            // 查看是否有不可访问的,不可访问优先
            ur.setIsAccessible(BooleanUtils.isTrue(item.getIsAccessible()));
            ur.setHasOriginalRole(BooleanUtils.isTrue(item.getHasOriginalRole()));

            // 构造每个用户的角色列表
            List<RoleInfo> roleInfoList = new ArrayList<>();
            // 维度的角色,附加的角色
            List<UserOrgRoleDto> extraRole = userDimensionValueRoleList.stream()
                    .filter(p -> p.getId() != null && p.getId().equals(item.getId())).collect(Collectors.toList());
            if (extraRole != null && !extraRole.isEmpty()) {
                for (UserOrgRoleDto r : extraRole) {
                    roleInfoList.add(
                            generateRoleInfo(r.getRoleId(), r.getRoleName(), RoleSourceEnum.DimensionLevel.value()));
                }
            }
            // 添加原始角色
            if (orignialUserRole != null && !orignialUserRole.isEmpty()) {
                for (RoleInfo r : orignialUserRole) {
                    roleInfoList.add(generateRoleInfo(r.getId(), r.getName(), RoleSourceEnum.OriginalLevel.value()));
                }
            }
            ur.setRoleInfoList(roleInfoList);
            retlist.add(ur);
        }
        return retlist;
    }

    public List<UserRoleDisplayInfo> getSpecialUserRoleByDimensionValueId(String parentDimensionId,
                                                                          String dimensionValueId) {
        List<UserRoleDisplayInfo> retlist = new ArrayList<>();
        // 获取特殊角色基本数据
        List<UserRoleDimensionValueDto> basicQuery = getOrgSpecialUserRoleList();

        // 获取某个维度值下面的用户角色
        List<UserRoleDimensionValueDto> dimensionValueList = basicQuery.stream()
                .filter(s -> parentDimensionId != null && parentDimensionId.equals(s.getDimensionId())
                        && dimensionValueId != null && dimensionValueId.equals(s.getDimensionValueId()))
                .collect(Collectors.toList());
        List<UserRoleDimensionValueDto> userRoleList = dimensionValueList.stream()
                .map(this::reserveNecessaryUserOrgRelatedFieldForDistinct).distinct().collect(Collectors.toList());
        List<UserOrgRoleDto> userOrganizationRoleList = getUserOrganizationRoleList();
        // 每个用户可能多个角色
        for (UserRoleDimensionValueDto item : userRoleList) {
            UserRoleDisplayInfo ur = CommonUtils.copyProperties(item, new UserRoleDisplayInfo());
            // 构造每个用户的角色列表
            List<RoleInfo> roleInfoList = new ArrayList<>();
            // 维度的角色,要么是原始角色,要么附加的角色
            List<UserOrgRoleDto> extraRole = userOrganizationRoleList.stream()
                    .filter(p -> p.getId() != null && p.getId().equals(item.getId())).collect(Collectors.toList());
            if (extraRole != null && !extraRole.isEmpty()) {
                for (UserOrgRoleDto r : extraRole) {
                    if (roleInfoList.stream().noneMatch(s -> s.getId() != null && s.getId().equals(r.getRoleId()))) {
                        roleInfoList
                                .add(generateRoleInfo(r.getRoleId(), r.getRoleName(), RoleSourceEnum.Unknown.value()));
                    }
                }
            }

            // 添加原始角色
            if (BooleanUtils.isTrue(ur.getHasOriginalRole())) {
                List<RoleInfo> orignialUserRole = getOriginalRole(item.getUserId());
                if (orignialUserRole != null && !orignialUserRole.isEmpty()) {
                    for (RoleInfo r : orignialUserRole) {
                        if (roleInfoList.stream().noneMatch(s -> s.getId() != null && s.getId().equals(r.getId()))) {
                            roleInfoList.add(generateRoleInfo(r.getId(), r.getName(), RoleSourceEnum.Unknown.value()));
                        }
                    }
                }
            }
            ur.setRoleInfoList(roleInfoList);
            retlist.add(ur);
        }
        return retlist;
    }

    private List<UserRoleDimensionValueDto> getOrgSpecialUserRoleList() {
        List<DimensionValueOrgDto> basicQuery = getDimensionValueOrgDtoList();
        List<Map<String, Object>> userRoleOrganization = myUserMapper.selectUserOrganizationMap();
        List<UserRoleDimensionValueDto> query = new ArrayList<>();
        for (DimensionValueOrgDto p : basicQuery) {
            if (p.getId() == null) {
                continue;
            }
            for (Map<String, Object> utemp : userRoleOrganization) {
                if (p.getId().equals(utemp.get("orgId"))) {
                    UserRoleDimensionValueDto userRoleDimensionValueDto = generateUserRoleDimensionValueDto(p, utemp);
                    userRoleDimensionValueDto.setDimensionValueId(p.getDimensionValueId());
                    userRoleDimensionValueDto.setDimensionId(p.getDimensionId());
                    query.add(userRoleDimensionValueDto);
                }
            }
        }
        return query;
    }

    public List<UserOrgRoleDto> getDimensionUserRoleList(String parentDimensionId, String dimensionValueId) {
        List<DimensionValueOrgDto> orgList = getDimensionValueOrgDtoList().stream()
                .filter(s -> Objects.equals(parentDimensionId, s.getDimensionId())
                        && Objects.equals(dimensionValueId, s.getDimensionValueId()))
                .collect(Collectors.toList());
        List<UserDimensionValue> userDimensionValueList = findUserDimensionValueByDimensionRelatedId(parentDimensionId,
                dimensionValueId, null);
        List<UserDimensionValueOrg> userDimensionValueOrgList = getUserDimensionValueOrgList();
        List<UserOrganization> userOrganizationList = getUserOrganizationList().stream()
                .filter(s -> BooleanUtils.isTrue(s.getIsAccessible())).collect(Collectors.toList());
        // 机构的附加角色
        List<UserOrgRoleDto> userOrganizationRoleList = getUserOrganizationRoleList();

        // 获取原色角色列表
        List<UserOrgRoleDto> originalUserRoleList = getAllOriginalRole();

        // 维度的附加角色
        List<UserOrgRoleDto> userDimensionValueRoleList = getUserDimensionValueRoleList();

        // 维度上的机构
        List<UserRoleDimensionValueDto> dimensionOrgList = new ArrayList<>();
        for (DimensionValueOrgDto p : orgList) {
            for (UserDimensionValue q : userDimensionValueList) {
                if (Objects.equals(p.getDimensionId(), q.getDimensionId())
                        && Objects.equals(p.getDimensionValueId(), q.getDimensionValueId())) {
                    User u = findUserByStatusAndId(UserStatus.Active.value(), q.getUserId());
                    UserRoleDimensionValueDto userRoleDimensionValueDto = new UserRoleDimensionValueDto();
                    if (u != null) {
                        userRoleDimensionValueDto.setUserName(u.getUserName());
                    }
                    userRoleDimensionValueDto.setId(q.getId());
                    userRoleDimensionValueDto.setHasOriginalRole(BooleanUtils.isTrue(q.getHasOriginalRole()));
                    userRoleDimensionValueDto.setIsAccessible(BooleanUtils.isTrue(q.getIsAccessible()));
                    userRoleDimensionValueDto.setUserId(q.getUserId());
                    userRoleDimensionValueDto.setOrganizationId(p.getOrganizationId());
                    userRoleDimensionValueDto.setOrganizationName(p.getOrganizationName());
                    userRoleDimensionValueDto.setDimensionId(p.getDimensionId());
                    userRoleDimensionValueDto.setDimensionName(p.getDimensionName());
                    userRoleDimensionValueDto.setDimensionValueId(p.getDimensionValueId());
                    userRoleDimensionValueDto.setDimensionValueName(p.getDimensionValue());
                    dimensionOrgList.add(userRoleDimensionValueDto);
                }
            }
        }
        List<UserOrgDto> orgNoAccessList = new ArrayList<>();
        List<UserOrgRoleDto> userOrgDtoList = new ArrayList<>();
        // 维度上的机构的用户
        for (UserRoleDimensionValueDto d : dimensionOrgList) {
            // 机构在维度上是否可以被继承,或者被访问
            UserDimensionValueOrg userDimensionValuerOrg = userDimensionValueOrgList.stream()
                    .filter(uvg -> Objects.equals(uvg.getUserDimensionValueId(), d.getId())
                            && Objects.equals(uvg.getOrganizationId(), d.getOrganizationId()))
                    .findFirst().orElse(null);
            // 如果没有设置值,默认可以继承
            boolean isHeritable = userDimensionValuerOrg == null
                    || BooleanUtils.isTrue(userDimensionValuerOrg.getIsHeritable());
            // 任何一个维度上不可访问,且机构继承这个维度,那么这个机构就不可访问
            if (!isHeritable) {
                continue;
            }
            // 用户继承了不可访问的,则这个机构不可访问
            if (isHeritable && !BooleanUtils.isTrue(d.getIsAccessible())
                    && orgNoAccessList.stream().noneMatch(s -> Objects.equals(s.getOrgId(), d.getOrganizationId())
                    && Objects.equals(s.getUserId(), d.getUserId()))) {
                UserOrgDto orgRoleInfo = new UserOrgDto();
                orgRoleInfo.setOrgId(d.getOrganizationId());
                orgRoleInfo.setUserId(d.getUserId());
                orgNoAccessList.add(orgRoleInfo);
                continue;
            }
            // 1.1 继承原始角色
            if (BooleanUtils.isTrue(d.getHasOriginalRole())) {
                // 原始角色
                List<UserOrgRoleDto> orignialUserRole = originalUserRoleList.stream()
                        .filter(s -> Objects.equals(s.getUserId(), d.getUserId())).collect(Collectors.toList());
                for (UserOrgRoleDto r : orignialUserRole) {
                    if (userOrgDtoList.stream()
                            .noneMatch(s -> Objects.equals(s.getOrgId(), d.getOrganizationId())
                                    && Objects.equals(s.getUserId(), d.getUserId())
                                    && Objects.equals(s.getRoleId(), r.getRoleId()))) {
                        userOrgDtoList.add(generateUserOrgRoleDto(d, r));
                    }
                }
            }
            List<UserOrgRoleDto> currentDimensionRoleList = userDimensionValueRoleList.stream()
                    .filter(s -> Objects.equals(s.getId(), d.getId())).collect(Collectors.toList());
            // 1.2 维度的附加角色
            for (UserOrgRoleDto r : currentDimensionRoleList) {
                if (userOrgDtoList.stream()
                        .noneMatch(s -> Objects.equals(s.getOrgId(), d.getOrganizationId())
                                && Objects.equals(s.getUserId(), d.getUserId())
                                && Objects.equals(s.getRoleId(), r.getRoleId()))) {
                    userOrgDtoList.add(generateUserOrgRoleDto(d, r));
                }
            }
        }
        // 移除没有访问权限的维度上的机构
        userOrgDtoList = userOrgDtoList.stream().filter(q -> orgNoAccessList.stream().noneMatch(
                es -> Objects.equals(es.getOrgId(), q.getOrgId()) && Objects.equals(es.getUserId(), q.getUserId())))
                .collect(Collectors.toList());
        // 机构上的用户角色
        List<UserRoleDimensionValueDto> userOrgList = new ArrayList<>();
        for (DimensionValueOrgDto p : orgList) {
            if (p == null || p.getOrganizationId() == null) {
                continue;
            }
            for (UserOrganization q : userOrganizationList) {
                if (p.getOrganizationId().equals(q.getOrganizationId())
                        && orgNoAccessList.stream().noneMatch(es -> Objects.equals(es.getOrgId(), p.getId())
                        && Objects.equals(es.getUserId(), q.getUserId()))) {
                    User u = findUserByStatusAndId(UserStatus.Active.value(), q.getUserId());
                    UserRoleDimensionValueDto userRoleDimensionValueDto = new UserRoleDimensionValueDto();
                    if (u != null) {
                        userRoleDimensionValueDto.setUserName(u.getUserName());
                    }
                    userRoleDimensionValueDto.setId(q.getId());
                    userRoleDimensionValueDto.setHasOriginalRole(BooleanUtils.isTrue(q.getHasOriginalRole()));
                    userRoleDimensionValueDto.setIsAccessible(BooleanUtils.isTrue(q.getIsAccessible()));
                    userRoleDimensionValueDto.setUserId(q.getUserId());
                    userRoleDimensionValueDto.setOrganizationId(p.getOrganizationId());
                    userOrgList.add(userRoleDimensionValueDto);
                }
            }
        }

        for (UserRoleDimensionValueDto userOrg : userOrgList) {
            if (!BooleanUtils.isTrue(userOrg.getIsAccessible())) {
                continue;
            }
            if (BooleanUtils.isTrue(userOrg.getHasOriginalRole())) {
                // 原始角色
                List<UserOrgRoleDto> orignialUserRole = originalUserRoleList.stream()
                        .filter(s -> Objects.equals(s.getUserId(), userOrg.getUserId())).collect(Collectors.toList());
                for (UserOrgRoleDto r : orignialUserRole) {
                    if (userOrgDtoList.stream()
                            .noneMatch(s -> Objects.equals(s.getOrgId(), userOrg.getOrganizationId())
                                    && Objects.equals(s.getUserId(), userOrg.getUserId())
                                    && Objects.equals(s.getRoleId(), r.getRoleId()))) {
                        userOrgDtoList.add(generateUserOrgRoleDto(userOrg, r));
                    }
                }
            }
            List<UserOrgRoleDto> currentOrgRoleList = userOrganizationRoleList.stream()
                    .filter(s -> Objects.equals(s.getId(), userOrg.getId())).collect(Collectors.toList());
            // 1.2 机构的附加角色
            for (UserOrgRoleDto r : currentOrgRoleList) {
                if (userOrgDtoList.stream()
                        .noneMatch(s -> Objects.equals(s.getOrgId(), userOrg.getOrganizationId())
                                && Objects.equals(s.getUserId(), userOrg.getUserId())
                                && Objects.equals(s.getRoleId(), r.getRoleId()))) {
                    userOrgDtoList.add(generateUserOrgRoleDto(userOrg, r));
                }
            }
        }

        return userOrgDtoList;
    }

    private UserOrgRoleDto generateUserOrgRoleDto(UserRoleDimensionValueDto d, UserOrgRoleDto r) {
        UserOrgRoleDto userOrgDto = new UserOrgRoleDto();
        userOrgDto.setUserId(d.getUserId());
        userOrgDto.setUserName(d.getUserName());
        userOrgDto.setOrgId(d.getOrganizationId());
        userOrgDto.setRoleId(r.getRoleId());
        userOrgDto.setRoleName(r.getRoleName());
        return userOrgDto;
    }

    private List<UserDimensionValue> findUserDimensionValueByDimensionRelatedId(String parentDimensionId,
                                                                                String dimensionValueId, String userId) {
        UserDimensionValueExample userDimensionValueExample = new UserDimensionValueExample();
        pwc.taxtech.atms.entity.UserDimensionValueExample.Criteria criteria = userDimensionValueExample
                .createCriteria();
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        criteria.andDimensionIdEqualTo(parentDimensionId);
        criteria.andDimensionValueIdEqualTo(dimensionValueId);
        return userDimensionValueMapper.selectByExample(userDimensionValueExample);
    }

    private List<UserOrgRoleDto> getAllOriginalRole() {
        return myUserMapper.selectUserOrgRoleDto();
    }

    private User findUserByStatusAndId(Integer status, String userId) {
        UserExample userExample = new UserExample();
        pwc.taxtech.atms.entity.UserExample.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andStatusEqualTo(status);
        userCriteria.andIdEqualTo(userId);
        List<User> users = userMapper.selectByExample(userExample);
        return users.isEmpty() ? null : users.get(0);
    }

    /**
     * 添加事业部的值的权限(其他维度也一样) 可继承原始角色,可添加附加角色 原始角色写在标记HasOriginalRole
     * 附加角色写在角色关联表UserDimensionValueRole
     */
    @SuppressWarnings("rawtypes")
    public OperationResultDto updateUserRoleDimension(List<UserRoleDimensionValueDto> userRoleList) {
        logger.debug("UserRoleServiceImpl updateUserRoleDimension");
        if (userRoleList == null) {
            throw new ApplicationException(CommonConstants.JSONNULLOBJECT);
        }
        OperationResultDto operationResultDto = new OperationResultDto<>();
        if (userRoleList.isEmpty()) {
            operationResultDto.setResult(true);
            return operationResultDto;
        }
        UserRoleDimensionValueDto first = userRoleList.get(0);
        // 删除用户维度的角色
        UserDimensionValue userDimensionValue = findUserDimensionValueByDimensionRelatedId(first.getDimensionId(),
                first.getDimensionValueId(), first.getUserId()).stream().findFirst().orElse(null);
        if (userDimensionValue == null) {
            throw new ApplicationException("UserDimensionValue cannot be found.");
        }
        UserDimensionValue old = CommonUtils.copyProperties(userDimensionValue, new UserDimensionValue());
        OrgCustomDto dimension = organizationService.getDimensionValueName(first.getDimensionId(),
                first.getDimensionValueId());
        if (dimension == null) {
            throw new ApplicationException("OrgCustomDto cannot be found.");
        }
        String dimensionName = dimension.getDimensionName();
        String dimensionValueName = dimension.getDimensionValueName();
        String operateUserName = getUserDtoById(first.getUserId()).getUserName();
        // 删除某个维度值下面的所有附加角色
        List<UserDimensionValueRole> target = findUserDimensionValueRoleByUserDimensionValueId(
                userDimensionValue.getId());
        for (UserDimensionValueRole ou : target) {
            logger.debug("Start to delete userDimensionValueRole [ {} ]", ou.getId());
            userDimensionValueRoleMapper.deleteByPrimaryKey(ou.getId());
        }
        // 添加日志
        for (UserDimensionValueRole r : target) {
            Role role = roleMapper.selectByPrimaryKey(r.getRoleId());
//            Role role = roleData.selectByPrimaryKey(r.getRoleId());
            String roleName = role == null ? "" : role.getName();
            addOrDeleteDataAddLog(
                    dimensionName + CommonConstants.DashSignSeparator + dimensionValueName
                            + CommonConstants.DashSignSeparator + operateUserName + CommonConstants.DashSignSeparator
                            + roleName,
                    operateUserName, OperationModule.UserDimensionValueRole.value(), OperationAction.Delete.value(),
                    "");
        }
        // 更新用户维度角色
        userDimensionValue.setIsAccessible(BooleanUtils.isTrue(first.getIsAccessible()));
        userDimensionValue.setHasOriginalRole(BooleanUtils.isTrue(first.getHasOriginalRole()));
        logger.debug("Start to update userDimensionValue [ {} ]", userDimensionValue.getId());
        userDimensionValueMapper.updateByPrimaryKey(userDimensionValue);
        // 添加日志
        updateDataAddLog(old, userDimensionValue, OperationModule.BasicDataDimensionValue.value(),
                LogMessage.UpdateDimensionValue, operateUserName, dimensionName + CommonConstants.DashSignSeparator
                        + dimensionValueName + CommonConstants.DashSignSeparator + operateUserName,
                OperateLogType.OperationLogUser.value());
        // 添加选中的附加角色
        for (UserRoleDimensionValueDto item : userRoleList) {
            if (BooleanUtils.isTrue(item.getIsAdd())) {
                UserDimensionValueRole userRole = new UserDimensionValueRole();
                userRole.setId(CommonUtils.getUUID());
                userRole.setUserDimensionValueId(userDimensionValue.getId());
                userRole.setRoleId(item.getRoleId());
                logger.debug("Start to insert userDimensionValueRole [ {} ] with userDimensionValueId [ {} ]",
                        userRole.getId(), userDimensionValue.getId());
                userDimensionValueRoleMapper.insert(userRole);
                // 添加日志
                String roleName = getRoleDtoById(item.getRoleId()).getName();
                addOrDeleteDataAddLog(
                        dimensionName + CommonConstants.DashSignSeparator + dimensionValueName
                                + CommonConstants.DashSignSeparator + operateUserName
                                + CommonConstants.DashSignSeparator + roleName,
                        operateUserName, OperationModule.UserDimensionValueRole.value(), OperationAction.New.value(),
                        "");
            }
        }
        operationResultDto.setResult(true);
        return operationResultDto;
    }

    private List<UserDimensionValueRole> findUserDimensionValueRoleByUserDimensionValueId(String userDimensionValueId) {
        UserDimensionValueRoleExample userDimensionValueRoleExample = new UserDimensionValueRoleExample();
        userDimensionValueRoleExample.createCriteria().andUserDimensionValueIdEqualTo(userDimensionValueId);
        return userDimensionValueRoleMapper.selectByExample(userDimensionValueRoleExample);
    }

    private RoleDto getRoleDtoById(String roleId) {
        Role query = roleMapper.selectByPrimaryKey(roleId);
//        Role query = roleData.selectByPrimaryKey(roleId);
        return query == null ? new RoleDto() : CommonUtils.copyProperties(query, new RoleDto());
    }

    /**
     * 机构用户权限编辑 添加删除原始角色 添加删除额外角色 机构上,修改可访问还是不可访问
     */
    @SuppressWarnings("rawtypes")
    public OperationResultDto updateUserRoleOrganization(List<UserRoleDimensionValueDto> userRoleList) {
        UserRoleDimensionValueDto first = userRoleList.stream().findFirst().orElse(null);
        OperationResultDto operationResultDto = new OperationResultDto();
        if (first == null) {
            operationResultDto.setResult(true);
            return operationResultDto;
        }
        String orgName = getOrgDtoById(first.getOrganizationId()).getName();
        String operateUserName = getUserDtoById(first.getUserId()).getUserName();
        // 编辑用户机构的角色
        UserOrganizationExample userOrganizationExample = new UserOrganizationExample();
        pwc.taxtech.atms.entity.UserOrganizationExample.Criteria criteria = userOrganizationExample.createCriteria();
        criteria.andUserIdEqualTo(first.getUserId());
        criteria.andOrganizationIdEqualTo(first.getOrganizationId());
        UserOrganization userOrganizationValue = userOrganizationMapper.selectByExample(userOrganizationExample)
                .stream().findFirst().orElse(null);
        String userOrgId = null;
        if (userOrganizationValue != null) {
            userOrgId = userOrganizationValue.getId();
            // 删除某个机构下面的所有附加角色
            UserOrganizationRoleExample userOrganizationRoleExample = new UserOrganizationRoleExample();
            userOrganizationRoleExample.createCriteria().andUserOrganizationIdEqualTo(userOrganizationValue.getId());
            List<UserOrganizationRole> target = userOrganizationRoleMapper.selectByExample(userOrganizationRoleExample);
            if (target != null && !target.isEmpty()) {
                for (UserOrganizationRole r : target) {
                    logger.debug("Start to delete UserOrganizationRole [ {} ]", r.getId());
                    userOrganizationRoleMapper.deleteByPrimaryKey(r.getId());

                    // 添加日志
                    Role role = roleMapper.selectByPrimaryKey(r.getRoleId());
//                    Role role = roleData.selectByPrimaryKey(r.getRoleId());
                    String roleName = role == null ? "" : role.getName();
                    addOrDeleteDataAddLog(orgName + CommonConstants.DashSignSeparator + roleName, operateUserName,
                            OperationModule.UserOrganizationRole.value(), OperationAction.Delete.value(), "");
                }

            }
            UserOrganization old = CommonUtils.copyProperties(userOrganizationValue, new UserOrganization());
            // 更新用户机构角色
            userOrganizationValue.setIsAccessible(BooleanUtils.isTrue(first.getIsAccessible()));
            userOrganizationValue.setHasOriginalRole(BooleanUtils.isTrue(first.getHasOriginalRole()));
            logger.debug("Start to update userOrganizationValue [ {} ]", userOrganizationValue.getId());
            userOrganizationMapper.updateByPrimaryKey(userOrganizationValue);
            // 添加日志
            updateDataAddLog(old, userOrganizationValue, OperationModule.UserOrganization.value(), "", operateUserName,
                    orgName + CommonConstants.DashSignSeparator + operateUserName,
                    OperateLogType.OperationLogUser.value());

        } else {
            userOrgId = CommonUtils.getUUID();
            // 没有数据,则插入一条
            UserOrganization userRole = new UserOrganization();
            userRole.setId(userOrgId);
            userRole.setUserId(first.getUserId());
            userRole.setOrganizationId(first.getOrganizationId());
            userRole.setIsAccessible(BooleanUtils.isTrue(first.getIsAccessible()));
            userRole.setHasOriginalRole(BooleanUtils.isTrue(first.getHasOriginalRole()));

            userOrganizationMapper.insert(userRole);
            // 添加日志
            addOrDeleteDataAddLog(orgName + CommonConstants.DashSignSeparator + operateUserName, operateUserName,
                    OperationModule.UserOrganization.value(), OperationAction.New.value(), "");
        }
        // 添加选中的附加角色
        for (UserRoleDimensionValueDto item : userRoleList) {
            if (item.getRoleId() != null) {
                UserOrganizationRole userRole = new UserOrganizationRole();
                userRole.setId(CommonUtils.getUUID());
                userRole.setUserOrganizationId(userOrgId);
                userRole.setRoleId(item.getRoleId());
                logger.debug("Start to insert user organization role [ {} ] with roleId [ {} ]", userRole.getId(),
                        userRole.getRoleId());
                userOrganizationRoleMapper.insert(userRole);
                // 添加日志
                Role roleObject = roleMapper.selectByPrimaryKey(item.getRoleId());
//                Role roleObject = roleData.selectByPrimaryKey(item.getRoleId());
                String roleName = roleObject == null ? "" : roleObject.getName();
                addOrDeleteDataAddLog(orgName + CommonConstants.DashSignSeparator + roleName, operateUserName,
                        OperationModule.UserOrganizationRole.value(), OperationAction.New.value(), "");
            }
        }
        operationResultDto.setResult(true);
        return operationResultDto;
    }

    /**
     * 为维度删除权限用户
     */
    @SuppressWarnings("rawtypes")
    public OperationResultDto deleteUserRoleDimension(List<UserRoleDimensionValueDto> userRoleList) {
        logger.debug("UserRoleServiceImpl deleteUserRoleDimension");
        if (userRoleList.isEmpty()) {
            throw new ApplicationException(CommonConstants.JSONNULLOBJECT);
        }

        for (UserRoleDimensionValueDto userRoleDimensionValue : userRoleList) {
            // 删除用户与维度的关联
            OperationResultDto operationResultDto = new OperationResultDto();
            UserDimensionValueExample userDimensioValueExample = new UserDimensionValueExample();
            userDimensioValueExample.createCriteria().andUserIdEqualTo(userRoleDimensionValue.getUserId())
                    .andDimensionIdEqualTo(userRoleDimensionValue.getDimensionId())
                    .andDimensionValueIdEqualTo(userRoleDimensionValue.getDimensionValueId());
            List<UserDimensionValue> userDimensionValueList = userDimensionValueMapper
                    .selectByExample(userDimensioValueExample);
            UserDimensionValue firstUserDimensionValue = userDimensionValueList.isEmpty() ? null
                    : userDimensionValueList.get(0);
            if (firstUserDimensionValue == null) {
                operationResultDto.setResult(true);
                return operationResultDto;
            }

            OrgCustomDto dimension = organizationService.getDimensionValueName(firstUserDimensionValue.getDimensionId(),
                    firstUserDimensionValue.getDimensionValueId());
            String dimensionName = dimension.getDimensionName();
            String dimensionValueName = dimension.getDimensionValueName();
            String operateUserName = getUserDtoById(firstUserDimensionValue.getUserId()).getUserName();
            String userDimensionValueId = firstUserDimensionValue.getId();

            // 存在则删除 用户在这个维度
            deleteUserDimensionValueList(userDimensionValueList);

            // 添加日志
            userDimensionValueList.forEach(a -> {
                UpdateLogParams updateLogParams = new UpdateLogParams();
                updateLogParams.setOperateLogType(OperateLogType.OperationLogUser.value());
                updateLogParams.setOperationModule(OperationModule.UserDimensionValue.value());
                updateLogParams.setOperationContent(dimensionName + CommonConstants.DashSignSeparator + dimensionName
                        + CommonConstants.DashSignSeparator + operateUserName);
                updateLogParams.setOperationAction(OperationAction.Delete.value());
                updateLogParams.setOperationObject(operateUserName);
                operationLogService.addOrDeleteDataAddLog(updateLogParams);
            });

            // 删除附加维度
            UserDimensionValueRoleExample userDimensionValueRoleExample = new UserDimensionValueRoleExample();
            userDimensionValueRoleExample.createCriteria().andUserDimensionValueIdEqualTo(userDimensionValueId);
            List<UserDimensionValueRole> userDimensionValueRoleList = userDimensionValueRoleMapper
                    .selectByExample(userDimensionValueRoleExample);
            deleteUserDimensionValueRoleList(userDimensionValueRoleList);

            // 添加日志
            userDimensionValueRoleList.forEach(a -> {
                String roleName = getRoleDtoById(a.getRoleId()).getName();
                UpdateLogParams updateLogParams = new UpdateLogParams();
                updateLogParams.setOperateLogType(OperateLogType.OperationLogUser.value());
                updateLogParams.setOperationModule(OperationModule.UserDimensionValueRole.value());
                updateLogParams.setOperationContent(dimensionName + CommonConstants.DashSignSeparator
                        + dimensionValueName + CommonConstants.DashSignSeparator + operateUserName
                        + CommonConstants.DashSignSeparator + roleName);
                updateLogParams.setOperationAction(OperationAction.Delete.value());
                updateLogParams.setOperationObject(operateUserName);
                operationLogService.addOrDeleteDataAddLog(updateLogParams);
            });
        }
        OperationResultDto operationResultDto = new OperationResultDto();
        operationResultDto.setResult(true);
        return operationResultDto;
    }

    private void deleteUserDimensionValueRoleList(List<UserDimensionValueRole> userDimensionValueRoleList) {
        if (!userDimensionValueRoleList.isEmpty()) {
            userDimensionValueRoleList.forEach(a -> {
                UserDimensionValueRoleExample example = new UserDimensionValueRoleExample();
                example.createCriteria().andUserDimensionValueIdEqualTo(a.getUserDimensionValueId());
                userDimensionValueRoleMapper.deleteByExample(example);
            });
        }
    }

    private void deleteUserDimensionValueList(List<UserDimensionValue> userDimensionValueList) {
        if (!userDimensionValueList.isEmpty()) {
            userDimensionValueList.forEach(a -> {
                UserDimensionValueExample example = new UserDimensionValueExample();
                example.createCriteria().andUserIdEqualTo(a.getUserId()).andDimensionIdEqualTo(a.getDimensionId())
                        .andDimensionValueIdEqualTo(a.getDimensionValueId());
                userDimensionValueMapper.deleteByExample(example);
            });
        }
    }

    // 给维度(事业部)添加用户
    public OperationResultDto<?> updateUserRoleForDimension(List<UserRoleDimensionValueDto> userRoleList) {
        logger.debug("UserRoleServiceImpl updateUserRoleForDimension");
        if (userRoleList.isEmpty()) {
            throw new ApplicationException(CommonConstants.JSONNULLOBJECT);
        }

        for (UserRoleDimensionValueDto item : userRoleList) {
            UserDimensionValueExample userDimensioValueExample = new UserDimensionValueExample();
            userDimensioValueExample.createCriteria().andUserIdEqualTo(item.getUserId())
                    .andDimensionIdEqualTo(item.getDimensionId())
                    .andDimensionValueIdEqualTo(item.getDimensionValueId());
            List<UserDimensionValue> userDimensionValueList = userDimensionValueMapper
                    .selectByExample(userDimensioValueExample);
            // 如果已经存在,则不再添加了
            if (userDimensionValueList.isEmpty()) {
                UserDimensionValue userDimensionValue = new UserDimensionValue();
                userDimensionValue.setId(CommonUtils.getUUID());
                userDimensionValue.setDimensionId(item.getDimensionId());
                userDimensionValue.setDimensionValueId(item.getDimensionValueId());
                userDimensionValue.setUserId(item.getUserId());
                boolean isAccessible = BooleanUtils.isTrue(item.getIsAccessible());
                userDimensionValue.setIsAccessible(isAccessible);
                boolean hasOriginalRole = BooleanUtils.isTrue(item.getHasOriginalRole());
                userDimensionValue.setHasOriginalRole(hasOriginalRole);
                userDimensionValueMapper.insert(userDimensionValue);

                // 添加日志
                OrgCustomDto dimension = organizationService.getDimensionValueName(item.getDimensionId(),
                        item.getDimensionValueId());
                String dimensionName = dimension.getDimensionName();
                String dimensionValueName = dimension.getDimensionValueName();
                String operateUserName = getUserDtoById(item.getUserId()).getUserName();

                UpdateLogParams updateLogParams = new UpdateLogParams();
                updateLogParams.setComment(LogMessage.AddUserForDimensionValue);
                updateLogParams.setOperateLogType(OperateLogType.OperationLogUser.value());
                updateLogParams.setOperationModule(OperationModule.UserDimensionValue.value());
                updateLogParams.setOperationContent(dimensionName + CommonConstants.DashSignSeparator
                        + dimensionValueName + CommonConstants.DashSignSeparator + operateUserName);
                updateLogParams.setOperationAction(OperationAction.New.value());
                updateLogParams.setOperationObject(operateUserName);
                operationLogService.addOrDeleteDataAddLog(updateLogParams);
            }
        }
        OperationResultDto<?> operationResultDto = new OperationResultDto<>();
        operationResultDto.setResult(true);
        return operationResultDto;
    }

    @SuppressWarnings("rawtypes")
    public OperationResultDto updateUserRoleForOrg(List<UserRoleDimensionValueDto> userRoleList) {
        if (userRoleList == null) {
            throw new ApplicationException(CommonConstants.JSONNULLOBJECT);
        }
        for (UserRoleDimensionValueDto item : userRoleList) {
            List<UserOrganization> query = userService.findUserOrganizationByUserIdAndOrganizationId(item.getUserId(),
                    item.getOrganizationId());
            User user = userMapper.selectByPrimaryKey(item.getUserId());
            Organization organization = organizationMapper.selectByPrimaryKey(item.getOrganizationId());
            String operateUserName = user == null ? "" : user.getUserName();
            String orgName = organization == null ? "" : organization.getName();
            // 如果已经存在,则不再添加了
            if (query == null || query.isEmpty()) {
                UserOrganization ur = new UserOrganization();
                ur.setId(CommonUtils.getUUID());
                ur.setOrganizationId(item.getOrganizationId());
                ur.setUserId(item.getUserId());
                ur.setIsAccessible(BooleanUtils.isTrue(item.getIsAccessible()));
                ur.setHasOriginalRole(BooleanUtils.isTrue(item.getHasOriginalRole()));
                logger.debug("Start to insert UserOrganization [ {} ]", ur.getId());
                userOrganizationMapper.insert(ur);
                // 添加日志
                addOrDeleteDataAddLog(orgName + CommonConstants.DashSignSeparator + operateUserName, operateUserName,
                        OperationModule.UserOrganization.value(), OperationAction.New.value(),
                        LogMessage.AddUserForOrganization);
            } else {
                UserOrganization first = query.stream().findFirst().orElse(null);
                if (first != null) {
                    if (BooleanUtils.isFalse(first.getIsAccessible())) {
                        first.setIsAccessible(CommonConstants.IsAccessible);
                    }
                    if (BooleanUtils.isFalse(first.getHasOriginalRole())) {
                        first.setHasOriginalRole(CommonConstants.HasOriginalRole);
                    }
                    logger.debug("Start to update UserOrganization [ {} ]", first.getId());
                    userOrganizationMapper.updateByPrimaryKey(first);
                    // 添加日志
                    addOrDeleteDataAddLog(orgName + CommonConstants.DashSignSeparator + operateUserName,
                            operateUserName, OperationModule.UserOrganization.value(), OperationAction.New.value(),
                            LogMessage.AddUserForOrganization);
                }
            }
        }
        OperationResultDto operationResultDto = new OperationResultDto();
        operationResultDto.setResult(true);
        return operationResultDto;
    }

    /**
     * 在某个机构下面,删除用户(特殊权限和继承的权限),如果是特殊权限,直接删除权限机构的数据, 如果是继承维度的权限,将继承的维度设置为不可继承
     */
    @SuppressWarnings("rawtypes")
    public OperationResultDto deleteUserRoleByOrgId(UserOrgDto userDto) {
        logger.debug("enter UserRoleServiceImpl");
        if (userDto == null) {
            throw new ApplicationException(CommonConstants.JSONNULLOBJECT);
        }

        OperationResultDto result = null;

        // 删除用户与机构上的角色
        UserOrganizationExample example = new UserOrganizationExample();
        example.createCriteria().andOrganizationIdEqualTo(userDto.getOrgId()).andUserIdEqualTo(userDto.getUserId());
        List<UserOrganization> target = userOrganizationMapper.selectByExample(example);
        UserOrganization first = target.stream().findFirst().orElse(null);
        if (first == null) {
            result = new OperationResultDto<>();
            result.setResult(true);
            return result;
        }

        target.forEach(a -> {
            userOrganizationMapper.deleteByPrimaryKey(a.getId());
        });

        String userOrganizationId = first.getId();
        // 机构上的附加角色
        UserOrganizationRoleExample userOrganizationRoleExample = new UserOrganizationRoleExample();
        userOrganizationRoleExample.createCriteria().andUserOrganizationIdEqualTo(userOrganizationId);
        List<UserOrganizationRole> userOrganizationRole = userOrganizationRoleMapper
                .selectByExample(userOrganizationRoleExample);

        userOrganizationRole.forEach(a -> {
            userOrganizationRoleMapper.deleteByPrimaryKey(a.getId());
        });

        // 用户在所有机构继承维度上,设置成不可继承
        UserDimensionValueExample userDimensionValueExample = new UserDimensionValueExample();
        userDimensionValueExample.createCriteria().andUserIdEqualTo(userDto.getUserId());
        List<UserDimensionValue> userDimensionValue = userDimensionValueMapper
                .selectByExample(userDimensionValueExample);
        userDimensionValue.forEach(a -> {
            // 机构上继承的维度
            UserDimensionValueOrgExample userDimensionValueOrgExample = new UserDimensionValueOrgExample();
            userDimensionValueOrgExample.createCriteria().andOrganizationIdEqualTo(userOrganizationId)
                    .andUserDimensionValueIdEqualTo(a.getId());
            List<UserDimensionValueOrg> inheritDimensionList = userDimensionValueOrgMapper
                    .selectByExample(userDimensionValueOrgExample);
            inheritDimensionList.forEach(b -> {
                b.setIsHeritable(CommonConstants.DEACTIVE_STATUS);// 设置为不可继承
                userDimensionValueOrgMapper.updateByPrimaryKey(b);
            });
        });

        result = new OperationResultDto<>();
        result.setResult(true);
        return result;
    }

    public UserDto GetUserByUserName(UserDto userParam) {
        return userService.getUserByDto(userParam);
    }
}