infrastructureModule
.controller('RoleManageController', ['$scope', '$log', '$translate', 'loginContext', 'roleService', 'risDialog', 'permissionService', '$state', '$q', '$timeout',
    'menuService', 'uiGridConstants', 'SweetAlert', 'userService',
    function ($scope, $log, $translate, loginContext, 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 () {
            var isSuperAdmin;
            userService.getUserPermissionNew(loginContext.userName, function (data) {
                isSuperAdmin = data.isSuperAdmin;
            });
            $scope.isSelected = false;
            roleService.getRoleListByServiceGroup().success(function (roleData) {
                if(!isSuperAdmin){
                    roleData[0].subRoles = [roleData[0].subRoles[0]];
                }
                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;
                        if(!isSuperAdmin){
                            data[0].items[0].items.splice(3,1);
                            data[0].items[0].items[2].items.splice(1,2);
                            $scope.allPermissionTreeViewData = data;
                        } else {
                            $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();
        })();
    }
]);