role-manage.ctrl.js 37 KB
Newer Older
eddie.woo's avatar
eddie.woo 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
infrastructureModule
.controller('RoleManageController', ['$scope', '$log', '$translate', 'roleService', 'risDialog', 'permissionService', '$state', '$q', '$timeout',
    'menuService', 'uiGridConstants', 'SweetAlert', 'userService',
    function ($scope, $log, $translate, roleService, risDialog, permissionService, $state, $q, $timeout, menuService,
         uiGridConstants, SweetAlert, userService) {
        'use strict';

        $scope.open = false;
        $scope.openRolePanel = false;
        $scope.serviceType = constant.serviceType.VAT;

        $scope.validateOnServer = function (newValue, role) {

            $scope.editRole = role;

            var defer = $q.defer();

            //check duplication name
            var nodeListWithoutCurrentOne = _.without($scope.roleList, role);
            var IsFindExistOne = _.find(nodeListWithoutCurrentOne, function (item) {
                return item.name === newValue.trim();
            });

            if (IsFindExistOne) {
                SweetAlert.warning($translate.instant('hasDuplicateRoleCategory'));
                defer.reject();
            }
            else if (newValue.trim() === '') {
                SweetAlert.warning($translate.instant('roleCategoryNameEmptyWarn'));
                defer.reject();
            }
            else if (newValue.trim().length > 50) {
                SweetAlert.warning($translate.instant('roleCategoryName50Warn'));
                defer.reject();
            }
            else {

                $scope.updateRoleCategory(newValue.trim());
                defer.resolve();
            }

            return defer.promise;
        };

        $scope.updateRoleCategory = function (updateName) {
            $scope.editRole.name = updateName;
            console.log($scope.editRole);

            var roleCategoryID = $scope.editRole.id == undefined ? $scope.editRole.roleCategoryID : $scope.editRole.id;

            roleService.updateRoleCategory(updateName, roleCategoryID).success(function (data) {
                SweetAlert.success($translate.instant('updateRoleCategoryTitle'), $translate.instant('updateRoleCategorySuccess'));
            });
        };

        //添加用户,弹框,call指令 add-exist-user-modal
        $scope.addUser = function () {
            var selectedKeyItem = [];

            $scope.nameList.forEach(function (row) {
                selectedKeyItem.push(row.userID);
            });
            $scope.addUserOperateType = constant.Operation.Add;
            $scope.addUserIsUpdate = false;
            $scope.selectedKeyItems = selectedKeyItem.length == 0 ? [''] : selectedKeyItem;
        };

        //如果添加了用户,则写入该维度下的库
        $scope.$watch('addUserIsUpdate', function (newValue, oldValue) {
            if (newValue) {
                if ($scope.selectedUserList && $scope.selectedUserList.length > 0) {
                    console.log(JSON.stringify($scope.selectedUserList));
                    addUsersToRole($scope.selectedUserList);
                }
            }
        });

        //为当前维度添加用户
        var addUsersToRole = function (selectedUserArray) {

            var userIdList = _.map($scope.nameList, function (item) { return item.userID; });
            var selectedUserIdList = _.map(selectedUserArray, function (item) { return item.userID; });

            var addedUserList = [];
            selectedUserIdList.forEach(function (item) {
                if (userIdList.indexOf(item) < 0) {
                    addedUserList.push(item);
                }
            });

            var updatedModel = {
                userIdList: addedUserList,
                serviceTypeID: $scope.serviceType,
                roleID: $scope.selectedRole.id
            };

            if (addedUserList && addedUserList.length > 0) {
                userService.updateUserToRole(updatedModel).success(function (data) {
                    if (data) {
                        showSuccessMsg("SaveSuccess");
                        //刷新角色列表
                        getUsersByRoleID($scope.selectedRole.id);
                    }
                });
            }
        };

        var showSuccessMsg = function (resultMsg) {

            var errMsg = $translate.instant(resultMsg);
            SweetAlert.success(errMsg);
        };

        //删除用户
        $scope.removeUser = function (user) {
            var roleID = user.roleID;
            var userID = user.userID;
            var userName = user.userName;

            SweetAlert.swal({
                title: $translate.instant('ConfirmDelete') + '?',
                text: $translate.instant('UserDeleteConfirm') + ' - ' + userName + '?',
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: $translate.instant('Confirm'),
                cancelButtonText: $translate.instant('Cancel'),
                closeOnConfirm: false,
                closeOnCancel: true
            }, function (isConfirm) {
                if (isConfirm) {

                    var roleIDList = [];
                    roleIDList.push(roleID);

                    roleService.removeUserRole(userID, roleIDList, $scope.serviceType).success(function (data) {
                        $scope.nameList = _.without($scope.nameList, _.find($scope.nameList, function (item) {
                            return item.userID === userID
                        }));
                        SweetAlert.success($translate.instant('deleteUserRole'), $translate.instant('deleteUserSuccess'));
                    });
                }
            });
        };

        //获取当前角色对应的权限列表
        var loadPermissionTree = function () {
            $scope.permissionTreeViewOptions = {
                bindingOptions: {
                    dataSource: 'permissionTreeViewData',
                    searchValue: 'searchValue',
                    expandAllEnabled: 'expandAll'
                },
                dataStructure: "plain",
                selection: {
                    mode: "single"
                },
                loadPanel: {
                    enabled: true
                },
                scrolling: {
                    mode: "virtual"
                },
                keyExpr: "id",
                showRowLines: true,
                showColumnLines: true,
                rowAlternationEnabled: true,
                showBorders: true,
                selectAllText: $translate.instant('SelectAll'),
                scrollDirection: 'vertical',  //Accepted Values: 'vertical' | 'horizontal' | 'both'
                selectNodesRecursive: true,  //级联选择
                //showCheckBoxesMode: 'selectAll', //Accepted Values: 'none' | 'normal' | 'selectAll'
                noDataText: $translate.instant('NoDataText'),
            };
        };

        //获取所有的权限
        var breakFlag = false;
        var loadAllPermissionTree = function () {
            $scope.allPermissionTreeViewOptions = {
                bindingOptions: {
                    dataSource: 'allPermissionTreeViewData',
                    searchValue: 'searchValue',
                    expandAllEnabled: 'expandAll'
                },
                dataStructure: "plain",
                selection: {
                    mode: "multiple"
                },
                loadPanel: {
                    enabled: true
                },
                scrolling: {
                    mode: "virtual"
                },
                keyExpr: "id",
                showRowLines: true,
                showColumnLines: true,
                rowAlternationEnabled: true,
                showBorders: true,
                selectAllText: $translate.instant('SelectAll'),
                scrollDirection: 'vertical',  //Accepted Values: 'vertical' | 'horizontal' | 'both'
                selectNodesRecursive: true,  //级联选择
                showCheckBoxesMode: 'selectAll',  //Accepted Values: 'none' | 'normal' | 'selectAll'
                onInitialized: function (e) {
                    $scope.widgetInstance = e.component;
                    // $scope.widgetInstance.selectItem($scope.itemElement.id);
                },
                onItemSelectionChanged: function (e) {
                    var node = e.node;
                    var relyOnCodesStr = node.itemData.relyOnCodes;
                    if (relyOnCodesStr !== null && relyOnCodesStr !== undefined) {
                        var relyOnCodesArray = relyOnCodesStr.split(',');
                        if (relyOnCodesArray && relyOnCodesArray.length > 0) {

                            //提取出统一层级的属性为数组
                            var relyOnCodeList = _.map(node.parent.children, function (item) {
                                return {
                                    'key': item.key,
                                    'code': item.itemData.relyOnCodes,
                                    'selected': item.itemData.selected
                                };
                            });

                            node.parent.children.forEach(function (child) {

                                if (!node.selected) {
                                    var filtered = _.filter(relyOnCodeList, function (item) {
                                        return item.code == child.itemData.code && item.selected !== node.selected;
                                    });

                                    if (filtered && filtered.length >= 0) return;
                                }

                                //https://www.devexpress.com/Support/Center/Question/Details/T499903/treeview-selectitem-method-not-working
                                if (relyOnCodesArray.indexOf(child.itemData.code) >= 0) {
                                    if (node.selected) {
                                        $scope.widgetInstance.selectItem(child.key);
                                    }
                                    else {
                                        $scope.widgetInstance.unselectItem(child.key);
                                    }
                                }
                            });
                        }
                    } else {

                        if (node.selected) return;

                        //比如手动取消查看的权限,那么此时修改等权限也应该做相应的改动
                        var codeList = _.map(node.parent.children, function (item) {
                            return {
                                'key': item.key,
                                'selected': item.selected,
                                'relyOnCodes': item.itemData.relyOnCodes
                            };
                        });

                        var filtered = _.filter(codeList, function (item) {
                            return item.relyOnCodes !== null && item.relyOnCodes.indexOf(node.itemData.code) >= 0 && item.selected == true;
                        });

                        //unchecked 
                        _.each(filtered, function (item) {
                            $scope.widgetInstance.unselectItem(item.key);
                        });
                    }
                }
            };
        };

        $scope.searchOptions = {
            bindingOptions: {
                value: "searchValue"
            },
            placeholder: $translate.instant('Search'),
            width: '92%',
            mode: "search",
            valueChangeEvent: "keyup"
        };

        var checkedRelyOnCodesRecursion = function (child, relyOnCodesArray, selected) {
            if (child === undefined || child.items === undefined || child.items.length == 0) return;

            child.items.forEach(function (sub) {
                if (relyOnCodesArray.indexOf(sub.code) >= 0) {
                    sub.selected = selected;
                }

                checkedRelyOnCodesRecursion(sub, relyOnCodesArray, selected);
            });
        };

        function clearAddFormValidation() {
            $scope.newRoleModel = {};
            //form validation
            $scope.roleNameExist = false;
            $scope.notServiceSelected = false;

            $scope.roleCategory = undefined;
        };

        function clearAllExceptRoleList() {
            //To save new role model or edit role model
            $scope.isEdit = false;
            $scope.editRoleModel = {};

            $scope.selectedRole = null;
            $scope.isSelected = false;

            //search
            $scope.searchText = '';
            //loading
            $scope.loadingMenu = false;

            clearAddFormValidation();


        };
        var initVariable = function () {
            //display
            $scope.roleList = [];

            clearAllExceptRoleList();

        };

        //Save role info
        var createRole = function () {

            var roleName = $scope.newRoleModel.Name;

            if (!$scope.newRoleModel || !$scope.newRoleModel.Name || !$scope.newRoleModel.RoleCategoryID) {
                return;
            }

            $scope.newRoleModel.ServiceTypeID = $scope.serviceType;
            $scope.newRoleModel.PermissionIDs = $scope.selectedPermissionCodes;

            roleService.addRole($scope.newRoleModel).success(function (res) {
                if (res.data === -1) {
                    $scope.roleNameExist = true;
                } else {
                    initVariable();
                    $('#addRolePop').modal('hide');
                    //Reload role list
                    $scope.roleList = res.data;
                    var newRole;
                    $scope.roleList.forEach(function (item) {
                        if (item.name == roleName) {
                            newRole = item;
                        }
                        if (item.subRoles && item.subRoles.length > 0) {
                            item.subRoles.forEach(function (child) {
                                if (child.name == roleName) {
                                    newRole = child;
                                }
                            });
                        }
                    });

                    if (newRole !== undefined) {
                        selectRole(newRole);
                    }

                    SweetAlert.success($translate.instant('createRole'), $translate.instant('addOneRole'));
                }
            });
        };

        var selectedPermissons = [];
        var selectedPermissonsRecursion = function (p) {
            if (p.items === null && p.items === undefined && p.items.length == 0) return;

            p.items.forEach(function (child) {
                if (child.selected) {
                    var selectedItem = {
                        id: child.id,
                        pLevel: child.pLevel,
                        name: child.text
                    };
                    var find = _.find(selectedPermissons, function (item) {
                        return item.id === child.id;
                    });
                    if (find === undefined) {
                        selectedPermissons.push(selectedItem);
                    }
                }
                selectedPermissonsRecursion(child);
            });
        };

        var saveRole = function () {

            //save role description 
            selectedPermissons = [];

            //get all selected item
            var selectedItemKeys = $scope.widgetInstance.getSelectedNodesKeys();

            selectedItemKeys.forEach(function (items) {
                //为了与后端统一,暂时传对象
                var selectedItem = {
                    id: items
                };
                selectedPermissons.push(selectedItem);
            });

            var updatedRoleInfo = {
            };
            updatedRoleInfo.updateRolePermissionDtoList = selectedPermissons;
            //add role name, role desc
            updatedRoleInfo.roleName = $scope.roleUpdatedModel.editRoleName;
            updatedRoleInfo.roleDescription = $scope.roleUpdatedModel.editDescription;

            //save to database
            roleService.updateRole(updatedRoleInfo, $scope.selectedRole.id).success(function (roleData) {
                $scope.isEdit = false;

                $scope.selectedRole.name = updatedRoleInfo.roleName;
                $scope.selectedRole.description = updatedRoleInfo.roleDescription;

                getPermissionsByService($scope.serviceType, $scope.selectedRole.id);

                SweetAlert.success($translate.instant('SaveSuccess'));
            });
        };

        $scope.updateRoleName = function (data) {
            console.log(data);
        };

        //获取特定服务下制定角色的权限列表
        function getPermissionsByService(serviceID, roleID) {
            if (roleID !== undefined) {
                $scope.permissionTreeViewData = [];
                permissionService.getDevTreePermissionsByRoleID(roleID, serviceID).success(function (data) {

                    //指定roleId下所拥有的权限 只显示有权限的列表,然后不需要显示checkbox
                    $scope.permissionTreeViewData = data.permissionDevTreeList;
                    $scope.rolePermissionList = data.rolePermissionList

                    console.log('permissionTreeViewData', data);

                    //先全部清空
                    $scope.widgetInstance.unselectAll();

                    $scope.rolePermissionList.forEach(function (item) {
                        $scope.widgetInstance.selectItem(item.permissionID);
                    });

                    //permissionService.getPermissionListByRoleID(roleID, serviceID).success(function (permissionList) {

                    //    //编辑模式下默认checked上拥有的权限
                    //    $scope.permisionTreeview = angular.copy($scope.allRawPermissionTreeViewData);
                    //    $scope.permisionTreeview.forEach(function (s) {
                    //        if (s.items && s.items.length > 0) {
                    //            s.items.forEach(function (sub) {

                    //                if (isPermissionChecked(permissionList, sub)) {
                    //                    //http://jsbin.com/pajeze/2/edit?html,js,output
                    //                    sub.selected = true;
                    //                }
                    //                checkedAuthorityDataRecursion(permissionList, sub);
                    //            });
                    //        }
                    //    });
                    //    $scope.allPermissionTreeViewData = $scope.permisionTreeview;
                    //});
                });

                // 获取对应用户
                getUsersByRoleID(roleID);

                //获取额外添加此角色的用户
                getExtraUserByRoleID(roleID);
            }
        };

        var getExtraUserByRoleID = function (roleID) {
            $scope.extraUserList = [];
            roleService.getExtraUsersByRoleID(roleID).success(function (extraUsers) {
                extraUsers.forEach(function (row) {
                    if (!row.orgName) {
                        row.orgName = $translate.instant('NoOrganization');
                    }
                });
                $scope.extraUserList = extraUsers;
                $scope.rightUserGridInstance.refresh();
                console.log("extraUsers: ", $scope.extraUserList);
            });
        };
        $scope.gotoPage1 = function () {
            $scope.leftUserGridInstance.refresh();
        };
        $scope.gotoPage2 = function () {
            $scope.rightUserGridInstance.refresh();
        };

        var getUsersByRoleID = function (roleID) {
            //获取对应用户
            $scope.nameList = [];
            roleService.getUsersByRoleID(roleID).success(function (users) {
                if (users) {
                    users.forEach(function (row) {
                        if (!row.orgName) {
                            row.orgName = $translate.instant('NoOrganization');
                        }
                    });
                    $scope.nameList = users;
                    $scope.leftUserGridInstance.refresh();
                    console.log("nameList: ", $scope.nameList);
                }
            });
        };

        var checkedAuthorityDataRecursion = function (permissionList, subPermission) {

            if (subPermission === undefined || subPermission.items === undefined || subPermission.items.length == 0) return;

            subPermission.items.forEach(function (sub) {
                if (isPermissionChecked(permissionList, sub)) {
                    sub.selected = true;
                }

                checkedAuthorityDataRecursion(permissionList, sub);
            });
        };

        ///检查当前permission是否在list中存在
        var isPermissionChecked = function (permissionList, permission) {

            var isChecked = false;
            permissionList.forEach(function (s) {
                if (s.permissionID === permission.id) {
                    isChecked = true;
                }
            });
            return isChecked;
        };

        //select an org
        var selectRole = function (role) {
            if (!role.id || role.id === role.roleCategoryID) {
                return;
            }

            clearAllExceptRoleList();
            $scope.isSelected = true;
            $scope.selectedRole = role;

            if (role.id !== role.roleCategoryID) {
                $scope.editRoleModel.ServiceTypeId = role.serviceTypeID;

                getPermissionsByService(role.serviceTypeID, role.id);
            }
        };


        //Clear role model
        var newRole = function () {
            $scope.newRoleModel = {};
            $scope.roleNameExist = false;

            //初始化权限选中状态
            $scope.selectedPermissionNames = [];
            $('#addRolePop').modal('show');
        };

        //create role category
        $scope.addRoleCategory = function () {
            $scope.newRoleCategory = '';
            $scope.isShow = !$scope.isShow;
        };

        //https://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity
        function setEndOfContenteditable(contentEditableElement) {
            var range, selection;
            if (document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
            {
                range = document.createRange();//Create a range (a range is a like the selection but invisible)
                range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
                range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                selection = window.getSelection();//get the selection object (allows you to change selection)
                selection.removeAllRanges();//remove any selections already made
                selection.addRange(range);//make the range you have just created the visible selection
            }
            else if (document.selection)//IE 8 and lower
            {
                range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
                range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
                range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
                range.select();//Select the range (make it the visible selection
            }
        }

        $scope.modifyRoleCategoryName = function (role, $event) {

            var element = $event.target;
            var div = $(element).parent().siblings('.divRoleCategoryName');

            if ($(div).attr('contenteditable')) {
                $(div).removeAttr('contenteditable');
            } else {
                $(div).attr('contenteditable', true);
            }

            setTimeout(function () {
                div.focus();
                //setEndOfContenteditable(div);
            }, 0);

            $scope.editRole = role;
        };

        $scope.deleteRoleCategoryName = function (role) {
            if (!(role && role.id)){
                SweetAlert.warning($translate.instant('RoleCategoryNotFound'));
                return;
            }
            if (role.subRoles && role.subRoles.length > 0) {
                SweetAlert.warning($translate.instant('hasSubRolesWarn'));
                return;
            }

            SweetAlert.swal({
                title: $translate.instant('ConfirmDelete') + '?',
                text: $translate.instant('roleCategoryDeleteConfirm') + ' - ' + role.name + '?',
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: $translate.instant('Confirm'),
                cancelButtonText: $translate.instant('Cancel'),
                closeOnConfirm: false,
                closeOnCancel: true
            }, function (isConfirm) {
                if (isConfirm) {
                    roleService.deleteRoleCategory(role.id).success(function (data) {
                        if (!data.result) {
                            SweetAlert.warning($translate.instant(data.resultMsg));
                            return;
                        }

                        $scope.roleList = _.without($scope.roleList, role);

                        SweetAlert.success($translate.instant('deleteRoleCategoryTitle'), $translate.instant('deleteRoleCategorySuccess'));
                    });
                }
            });
        };

        $scope.cancelRoleCategoryPanel = function () {
            $scope.isShow = false;
        };

        $scope.createRoleCategory = function () {
            var roleCategoryName = $scope.newRoleCategory;

            //check existance
            var roleCategoryList = _.pluck($scope.roleList, 'name');
            if (roleCategoryList.indexOf(roleCategoryName) >= 0) {
                SweetAlert.warning("", $translate.instant('updateRoleCategoryDuplicate'));
                return;
            }

            $scope.isShow = !$scope.isShow;
            var roleCategoryID = PWC.newGuid();
            roleService.addRoleCategory(roleCategoryName, roleCategoryID).success(function (data) {
                var newRoleCategory = {
                    id: roleCategoryID,
                    isRoleCategory: true,
                    name: roleCategoryName,
                    subRoles: []
                };

                $scope.roleList.push(newRoleCategory);

                SweetAlert.success($translate.instant('createRoleCategoryTitle'), $translate.instant('createRoleCategorySuccess'));
            });
        };

        //$translate.instant(selectOneRole)
        var editRole = function () {
            if (!$scope.isSelected) {
                SweetAlert.warning("", $translate.instant('selectOneRole'));
                return;
            }

            $scope.roleUpdatedModel = {};
            $scope.roleUpdatedModel.editDescription = $scope.selectedRole.description;
            $scope.roleUpdatedModel.editRoleName = $scope.selectedRole.name;

            $scope.isEdit = true;
        };

        var deleteRole = function () {

            roleService.deleteRole($scope.selectedRole).success(function (roleData) {
                //$('#deleteConfirmPop').modal('hide');
                SweetAlert.success($translate.instant('deleteOneRoleTitle'), $translate.instant('deleteOneRole'));
                initVariable();
                //reload data
                $scope.roleList = roleData;
                //select first one
                if (roleData[0].subRoles[0]) {
                    selectRole(roleData[0].subRoles[0]);
                }
            });
        };

        //Delete role info
        var deleteRoleConfirm = function () {
            if (!$scope.isSelected) {
                SweetAlert.warning("", $translate.instant('selectOneRole'));
                return;
            }
            //if there is at least user have this role, not allow to delete the role.
            roleService.checkReference($scope.selectedRole.id).success(function (canDelete) {
                if (eval(canDelete)) {
                    //$('#deleteConfirmPop').modal('show');
                    deleteConfirmPop();
                } else {
                    SweetAlert.error($translate.instant('notDeleteOneRoleTitle'), $translate.instant('notDeleteOneRole'))
                }
            });


        };

        var deleteConfirmPop = function () {
            SweetAlert.swal({
                title: $translate.instant('ConfirmDelete') + '?',
                text: $translate.instant('roleDeleteConfirm') + ' - ' + $scope.selectedRole.name + '?',
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: $translate.instant('Confirm'),
                cancelButtonText: $translate.instant('Cancel'),
                closeOnConfirm: false,
                closeOnCancel: true
            }, function (isConfirm) {
                if (isConfirm) {
                    deleteRole();
                }
            });
        };

        /*-------------------------------------------------------org list function start-------------------------------------------------*/
        //init org list
        var initRoleList = function () {
            $scope.isSelected = false;
            roleService.getRoleListByServiceGroup().success(function (roleData) {

                console.log('roleData:', roleData);
                $scope.roleList = roleData;
                if (roleData[0].subRoles != null && roleData[0].subRoles !== undefined && roleData[0].subRoles[0]) {
                    permissionService.getAllPermissions($scope.serviceType).success(function (data) {
                        $scope.allRawPermissionTreeViewData = data;
                        $scope.allPermissionTreeViewData = data;
                        selectRole(roleData[0].subRoles[0]);
                    });
                }
            });
        };

        //toggle tree node
        var toggleItem = function (icon) {
            icon.toggle();
        };

        var fillServiceType = function () {
            $scope.newRoleModel.RoleCategoryID = $scope.roleCategory;
        };


        var cancelRole = function () {
            clearAddFormValidation();
        };

        var cancelSave = function () {
            $scope.isEdit = false;
        };

        $scope.showOperateLogPop = function () {
            $scope.isShowLog = true;
            // $('#showOperatePop').modal('show');
        };

        //构造用户datagrid
        var loadLeftUserDatagrid = function () {

            //删除列定义
            var deleteColumnDef = {

                dataField: "userID",
                caption: $translate.instant('Delete'),
                alignment: 'center',
                cellTemplate: function (container, options) {
                    try {
                        var template = '<i class="material-icons highlight-tag" style="font-size:18px; cursor:pointer;">&#xE872;</i>';
                        $(template).on('dxclick', function () {
                            $scope.removeUser(options.row.data);
                        }).appendTo(container);
                    }
                    catch (e) {
                        $log.error(e);
                    }
                }
            };

            //grid 列定义
            var columnsDef = [
                    {
                        dataField: "userName",
                        caption: $translate.instant('UserDesc'),
                        cellTemplate: function (container, options) {
                            try {
                                $('<a>' + options.value + '</a>')
                                    .attr('href', '#/userDetail/' + options.row.data.userID)
                                    .appendTo(container);
                            }
                            catch (e) {
                                $log.error(e);
                            }
                        }
                    },
                    {
                        dataField: "orgName",
                        caption: $translate.instant('PCompany')
                    }
            ];

            //如果有编辑权限,那么添加删除列到grid中
            if ($scope.hasEditPermission) {
                columnsDef.push(deleteColumnDef);
            }

            $scope.leftUserdatagridOptions = {
                bindingOptions: {
                    dataSource: 'nameList'
                },
                selection: {
                    mode: "single"
                },
                columns: columnsDef,
                loadPanel: {
                    enabled: false
                },
                scrolling: {
                    mode: "virtual"
                },
                onInitialized: function (e) {
                    $scope.leftUserGridInstance = e.component;
                },
                allowColumnResizing: true,
                noDataText: $translate.instant('NoDataText'),
                showColumnLines: false,
                showRowLines: false,
                rowAlternationEnabled: false,
                showBorders: false,
                sorting: {
                    mode: "none"
                }
            };
        };


        var loadRightUserDatagrid = function () {

            $scope.rightUserdatagridOptions = {
                bindingOptions: {
                    dataSource: 'extraUserList'
                },
                selection: {
                    mode: "single"
                },
                columns: [
                    {
                        dataField: "userName",
                        caption: $translate.instant('UserDesc'),
                        cellTemplate: function (container, options) {
                            try {
                                $('<a>' + options.value + '</a>')
                                    .attr('href', '#/userDetail/' + options.row.data.userID)
                                    .appendTo(container);
                            }
                            catch (e) {
                                $log.error(e);
                            }
                        }
                    },
                    {
                        dataField: "orgName",
                        caption: $translate.instant('PCompany')
                    }
                ],
                onInitialized: function (e) {
                    $scope.rightUserGridInstance = e.component;
                },
                loadPanel: {
                    enabled: false
                },
                scrolling: {
                    mode: "virtual"
                },
                allowColumnResizing: true,
                noDataText: $translate.instant('NoDataText'),
                showColumnLines: false,
                showRowLines: false,
                rowAlternationEnabled: false,
                showBorders: false,
                sorting: {
                    mode: "none"
                }
            };
        };

        //权限check
        var checkUserPermission = function () {

            var list = [];
            $scope.hasQueryPermission = false;
            $scope.hasEditPermission = false;
            $scope.hasUserQueryPermission = false;
            $scope.hasOrgQueryPermission = false;

            //角色管理查看,添加和编辑角色权限Code
            var temp = constant.adminPermission.infrastructure.roleManage;
            list.push(temp.queryCode);
            list.push(temp.addCode);
            list.push(temp.editCode);

            $scope.$root.checkUserPermissionList(list).success(function (data) {

                $scope.hasQueryPermission = data[temp.queryCode];
                $scope.hasEditPermission = data[temp.editCode];
                $scope.hasAddPermission = data[temp.addCode];

                loadLeftUserDatagrid();

            });
        };

        /*-------------------------------------------------------org list function end-------------------------------------------------*/

        (function initialize() {
            $log.debug('RoleManageController.ctor()...');
            initVariable();
            initRoleList();
            $scope.currentNavItem = 'page1';

            loadRightUserDatagrid();

            //Save role info
            $scope.createRole = createRole;
            $scope.saveRole = saveRole;

            //Clear role model
            $scope.newRole = newRole;
            $scope.editRole = editRole;
            //Delete role info
            $scope.deleteRole = deleteRole;

            $scope.deleteRoleConfirm = deleteRoleConfirm;

            $scope.selectRole = selectRole;
            $scope.cancelRole = cancelRole;
            $scope.fillServiceType = fillServiceType;
            $scope.cancelSave = cancelSave;

            loadPermissionTree();
            loadAllPermissionTree();

            checkUserPermission();
        })();
    }
]);