infrastructureModule.controller('landManageController', ['$log', '$scope', '$translate', '$timeout', 'orgService', 'landManageService',
    'SweetAlert', 'loginContext',
    function ($log, $scope, $translate, $timeout, orgService, landManageService, SweetAlert, loginContext) {
        //---------------land---manage-------------------
        $scope.pageStatus = {
            noData: 0,
            hasData: 1
        };
        var showAddLandDialog = function () {
            $scope.editLand = initLand();
            $scope.isEdit = false;
            $('#add-land').modal('show');
        };
        var showEditLandDialog = function () {
            $scope.editLand = angular.copy($scope.Land);
            $scope.isEdit = true;
            $('#add-land').modal('show');
        };
        var toDisplay = function () {
            $scope.Land.computeTaxWayText = $scope.Land.computeTaxWay === 1 ? $translate.instant('SpecialComputeTaxWay') : $translate.instant('GeneralComputeTaxWay');
            $scope.Land.isPrepaidText = $scope.Land.isPrepaid ? $translate.instant('Yes') : $translate.instant('No');
        };
        var addorUpdateLand = function () {
            //  $scope.editLand.updator = loginContext.userId;
            if ($scope.isEdit) {
                $scope.editLand.updater = '66933E7B-DA75-4B2E-B7D6-AB65DCA20D50';
                landManageService.updateLand($scope.editLand).success(function (data) {
                    if (data.result) {
                        $scope.Land = $scope.editLand;
                        //toDisplay();
                        //initGrid();
                        //$scope.landLoadstatus = $scope.pageStatus.hasData;
                    } else {
                        SweetAlert.error($translate.instant('AddLandFail'), '');
                    }
                }).error(function (err) {
                    SweetAlert.error($translate.instant('CommonFail'), '');
                });
            } else
            {
                $scope.editLand.creator = '66933E7B-DA75-4B2E-B7D6-AB65DCA20D50';
                landManageService.addLand($scope.editLand).success(function (data) {
                    if (data.result) {
                        $scope.Land = $scope.editLand;
                        $scope.Land.id = data.resultMsg;//new land id
                        toDisplay();
                        initGrid();
                        $scope.landLoadstatus = $scope.pageStatus.hasData;
                    } else {
                        SweetAlert.error($translate.instant('AddLandFail'), '');
                    }
                }).error(function (err) {
                    SweetAlert.error($translate.instant('CommonFail'), '');
                });
            }
          
        };
        var initLand = function () {
            return {
                id: '',
                //because organization selector need it
                organization: {
                    id: null,
                    name: ''
                },
                //in order to map the backend feild
                organizationID: '',
                organizationName: '',
                code: '',
                name: '',
                area: '',
                city: '',
                period: '',
                amount: null,
                computeTaxWay: 0,
                isPrepaid: false,
                creator: null,
                updater: null,
                isActive: 1
            };
        };
        var loadLandData = function () {
            landManageService.loadAll().success(function (data) {
                if (data.result) {
                    if (data.data && data.data.length > 0) {
                        $scope.landLoadstatus = $scope.pageStatus.hasData;
                        $scope.LandList = data.data;
                    } else {
                        $scope.landLoadstatus = $scope.pageStatus.noData
                    }

                } else {
                    SweetAlert.error($translate.instant('CommonFail'), '');
                }
            }).error(function () {
                SweetAlert.error($translate.instant('CommonFail'), '');
            });
        };
        var showLand = function (land) {
            $scope.Land = land;
            toDisplay();
            var datagrid = $('#taxGrid').dxDataGrid("instance");
            datagrid.refresh();
            $('#detail-content').show();
        };
        var disableOrActiveLand = function () {
            $scope.Land.isActive = !$scope.Land.isActive
            var currentLand = initLand();
            currentLand.id = $scope.Land.id;
            currentLand.isActive = $scope.Land.isActive;
            currentLand.updater = $scope.Land.updater;
            landManageService.disableOrEnableLand(currentLand).success(function (res) {
                if (!res.result) {
                    SweetAlert.error($translate.instant('CommonFail'), '');
                }
            }).error(function () {
                SweetAlert.error($translate.instant('CommonFail'), '');
            });
        };
        //------------------taxation----basic-----------------------------------
        var getTaxData = function () {
            landManageService.loadAllTax($scope.Land.id)
                    .then(function (response) {
                        $scope.taxBasicData = response.data.data;
                        //return { data: response.data.data, totalCount: response.data.data.length };
                    }, function (response) {
                        return SweetAlert.error($translate.instant('CommonFail'), '');
                    });

        };
        var initGrid = function () {
            // getTaxData();
            // customStore(); CustomStore
            $scope.taxBasicSource = new DevExpress.data.DataSource({
                load: function (loadOptions) {
                    return landManageService.loadAllTax($scope.Land.id)
                    .then(function (response) {
                        return { data: response.data.data, totalCount: response.data.data.length };
                    }, function (response) {
                        return $q.reject($translate.instant('CommonFail'));
                    });
                },
                key: 'id',
                insert: function (values) {
                    values.landManageID = $scope.Land.id;
                    values.creator = '66933E7B-DA75-4B2E-B7D6-AB65DCA20D50';
                    values.updater = '66933E7B-DA75-4B2E-B7D6-AB65DCA20D50';
                    //validation
                    return landManageService.addTaxBasic(values);
                },
                //onInserted: function (values, key) {
                //    console.log('inserted');
                //    console.log(values);
                //    console.log(key);
                //},
                remove: function (key) {
                    return landManageService.deleteTaxBasic(key);
                },
                update: function (key, values) {
                    return landManageService.updateTaxBasic(values);
                },
                errorHandler: function (error) {
                    SweetAlert.error($translate.instant('CommonFail'), '');
                    return false;
                }
            });

            //loadAllTax
            $scope.gridOptions = {
                height:300,
                dataSource: $scope.taxBasicSource,
                paging: { pageSize: 6 },
                pager: {
                    showNavigationButtons: true
                },
                editing: {
                    mode: "form",
                    allowUpdating: true,
                    allowAdding: true,
                    allowDeleting: true,
                    form: {
                        colCount: 2,
                        items: [
                           'accountCode', 'accountName',
                           {
                               colSpan: 2,
                               dataField: "description",
                               editorType: "dxTextArea"
                               //editorOptions: {
                               //    height: 90,
                               //}
                           },
                        "isTaxpaying"
                        ]
                    }

                },
                //scrolling:{
                //    mode: 'standard',
                //    showScrollbar: 'Always'
                //},
                searchPanel: {
                    visible: true,
                    width: 240,
                    placeholder: "Search..."
                },
                onRowUpdating: function (e) {
                    // console.log(e.oldData);                    
                    e.newData = _.extend(e.oldData, e.newData);
                },
                showBorders: true,
                showRowLines: true,
                columns: [
                    //{ dataField: 'id', caption: 'ID', width: '3%' },
                    { dataField: 'accountCode', caption: $translate.instant('SubjectCode'), width: '25%', validationRules: [{ type: "required" }] },
                    { dataField: 'accountName', caption: $translate.instant('SubjectName'), width: '25%', validationRules: [{ type: "required" }] },
                    {
                        dataField: 'description', caption: $translate.instant('Description'), width: '37%',
                        editCellTemplate: function (cellElement, cellInfo) {
                            $('<div/>').dxTextArea({
                                value: cellInfo.value,
                                valueChangeEvent: "change",
                                onValueChanged: function (data) {
                                    cellInfo.setValue(data.value);
                                }
                            }).appendTo(cellElement);
                        }
                        //cellTemplate: function (cellElement, cellInfo) {
                        //    console.log(cellInfo.value);
                        //}
                    },
                    { dataField: 'isTaxpaying', dataType: 'boolean', caption: $translate.instant('IsCompute'), width: '13%' },
                ],
                onCellPrepared: function (e) {

                    if (e.rowType === "data" && e.column.command === "edit") {
                        var isEditing = e.row.isEditing,
                            $links = e.cellElement.find(".dx-link");

                        $links.text("");

                        if (isEditing) {
                            //$links.filter(".dx-link-save").addClass("dx-icon-save");
                            //$links.filter(".dx-link-cancel").addClass("dx-icon-revert");
                            $links.filter(".dx-link-save").addClass("fa").addClass("fa-floppy-o").addClass('action-icon');
                            $links.filter(".dx-link-cancel").addClass("fa").addClass("fa-undo").addClass('action-icon');
                        } else {
                            //$links.filter(".dx-link-edit").addClass("dx-icon-edit");
                            //$links.filter(".dx-link-delete").addClass("dx-icon-trash");
                            $links.filter(".dx-link-edit").addClass("fa").addClass("fa-pencil-square-o").addClass('action-icon');
                            $links.filter(".dx-link-delete").addClass("fa").addClass("fa-trash-o").addClass('action-icon');
                        }
                    }
                }
            };
        };

        var filterTax = function (value) {
            var dataGrid = $('#taxGrid').dxDataGrid("instance");
            if (value === -1)
                dataGrid.clearFilter();
            else
                dataGrid.filter(["isTaxpaying", "=", value]);
        };
        var initTaxation = function () {
            return {
                id: '',
                landManageID: '',
                accountCode: null,
                accountName: null,
                description: null,
                isTaxpaying: false,
                creator: null,
                updater: null
            }
        };

        //----------------------taxation----basic-end-------------------------------
        (function initialize() {
            $scope.addorUpdateLand = addorUpdateLand;
            $scope.disableOrActiveLand = disableOrActiveLand;
            $scope.showEditLandDialog = showEditLandDialog;
            $scope.showAddLandDialog = showAddLandDialog;
            loadLandData();
            //current land
            $scope.Land = {};
            $scope.editLand = {};
            $scope.initLand = initLand;
            $scope.ways = [
                { id: 0, name: $translate.instant('GeneralComputeTaxWay') },
                { id: 1, name: $translate.instant('SpecialComputeTaxWay') },
            ];
            $scope.wayOptions = {
                dataSource: $scope.ways,
                valueExpr: 'id',
                displayExpr: 'name',
                bindingOptions: {
                    value: "editLand.computeTaxWay"
                }
            };
            //show land detail
            $scope.showLand = showLand;
            initGrid();
            //taxation basic
            $scope.filterTax = filterTax;
            $scope.editTaxationBasic = {};
        })();
    }]);
infrastructureModule.directive('landManage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('landManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/landManage/land-manage.html' + '?_=' + Math.random(),
            scope: {},
            controller: 'landManageController',
            link: function ($scope, $element, $attr) {
                //all validation put here
                $scope.periodOptions = {
                    bindingOptions: {
                        value: "editLand.period"
                    },
                    onKeyPress: function (e) {
                        var event = e.jQueryEvent,
                            str = event.key || String.fromCharCode(event.which);
                        if (/^[\.\,e]$/.test(str))
                            event.preventDefault();
                    },
                };




            }
        };
    }
]);
infrastructureModule.
controller('MenuManageController', ['$scope', '$rootScope', '$log', '$http', '$location', '$translate',
    '$timeout', '$attrs', 'ngDraggable', 'menuService', 'serviceTypeService',
    function ($scope, $rootScope, $log, $http, $location, $translate, $timeout, $attrs, ngDraggable, menuService, serviceTypeService) {
        //'use strict';
        $log.debug('MenuManageController.ctor()...');
  
        $scope.bag = [{
            label: 'Glasses',
            value: 'glasses',
            children: [{
                label: 'Top Hat',
                value: 'top_hat',
                children: [{
                    label: 'Top Hat 2',
                    value: 'top_hat 2'
                }, {
                    label: 'Top Hat 3',
                    value: 'top_hat 3'
                }]
            }, {
                label: 'Curly Mustache',
                value: 'mustachio'
            }]
        }];

        $scope.awesomeCallback = function (node, tree) {
            // Do something with node or tree
            $log.info('callback');
        };

        $scope.otherAwesomeCallback = function (node, isSelected, tree) {
            // Do soemthing with node or tree based on isSelected
            $log.info('other call back',node);
        }
         
        //scope model
        $scope.isAdd = false;
        $scope.selectedMenu = null;
        $scope.editMenuModel = null;
        $scope.menuData = [];
        $scope.checkedMenusSet = {};
        $scope.set = [];
        $scope.defaultServiceType = {};
        $scope.currentServiceTypeId = null; 
         
        var getMenusByServiceTypeId = function (serviceTypeId) {
            menuService.getMenus(serviceTypeId).success(function(menuData) {
                $scope.menuData = menuData;
            });
        };

        //根据serviceTypeId重新获取菜单
        $scope.updateMenus = function (selectedServiceType) {
            $scope.currentServiceTypeId = selectedServiceType.id;
            $scope.selectedMenu = null;

            menuService.getMenus($scope.currentServiceTypeId).success(function (menuData) {
                if (menuData.length === 0) {
                    $scope.showTree = false;
                    $scope.menuData = [];
                    return;
                }
                $scope.menuData = menuData;
                $scope.editMenuModel = null;
                $scope.showTree = true;
            });
        };

        serviceTypeService.getServiceTypeList().success(function (serviceTypeList) {
            $scope.serviceTypeList = serviceTypeList;
            $scope.selectedServiceType = _.find($scope.serviceTypeList, function (num) { return num.id === '1'; });
            $scope.currentServiceTypeId = $scope.selectedServiceType.id;
            getMenusByServiceTypeId($scope.currentServiceTypeId);
            $scope.showTree = true;
        });
         
        //scope function
        $scope.addMenu = function () {
            $scope.isAdd = true;
            $scope.editMenuModel = {};
        };

        $scope.toggle = function (scope) {
            scope.toggle();
        };

        $scope.toggleSub = function (menu) {
            if (menu.isChecked) {
                $scope.checkedMenusSet[menu.id] = menu;
            }
            else {
                delete $scope.checkedMenusSet[menu.id];
                //if the menu is child menu, and parent menu is checked, need to uncheck parent menu

                if (!menu.parentID) {
                    //return;
                }

                if ($.inArray(menu.parentID + "", $scope.set) !== - 1) {
                    delete $scope.checkedMenusSet[menu.parentID];
                    for (var i = 0, len = $scope.menuData.length; i < len; i++) {
                        var parentMenu = $scope.menuData[i];
                        if (parentMenu.id === menu.parentID) {
                            parentMenu.isChecked = false;
                            break;
                        }
                    }
                }
            }
            $scope.set = _.keys($scope.checkedMenusSet);
            if (!menu.subMenus) {
                return;
            }
            menu.subMenus.forEach(function (d) {
                d.isChecked = menu.isChecked;
                if (menu.isChecked) {
                    $scope.checkedMenusSet[d.id] = d;
                }
                else {
                    delete $scope.checkedMenusSet[d.id];
                }
            });

            $scope.set = _.keys($scope.checkedMenusSet);
        };

        $scope.save = function () {
            if (!$scope.editMenuModel) {
                return;
            }
            if (!$scope.isAdd) {
                $scope.editMenuModel.serviceTypeID = $scope.currentServiceTypeId;
                menuService.updateMenu($scope.editMenuModel).success(function () {
                    exchangeModel($scope.editMenuModel, $scope.selectedMenu);
                    $scope.editMenuModel = null;
                    $scope.selectedMenu = null;
                    $log.debug('Update menu successfully');
                });
            }
            else {
                if ($scope.selectedMenu != null) {
                    $scope.editMenuModel.parentID = $scope.selectedMenu.id;
                }
                $scope.editMenuModel.serviceTypeID = $scope.currentServiceTypeId; 
                menuService.addMenu($scope.editMenuModel).success(function (id) {
                    $scope.editMenuModel.id = id;
                    if ($scope.selectedMenu != null) {
                        $scope.selectedMenu.subMenus = $scope.selectedMenu.subMenus || [];
                        //when parent menu check box is checked, the new child should be checked as well.
                        if ($scope.selectedMenu.isChecked) {
                            $scope.editMenuModel.isChecked = true;
                            $scope.checkedMenusSet[$scope.editMenuModel.ID]= $scope.editMenuModel;
                            $scope.set = _.keys($scope.checkedMenusSet);
                        }
                        $scope.selectedMenu.subMenus.push($scope.editMenuModel);
                        $scope.showTree = true;
                    }
                    else {
                        $scope.editMenuModel.parentID = null;
                        $scope.editMenuModel.subMenus = [];
                        $scope.menuData.push($scope.editMenuModel);
                        $scope.showTree = true;
                    }
                    $scope.selectedMenu = null;
                    $scope.editMenuModel = null;
                    $log.debug('Add new menu successfully');
                });
            }
        };

        $scope.cancel = function () {
            $scope.selectedMenu = null;
            $scope.editMenuModel = null;
        };

        //$scope.selectMenu = function (node, isSelected, tree) {
        //    menu = node.value;
        //    $scope.isAdd = false;
        //    $scope.selectedMenu = menu;
        //    $scope.editMenuModel = {};
        //    exchangeModel(menu, $scope.editMenuModel);
        //};

        $scope.selectMenu = function (menu) { 
            $scope.isAdd = false;
            $scope.selectedMenu = menu;
            $scope.editMenuModel = { };
            exchangeModel(menu, $scope.editMenuModel);
        };

        function exchangeModel(from, to) {
            to.name = from.name; 
            to.orderIndex = from.orderIndex;
            to.parentID = from.parentID;
            to.navigationUrl = from.navigationUrl;
            to.isActive = from.isActive;
            to.isVisible = from.isVisible;
            to.moduleID = from.moduleID;
            to.iconClassName = from.iconClassName;
            to.id = from.id;
            to.createTime = from.createTime;
            to.updateTime = from.updateTime;
        };

        $scope.deleteMenus = function () {
            menuService.deleteMenus($scope.set)
                .success(function () {
                    $scope.set = [];
                    menuService.getMenus($scope.currentServiceTypeId).success(function (menuData) {
                        $scope.menuData = menuData;
                    });
                });
            //.fail(function () {

            //});
        }
    }
]);
infrastructureModule.directive('menuManage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('menuManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/menuManage/menu-manage.html' + '?_=' + Math.random(),
            replace: true,
            scope: {},
            controller: 'MenuManageController',
        };
    }
]);
infrastructureModule
    .controller('OrganizationAreaViewController', ['$scope', '$log', 'SweetAlert', 'regionService', '$translate', 'areaRegionService', 'uiGridTreeViewConstants', '$timeout', 'areaService', 'uiGridConstants', '$interval', 'orgService', 'dimensionService', '$state', '$stateParams', 'statisticAttributeService', '$q', 'roleService', 'enums',
        function ($scope, $log, SweetAlert, regionService, $translate, areaRegionService, uiGridTreeViewConstants, $timeout, areaService, uiGridConstants, $interval, orgService, dimensionService, $state, $stateParams, statisticAttributeService, $q, roleService, enums) {
            'use strict';

            // 机构缩略图
            var isGeneral = true;

            var defaultValue = {
                unknownArea: '未知分区',
                notSetAttribute: '未設置值',
            };

            // 机构缩略图ID
            var orgGeneralInfoPopId = '#orgGeneralInfoPop';
            var unassisgnText = $translate.instant('UnAssignText');
            $scope.unassisgnText = unassisgnText;
            var areaCommonCardID = '#areaOrgCard';
            var areaUserCardID = '#areaUserCard';

            // 系统级别的纬度id列表
            var systemDimensionIdList = [
                constant.attributeID.businessUnitID,
                constant.attributeID.areaID,
                constant.attributeID.organizationStructureID,
                constant.attributeID.userID,
                constant.attributeID.industryID,
                constant.attributeID.rgSubChildrenID
            ];

            // 颜色模板
            var colorPanel = {

                // 颜色列表
                // yellow,orange,gold
                colorList: ['#FFB300', '#FEE002', '#FFFA23'],

                createNew: function () {
                    var colorPanelInstance = {};
                    colorPanelInstance.index = -1;
                    colorPanelInstance.getNextColor = function () {
                        if (colorPanelInstance.index >= colorPanel.colorList.length - 1) {
                            colorPanelInstance.index = 0;
                        } else {
                            colorPanelInstance.index++;
                        }

                        return colorPanel.colorList[colorPanelInstance.index];
                    }

                    return colorPanelInstance;
                }
            };

            // 颜色实例
            var colorPanelInstance = colorPanel.createNew();

            var barColorPanel = {

                // 颜色列表
                // yellow,orange,gold
                colorList: [{
                    name: 'orange-color',
                    value: '#FDB37F',
                    lightColor: '#FEDEBB'
                }, {
                    name: 'purple-color',
                    value: '#CE97D7',
                    lightColor: '#F3DEF0'
                }, {
                    name: 'green-color',
                    value: '#B0DC56',
                    lightColor: '#E0E0A4'
                }],
                createNew: function () {
                    var colorPanelInstance = {};
                    colorPanelInstance.index = -1;
                    colorPanelInstance.currentColor = {};
                    colorPanelInstance.getNextColor = function () {
                        if (colorPanelInstance.index >= barColorPanel.colorList.length - 1) {
                            colorPanelInstance.index = 0;
                        } else {
                            colorPanelInstance.index++;
                        }

                        colorPanelInstance.currentColor = barColorPanel.colorList[colorPanelInstance.index];
                        return colorPanelInstance.currentColor;
                    };

                    return colorPanelInstance;
                }
            };

            // 柱状图颜色实例
            var barColorPanelInstance = barColorPanel.createNew();

            // 初始化维度展示列表Grid
            var areaDimensionORGGridListInit = function () {

                var columns = [{
                    field: 'name',
                    name: $translate.instant('ProjectCompanyCol'),
                    headerCellClass: 'text-align-left',
                    width: '100%',
                    cellTemplate: '<div ng-if="row.entity.isOrg" ng-class="{0: \'text-align-left\', 1: \'padding-left1\', 2:\'padding-left2\'}[row.entity.paddingLevel]">\
                        <span class="org-show-general" ng-click="grid.appScope.ShowOrgGeneralInfo(row,$event)" title="{{row.entity.name}}" id="{{row.entity.id}}">{{row.entity.name|limitString:16}}</span>\
                        </div>\
                        <div ng-if="!row.entity.isOrg" ng-class="{0: \'text-align-left\', 1: \'padding-left1\', 2:\'padding-left2\'}[row.entity.paddingLevel]">\
                        <span title="{{row.entity.name}}" id="{{row.entity.id}}">{{row.entity.name|limitString:16}}</span>\
                        </div>\
                        '
                }];

                $scope.areaDimensionORGGridList = {
                    enableRowSelection: true,
                    enableSelectAll: false,
                    rowHeight: constant.UIGrid.rowHeight,
                    enableRowHeaderSelection: false,
                    modifierKeysToMultiSelect: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    enableVerticalScrollbar: uiGridConstants.scrollbars.enableVerticalScrollbar,
                    selectionRowHeaderWidth: constant.UIGrid.rowHeight,
                    enableSorting: true,
                    enableColumnMenus: false,
                    enableFiltering: false,
                    showTreeExpandNoChildren: false,
                    enableFullRowSelection: true, //是否点击行任意位置后选中,默认为false
                    multiSelect: false, // 是否可以选择多个,默认为true;
                    columnDefs: columns,
                    onRegisterApi: function (gridApi) {
                        $scope.gridApiareaDimensionORGGridList = gridApi;

                        // call resize every 500 ms for 5 s after modal finishes opening - usually only necessary on a bootstrap modal
                        $interval(function () {
                            $scope.gridApiareaDimensionORGGridList.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);
                    }
                };


                $scope.areaDimensionORGGridList.data = [];
            };

            // 区域UI-Grid图
            var areaORGGridInit = function () {

                $scope.columns = [{
                    field: 'name',
                    name: $translate.instant('FieldorgName'),
                    headerCellClass: '',
                    // width: '50%',
                    cellTemplate: '<div ng-class="{0: \'text-align-left\', 1: \'padding-left1\', 2:\'padding-left2\'}[row.entity.paddingLevel]">\
                        <span class="org-show-general" ng-click="grid.appScope.ShowOrgGeneralInfo(row,$event)" title="{{row.entity.name}}" id="{{row.entity.id}}">{{row.entity.name|limitString:16}}</span>\
                        </div>'
                }];

                $scope.areaORGGridList = {
                    enableRowSelection: true,
                    enableSelectAll: false,
                    rowHeight: constant.UIGrid.errorRowHeight,
                    enableRowHeaderSelection: false,
                    modifierKeysToMultiSelect: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    enableVerticalScrollbar: uiGridConstants.scrollbars.enableVerticalScrollbar,
                    selectionRowHeaderWidth: constant.UIGrid.selectionRowHeaderWidth,
                    enableSorting: true,
                    enableColumnMenus: false,
                    enableFiltering: false,
                    showTreeExpandNoChildren: false,
                    enableFullRowSelection: true, //是否点击行任意位置后选中,默认为false
                    multiSelect: false, // 是否可以选择多个,默认为true;
                    columnDefs: $scope.columns,
                    onRegisterApi: function (gridApi) {
                        $scope.gridApiAreaORGGridList = gridApi;

                        // call resize every 500 ms for 5 s after modal finishes opening - usually only necessary on a bootstrap modal
                        $interval(function () {
                            $scope.gridApiAreaORGGridList.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);
                    }
                };

                $scope.areaORGGridList.data = [];
            };

            var initUserSumDevGrid = function () {

                $scope.userDatagridDataSource = [];
                $scope.areaUserdatagridOptions = {
                    bindingOptions: {
                        dataSource: 'userDatagridDataSource'
                    },
                    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: "roleInfo",
                        caption: $translate.instant('Role')
                    }, {
                        dataField: "orgCount",
                        caption: $translate.instant('OrganizationCount'),
                        alignment: 'center'

                    }, ],
                    loadPanel: {
                        enabled: false
                    },
                    scrolling: {
                        mode: "virtual"
                    },
                    noDataText: $translate.instant('NoDataText'),
                    showColumnLines: false,
                    showRowLines: false,
                    rowAlternationEnabled: true,
                    showBorders: false,
                    sorting: {
                        mode: "none"
                    }
                };
            };

            $scope.$on("DimensionUpdate", function (event, data) {
                // console.log('DimensionUpdate' + JSON.stringify(data));
                // 强制刷新机构部分
                $scope.forceOrgUpdate = true;
                // 修改维度可能修改到的值
                init();

            });

            // 绘制中国地图
            var drawChinaMap = function () {

                $.get('/app-resources/map/china.json', function (chinaJson) {
                    echarts.registerMap('china', chinaJson);
                    var mychart = echarts.init(document.getElementById('chinaShowOrganizationMap'));
                    var option = {
                        // remove hover show
                        // tooltip: {
                        //     trigger: 'item',
                        //     // triggerOn: 'click', 调试tooltip样式使用
                        //     showDelay: 10,
                        //     enterable: true,
                        //     formatter: fomatterFunction,
                        // },
                        legend: {
                            orient: 'vertical',
                            left: 'left',
                            data: []
                        },
                        textStyle: {
                            color: '#000',
                            fontWeight: 'bold'
                        },
                        series: [{
                            type: 'map',
                            map: 'china',
                            nameMap: {
                                'China': '中国'
                            },
                            label: {
                                normal: {
                                    show: true,
                                    textStyle: {
                                        color: '#894A00',
                                        fontWeight: 'normal'
                                    }
                                },
                                emphasis: {
                                    //textStyle: {
                                    //    color: '#fff'
                                    //}
                                }
                            },
                            itemStyle: {
                                normal: {
                                    areaColor: '#C9C9C9',
                                    borderColor: 'white',
                                    borderWidth: 0.5,
                                    label: {
                                        show: false
                                    }
                                },
                                emphasis: {
                                    areaColor: '#F2D997',
                                    label: {
                                        show: true
                                    }
                                }
                            },
                            zoom: 1.2,
                            scaleLimit: {
                                min: 1
                            },
                            selectedMode: false,
                            roam: true,
                            data: [],
                            markPoint: {
                                symbol: 'pin',
                                symbolSize: 50,
                                label: {
                                    normal: {
                                        show: true,
                                        formatter: function (d) {
                                            return d.name
                                        }
                                    }
                                },
                                data: [
                                    // {
                                    //     name: '武汉',
                                    //     coord: [114.31, 30.52]
                                    // },{
                                    //     name:'临汾市',
                                    //     coord:[111.517975,36.08415]
                                    // }
                                ]
                            }
                        }]
                    };

                    $scope.chinaMapOption = option;
                    mychart.setOption(option);
                    $scope.chinaMapChart = mychart;
                });

            };

            // 自动加上id、颜色及样式信息
            var generateID = function () {
                var index = 0;

                if ($scope.areaInfoList && $scope.areaInfoList.length > 0) {
                    $scope.areaInfoList.forEach(function (row) {

                        row.randomID = "area" + index;
                        row.totalCount = 0;
                        if (row.cityStatistics && row.cityStatistics.length > 0) {
                            row.cityStatistics.forEach(function (r) {
                                row.totalCount += r.organizationBusinessUnitStatistics.length;
                            });
                        }

                        // var areaOrgList = _.filter($scope.organizationList, function(org){
                        //     return org.areaID === row.id;
                        // });

                        // if (areaOrgList && areaOrgList.length > 0){
                        //     row.organizationCount = areaOrgList.length;
                        // } else{
                        //     row.organizationCount = 0;
                        // }

                        // 颜色及样式
                        row.theme = barColorPanelInstance.getNextColor();
                        row.detailTitle = row.name + $translate.instant('AreaDetail');
                        index++;
                    });
                }
            };

            $scope.getGridHeight = function () {

                return {};
            };

            // 构造机构层级父子节点树
            var parseDataGridOnlyOrg = function () {

                var gridData = [];

                // 直接看区域上设置的AreaID,不用根据行政区域划分到哪个分区来计算【简单做】
                var allOrgList = $scope.panelArea.organizationList;

                if (allOrgList && allOrgList.length > 0) {
                    // $scope.panelArea.cityStatistics.forEach(function (r) {
                    //     if (r.organizationBusinessUnitStatistics && r.organizationBusinessUnitStatistics.length > 0) {
                    //         allOrgList = _.union(r.organizationBusinessUnitStatistics, allOrgList);
                    //     }

                    // });

                    // 先复制一份,要改parentID,不要相互影响
                    allOrgList = angular.copy(allOrgList);

                    // 设置自定义维度的值
                    for (var i = 0; i < $scope.statisticAttrList.length; i++) {
                        var index = i + 1;
                        var attr = $scope.statisticAttrList[i];

                        if (attr.attributeType === constant.attributeType.SelfDimension) {
                            var relevantOrgList = _.filter($scope.dimensionOrgList, function (dimensionOrg) {
                                return dimensionOrg.dimensionID === attr.belongDimensionID;
                            });

                            relevantOrgList.forEach(function (dimensionOrg) {
                                var org = _.find(allOrgList, function (org) {
                                    return org.id === dimensionOrg.organizationID;
                                });

                                if (org) {
                                    org['selfDimension' + index] = dimensionOrg.dimensionValue;
                                }
                            });
                        }
                    }


                    if ($scope.selectAttribute.attributeType === constant.attributeType.OrgSubChildren) {

                        // 机构维度
                        gridData = buildOrgTreeData(allOrgList);


                    } else if ($scope.selectAttribute.attributeType === constant.attributeType.SelfDimension) {
                        // 自定义维度
                        var row = $scope.selectAttribute;

                        var orgidList = _.pluck(allOrgList, 'id');

                        var targetDimensionValueList = _.filter($scope.dimensionOrgList, function (data) {
                            return data.dimensionID === row.belongDimensionID && orgidList.indexOf(data.organizationID) > -1;
                        });

                        var orgList = [];
                        if (targetDimensionValueList && targetDimensionValueList.length > 0) {
                            orgList = _.uniq(_.pluck(targetDimensionValueList, 'dimensionValueID'));
                        }

                        gridData = selfDimensionOrgTree(allOrgList, targetDimensionValueList);

                    } else {
                        // 其他维度
                        var idCol = constant.attributeTypeIDColMap[$scope.selectAttribute.attributeType];
                        var nameCol = constant.attributeTypeNameColMap[$scope.selectAttribute.attributeType];
                        gridData = systemDimensionOrgTree(allOrgList, idCol, nameCol);

                    }

                }

                $scope.areaORGGridList.data = gridData;
                // $log.debug("gridData:" + JSON.stringify(gridData));
            };

            var buildOrgTreeData = function (allOrgList) {

                $scope.commonCountDataSource = [];

                if (!allOrgList) {
                    allOrgList = [];
                }

                $scope.commonCountDataSource.push({
                    name: '机构数',
                    count: allOrgList.length
                });

                // 获取所有根节点的机构
                var idList = _.pluck(allOrgList, 'id');
                var topNodeList = _.filter(allOrgList, function (org) {
                    return idList.indexOf(org.parentID) === -1;
                });

                var orglist = [];
                topNodeList.forEach(function (org) {
                    var temp = buildOrgTree(org, allOrgList);
                    orglist.push(temp);
                });

                var templist = parseUIGridTreeList(orglist, 0);

                return templist;
            };

            // 获取父节点
            var getParentID = function (current, allList, orgDtoList) {
                if (current.parentID === null) {
                    return null;
                }

                var findParent = _.find(allList, function (num) {
                    return num.id === current.parentID;
                });

                var parent = _.find(orgDtoList, function (num) {
                    return num.id === findParent.id;
                });

                if (parent != null) {
                    return parent.id;
                } else {
                    return getParentID(findParent, allList, orgDtoList);
                }
            };

            // 构造UITree
            var parseUIGridTreeList = function (orglist, level) {
                var all = [];
                if (orglist && orglist.length > 0) {
                    orglist.forEach(function (org) {

                        if (level <= 2) {
                            org.paddingLevel = level;
                        } else {
                            org.paddingLevel = 2;
                        }

                        if (org.children && org.children.length > 0) {

                            org.$$treeLevel = level;

                            all.push(org);
                            var temp = parseUIGridTreeList(org.children, level + 1);
                            all = _.union(all, temp);
                        } else {


                            org.$$treeLevel = level;
                            all.push(org);
                        }
                    });
                }

                return all;
            };

            // tree 数据
            var buildOrgTree = function (or, orgList) {

                var orgItem = or;
                var selfDimensionIndex = 1;

                var sublist = _.filter(orgList, function (org) {
                    return org.parentID === or.id;
                });

                var children = [];

                if (sublist != null && sublist.length > 0) {
                    sublist.forEach(function (org) {
                        var temp = buildOrgTree(org);
                        children.push(temp);
                    });
                }

                orgItem.children = children;

                return orgItem;
            };

            // 转换为UI Grid数据格式
            var parseDataGrid = function () {
                var gridData = [];

                if ($scope.panelArea.cityStatistics && $scope.panelArea.cityStatistics.length > 0) {

                    $scope.panelArea.cityStatistics.forEach(function (r) {
                        var cityItem = {
                            id: r.id,
                            name: r.name,
                            isOrganization: false,
                            businessUnitName: '',
                            structureName: '',
                            userCount: 0,
                            $$treeLevel: 0
                        };

                        gridData.push(cityItem);

                        if (r.organizationBusinessUnitStatistics && r.organizationBusinessUnitStatistics.length > 0) {
                            for (var i = 0; i <= r.organizationBusinessUnitStatistics.length - 1; i++) {
                                var or = r.organizationBusinessUnitStatistics[i];

                                var orgItem = {
                                    id: or.id,
                                    name: or.name,
                                    isOrganization: true,
                                    businessUnitName: or.businessUnitName,
                                    structureName: or.structureName,
                                    userCount: or.userCount,
                                    areaName: or.areaName,
                                    industryName: or.industryName
                                };

                                var selfDimensionIndex = 1;
                                $scope.subDimensionidList.forEach(function (id) {
                                    if (systemDimensionIdList.indexOf(id) === -1) {

                                        var targetValue = _.find($scope.dimensionOrgList, function (valueOrg) {
                                            return valueOrg.organizationID === or.id && valueOrg.dimensionID === id;
                                        });

                                        if (targetValue) {
                                            orgItem['selfDimension' + selfDimensionIndex] = targetValue.dimensionValue;
                                        } else {
                                            orgItem['selfDimension' + selfDimensionIndex] = '';
                                        }

                                    }

                                    selfDimensionIndex++;
                                });

                                cityItem.userCount += cityItem.userCount + or.userCount;
                                gridData.push(orgItem);
                            }
                        }
                    });
                }

                $log.debug("gridData:" + JSON.stringify(gridData));
                $log.debug("columns:" + JSON.stringify($scope.columns));

                $scope.areaORGGridList.data = gridData;
            };

            // 显示机构缩略图
            $scope.ShowOrgGeneralInfo = function (row, $event) {

                $scope.orgIdGeneralInfo = row.entity.id;
                var orgGeneralInfoPopup = $(orgGeneralInfoPopId);
                var a = $('#' + row.entity.id);
                showOrgCard(orgGeneralInfoPopup, a, 30, 50);
                $event.stopPropagation();
            };

            // 显示用户数卡片
            var showUserSumCard = function () {
                // 关闭其他卡片
                $scope.closeOrgCard();
                $scope.dimensionValue = $scope.panelArea.name;
                $scope.attributeName = '用户数';
                $(areaUserCardID).css('visibility', 'visible');

                $scope.userDatagridDataSource = [];
                $scope.roleCountDataSource = [];
                roleService.getActiveUserRoleListByAreaID($scope.panelArea.id).success(function (data) {

                    buildUserCardInfo(data);
                });
            };

            // 显示机构数
            var showAreaOrgCard = function () {
                // 关闭用户卡片
                $scope.closeUserCard();

                $scope.areaORGGridList.data = [];
                $scope.commonCountDataSource = [];
                if ($scope.panelArea.organizationList && $scope.panelArea.organizationList.length > 0) {
                    parseDataGridOnlyOrg();
                } else {
                    orgService.getOrganizationListByAreaID($scope.panelArea.id, $scope.selectAttribute.attributeID).success(function (data) {

                        $scope.panelArea.organizationList = data;
                        parseDataGridOnlyOrg();
                    });
                }

                $scope.isShowOrgCard = true;

                $(areaCommonCardID).css('visibility', 'visible');

                $timeout(function () {
                    $scope.gridApiAreaORGGridList.treeBase.collapseAllRows();
                }, 500);
            };

            // 根据维度展示卡片
            $scope.showDimensionCard = function (row) {

                $scope.selectAttribute = row;

                $scope.cardTitle = $scope.panelArea.name + '-' + row.attributeName;
                if (row.attributeType === constant.attributeType.User) {
                    showUserSumCard();
                    return;
                } else {
                    setColumns();
                    showAreaOrgCard();
                    return;
                }

            };

            // 构造用户卡片
            var buildUserCardInfo = function (thisAreaUserRoleList) {
                var userList = [];

                var userIdList = _.uniq(_.pluck(thisAreaUserRoleList, 'id'));

                // 当修改用户权限的时候可能会改到用户个数
                if (userIdList) {

                    var findUserAttr = _.find($scope.statisticAttrList, function (row) {
                        return row.attributeType === constant.attributeType.User;
                    });

                    if (findUserAttr) {
                        findUserAttr.count = userIdList.length;
                    }
                }

                var roleCountDataSource = [];

                userIdList.forEach(function (row) {

                    var thisUserOrgList = _.filter(thisAreaUserRoleList, function (num) {
                        return num.id === row;
                    });

                    var first = thisUserOrgList[0];
                    var item = {
                        userID: first.id,
                        userName: first.userName,
                        orgCount: thisUserOrgList.length,
                    };

                    var roleNameList = [];
                    thisUserOrgList.forEach(function (user) {
                        if (user.roleInfoList && user.roleInfoList.length > 0) {
                            var tempRoleNameList = _.pluck(user.roleInfoList, 'name');
                            roleNameList = _.union(roleNameList, tempRoleNameList);
                        }
                    });

                    roleNameList = _.uniq(roleNameList);

                    // 设置角色统计
                    for (var i = 0; i < roleNameList.length; i++) {
                        var roleName = roleNameList[i];
                        var find = _.find(roleCountDataSource, function (num) {
                            return num.name === roleName;
                        });
                        if (find) {
                            find.count++;
                        } else {
                            roleCountDataSource.push({ name: roleName, count: 1 });
                        }
                    }


                    item.roleInfo = roleNameList.join(',');
                    userList.push(item);

                });

                $scope.roleCountDataSource = roleCountDataSource;

                $scope.panelArea.userDatagridDataSource = userList;

                $scope.userDatagridDataSource = userList;

            };

            $scope.closeUserCard = function () {
                $(areaUserCardID).css('visibility', 'hidden');
            };

            // 地图上面绘制泡泡图markPoint
            var writeMap = function () {

                // clear old Map data
                $scope.chinaMapOption.series[0].markPoint.data = [];
                if ($scope.panelArea.cityStatistics && $scope.panelArea.cityStatistics.length > 0) {
                    $scope.panelArea.cityStatistics.forEach(function (row) {
                        var item = {
                            name: row.name,
                            coord: [row.longitude, row.latitude]
                        };

                        if (row.organizationBusinessUnitStatistics && row.organizationBusinessUnitStatistics.length > 0) {
                            $scope.chinaMapOption.series[0].markPoint.data.push(item);
                        }
                    });
                }

                $scope.chinaMapOption.color = [$scope.panelArea.theme.value];
                $scope.chinaMapChart.setOption($scope.chinaMapOption);
            };

            // 选中区域
            $scope.chooseArea = function (areaInfo) {


                $scope.isChooseAllArea = false;
                //$scope.closeUserCard();
                //$scope.closeOrgCard();
                $scope.panelArea = areaInfo;
                setAreaStatisticAttrOrgCount();

                //var firstDimension = null;
                //var secondDimension = null;
                //$scope.belowDimensionList = [];

                //if ($scope.statisticAttrList) {

                //    if ($scope.statisticAttrList.length > 0) {
                //        firstDimension = $scope.statisticAttrList[0];
                //    }

                //    if ($scope.statisticAttrList.length > 1) {
                //        secondDimension = $scope.statisticAttrList[1];
                //    }

                //    if ($scope.statisticAttrList.length > 2) {

                //        for (var i = 2; i < $scope.statisticAttrList.length; i++) {
                //            var row = $scope.statisticAttrList[i];
                //            $scope.belowDimensionList.push(row);
                //        }
                //    }
                //}

                //$scope.firstDimension = firstDimension;
                //$scope.secondDimension = secondDimension;

                setMapData();
                //hideOrgGeneralInfo();

                thisCardService.closeALLCard();
                //$timeout(function () {
                //    // writeMap();
                //    setMapData();
                //    hideOrgGeneralInfo();
                //    $scope.hideCard();
                //}, 10);
            };

            // choose all area
            $scope.chooseAllArea = function () {
                // body...
                $scope.isChooseAllArea = true;
                $scope.closeUserCard();
                $scope.closeOrgCard();
                $scope.panelArea = {};

                setAllAreaMapData();
                //$timeout(function () {
                //    setAllAreaMapData();
                //}, 10);
            };

            // 自定义维度机构树
            var selfDimensionOrgTree = function (thisAreaOrgList, targetDimensionValueList) {
                var dimensionValueObjList = [];

                targetDimensionValueList.forEach(function (row) {
                    var find = _.find(dimensionValueObjList, function (num) {
                        return num.id === row.dimensionValueID;
                    });

                    if (!find && row.dimensionValue) {
                        var item = {
                            id: row.dimensionValueID,
                            name: row.dimensionValue
                        };

                        dimensionValueObjList.push(item);
                    }
                });

                return buildDimensionTreeList(thisAreaOrgList, dimensionValueObjList, targetDimensionValueList);
            };

            // 构造维度机构树
            var buildDimensionTreeList = function (thisAreaOrgList, dimensionValueObjList, targetDimensionValueList) {
                dimensionValueObjList = _.sortBy(dimensionValueObjList, 'name');
                var treeList = [];

                $scope.commonCountDataSource = [];
                dimensionValueObjList.forEach(function (attr) {

                    var dimensionOrgList = _.filter(targetDimensionValueList, function (row) {
                        return row.dimensionValueID === attr.id;
                    });

                    var orgidlist = _.pluck(dimensionOrgList, 'organizationID');

                    var itemCount = {};
                    itemCount.name = attr.name;
                    itemCount.count = orgidlist.length;
                    $scope.commonCountDataSource.push(itemCount);

                    var orgList = _.filter(thisAreaOrgList, function (org) {
                        return orgidlist.indexOf(org.id) > -1;
                    });

                    var firstNode = {};
                    firstNode.id = attr.id;
                    firstNode.name = attr.name;
                    firstNode.isOrg = false;
                    firstNode.$$treeLevel = 0;

                    treeList.push(firstNode);


                    orgList.forEach(function (org) {

                        var orgItem = org;
                        orgItem.isOrg = true;
                        orgItem.paddingLevel = 1;
                        //var orgItem = {
                        //    id: org.id,
                        //    name: org.name,
                        //    isOrg: true,
                        //    paddingLevel: 1,
                        //};

                        treeList.push(orgItem);
                    });
                });

                return treeList;
            };

            // 系统级维度树
            var systemDimensionOrgTree = function (thisAreaOrgList, idCol, nameCol) {
                var dimensionValueObjList = [];
                thisAreaOrgList.forEach(function (row) {

                    var find = _.find(dimensionValueObjList, function (num) {
                        return num.id === row[idCol];
                    });

                    if (!find && row[nameCol]) {
                        var item = {
                            id: row[idCol],
                            name: row[nameCol]
                        };

                        dimensionValueObjList.push(item);
                    }

                });

                dimensionValueObjList = _.sortBy(dimensionValueObjList, 'name');

                var treeList = [];
                $scope.commonCountDataSource = [];
                dimensionValueObjList.forEach(function (attr) {

                    var itemCount = {};
                    itemCount.name = attr.name;

                    var orgList = _.filter(thisAreaOrgList, function (org) {
                        return org[idCol] === attr.id;
                    });

                    var firstNode = {};
                    firstNode.id = attr.id;
                    firstNode.name = attr.name;
                    firstNode.isOrg = false;
                    firstNode.$$treeLevel = 0;

                    treeList.push(firstNode);

                    itemCount.count = orgList.length;
                    $scope.commonCountDataSource.push(itemCount);
                    orgList.forEach(function (org) {
                        var orgItem = org;
                        orgItem.isOrg = true;
                        orgItem.paddingLevel = 1;
                        //var orgItem = {
                        //    id: org.id,
                        //    name: org.name,
                        //    isOrg: true,
                        //    paddingLevel: 1,
                        //};

                        treeList.push(orgItem);
                    });
                });

                return treeList;

            };

            // 设置每个维度的个数、事业部,统计这个区域下有几个事业部 
            var setAreaStatisticAttrOrgCount = function () {

                var thisAreaOrgList = _.filter($scope.organizationList, function (num) {
                    return num.areaID === $scope.panelArea.id;
                });

                var orgidList = _.pluck(thisAreaOrgList, 'id');

                $scope.panelArea.organizationCount = orgidList.length;

                $scope.panelArea.organizationIDList = orgidList;

                // 设置每个维度的个数
                $scope.statisticAttrList.forEach(function (row) {

                    row.count = $scope.panelArea.attributeStatics[row.attributeID];
                    //var orgList = [];

                    //if (row.attributeType === constant.attributeType.SelfDimension) {

                    //    var targetDimensionValueList = _.filter($scope.dimensionOrgList, function (data) {
                    //        return data.dimensionID === row.belongDimensionID && orgidList.indexOf(data.organizationID) > -1;
                    //    });

                    //    if (targetDimensionValueList && targetDimensionValueList.length > 0) {
                    //        orgList = _.uniq(_.pluck(targetDimensionValueList, 'dimensionValueID'));
                    //    }

                    //} else if (row.attributeType === constant.attributeType.RegionID) {
                    //    // 行政省市

                    //    var administrativeAreaIDList = _.uniq(_.pluck(thisAreaOrgList, 'cityID'));
                    //    row.count = administrativeAreaIDList.length;
                    //} else if (row.attributeType === constant.attributeType.Unknown) {
                    //    // 未知不做
                    //} else if (row.attributeType === constant.attributeType.User) {
                    //    // 用户 不做
                    //    row.count = $scope.panelArea.userCount;
                    //} else if (row.attributeType === constant.attributeType.OrgSubChildren) {
                    //    // 机构个数
                    //    row.count = orgidList.length;
                    //} else {
                    //    var idCol = constant.attributeTypeIDColMap[row.attributeType];
                    //    orgList = _.uniq(_.pluck(thisAreaOrgList, idCol));
                    //}

                    //if (orgList && orgList.length > 0) {

                    //    orgList = _.filter(orgList, function (num) {
                    //        if (num) {
                    //            return true;
                    //        } else {
                    //            return false;
                    //        }
                    //    });

                    //    row.count = orgList.length;
                    //}
                });
            };

            // 统计用户数
            var setUserCount = function () {

                $scope.panelArea.userCount = 0;

                if ($scope.userRoleList && $scope.userRoleList.length > 0) {
                    var filterList = _.filter($scope.userRoleList, function (row) {

                        return row.areaID === $scope.panelArea.id;
                    });

                    if (filterList && filterList.length > 0) {
                        var userIdList = _.uniq(_.pluck(filterList, 'id'));
                        $scope.panelArea.userCount = userIdList.length;
                    }
                }
            };

            // 隐藏机构数
            $scope.closeOrgCard = function () {
                $(areaCommonCardID).css('visibility', 'hidden');
            };

            // 显示卡片
            $scope.showCard = function () {
                // parseDataGrid();
                parseDataGridOnlyOrg();
                $scope.isShowCard = true;
                $timeout(function () {
                    $scope.gridApiareaDimensionORGGridList.treeBase.collapseAllRows();
                }, 500);
            };

            // 隐藏机构缩略图
            var hideOrgGeneralInfo = function () {
                $(orgGeneralInfoPopId).hide();
            };

            // 设置UI grid的列
            var setColumns = function () {

                if ($scope.columns.length > 1) {
                    $scope.columns.splice(1);
                }

                if ($scope.statisticAttrList && $scope.statisticAttrList.length > 0) {

                    for (var i = 0; i < $scope.statisticAttrList.length; i++) {
                        var row = $scope.statisticAttrList[i];

                        var index = i + 1;

                        if (row.attributeID === $scope.selectAttribute.attributeID) {
                            continue;
                        }

                        if (row.attributeType === constant.attributeType.SelfDimension) {

                            var str = '<div class="text-align-left text-align-left-padding"><span title="{{row.entity.selfDimension' + index + '}}">{{row.entity.selfDimension' + index + '|limitString:16}}</span></div>';
                            var nameCol = 'selfDimension' + index;

                            var businessUnit = {
                                field: nameCol,
                                name: row.attributeName,
                                headerCellClass: '',
                                cellTemplate: str
                            };

                            $scope.columns.push(businessUnit);
                        } else if (row.attributeType === constant.attributeType.Unknown) {
                            // 未知不做
                        } else if (row.attributeType === constant.attributeType.User) {
                            // 用户不做
                        } else if (row.attributeType === constant.attributeType.OrgSubChildren) {
                            // 机构个数
                        } else if (row.attributeType === constant.attributeType.RegionID) {
                            // 行政省市
                            var str = '<div class="text-align-left text-align-left-padding"><span title="{{row.entity.regionName}}">{{row.entity.regionName|limitString:16}}</span></div>';
                            var nameCol = 'regionName';
                            var businessUnit = {
                                field: nameCol,
                                name: row.attributeName,
                                headerCellClass: '',
                                cellTemplate: str
                            };

                            $scope.columns.push(businessUnit);
                        } else {
                            var idCol = constant.attributeTypeIDColMap[row.attributeType];
                            var nameCol = constant.attributeTypeNameColMap[row.attributeType];

                            var str = '<div class="text-align-left text-align-left-padding"><span title="{{row.entity.' + nameCol +
                                '}}">{{row.entity.' + nameCol + '|limitString:16}}</span></div>';

                            var nameStr = row.attributeName;
                            if (row.attributeType === constant.attributeType.OrgSubChildren ||
                                row.attributeType === constant.attributeType.OrganizationStructure) {
                                nameStr = $translate.instant('OrganizationLevelType');
                            }
                            var businessUnit = {
                                field: nameCol,
                                name: nameStr,
                                headerCellClass: '',
                                cellTemplate: str
                            };

                            $scope.columns.push(businessUnit);
                        }

                    }

                }

            };

            // 设置选中区域地图背景色
            var setMapData = function () {
                $scope.chinaMapOption.series[0].data = [];
                if ($scope.panelArea.provinceNameList &&
                    $scope.panelArea.provinceNameList.length > 0
                ) {
                    var reg = /省$/gi;
                    var cityreg = /市$/gi;


                    var provinceNameList = $scope.panelArea.provinceNameList;

                    provinceNameList.forEach(function (provinceName) {

                        var provinceNameShow = provinceName;
                        if (provinceName === '香港特别行政区') {
                            provinceNameShow = '香港';
                        } else if (provinceName === '澳门特别行政区') {
                            provinceNameShow = '澳门';
                        } else {
                            provinceNameShow = provinceName.replace(reg, '').replace(cityreg, '')
                        }

                        var item = {
                            name: provinceNameShow,
                            itemStyle: {
                                normal: {
                                    areaColor: $scope.panelArea.theme.lightColor
                                }
                            },
                            label: {
                                normal: {
                                    show: true,
                                    textStyle: {
                                        color: '#894A00',
                                        fontWeight: 'normal'
                                    }
                                }
                            }
                        };

                        $scope.chinaMapOption.series[0].data.push(item);

                    });
                };

                $scope.chinaMapChart.setOption($scope.chinaMapOption);
            };

            // choose all area
            var setAllAreaMapData = function () {
                $scope.chinaMapOption.series[0].data = [];
                if ($scope.areaInfoList && $scope.areaInfoList.length > 0) {
                    var reg = /省$/gi;
                    var cityreg = /市$/gi;
                    $scope.areaInfoList.forEach(function (row) {

                        if (row.provinceNameList && row.provinceNameList.length > 0) {
                            var provinceNameList = row.provinceNameList;

                            provinceNameList.forEach(function (provinceName) {

                                var provinceNameShow = provinceName;
                                if (provinceName === '香港特别行政区') {
                                    provinceNameShow = '香港';
                                } else if (provinceName === '澳门特别行政区') {
                                    provinceNameShow = '澳门';
                                } else {
                                    provinceNameShow = provinceName.replace(reg, '').replace(cityreg, '')
                                }

                                var item = {
                                    name: provinceNameShow,
                                    itemStyle: {
                                        normal: {
                                            areaColor: row.theme.lightColor
                                        }
                                    },
                                    label: {
                                        normal: {
                                            show: true,
                                            textStyle: {
                                                color: '#894A00',
                                                fontWeight: 'normal'
                                            }
                                        }
                                    }
                                };

                                $scope.chinaMapOption.series[0].data.push(item);
                            });
                        }
                    });
                }

                $scope.chinaMapChart.setOption($scope.chinaMapOption);
            };

            // 隐藏卡片
            $scope.hideCard = function () {
                $scope.isShowCard = false;
                hideOrgGeneralInfo();
            };

            // 添加区域
            $scope.addRegion = function ($event) {
                $scope.regionOperateType = 'add';
                $scope.isRegionUpdate = false;
                $scope.selectedRegion = null;
                $event.stopPropagation();
            };

            // 编辑区域
            $scope.editRegion = function (areaInfo, $event) {
                $scope.regionOperateType = 'edit';
                $scope.selectedRegion = {
                    id: areaInfo.id
                };

                $scope.isRegionUpdate = false;
                $event.stopPropagation();
            };

            // 添加或者编辑区域成功之后,刷新当前页面的数据
            $scope.$watch('isRegionUpdate', function (newValue, oldValue) {
                if (newValue) {
                    getAreaStatistics();
                }
            });

            // 添加机构
            $scope.addOrg = function ($event) {
                $scope.orgOperateType = 'add';

                $scope.newOrganization = {
                    areaID: $scope.panelArea.id,
                    areaName: $scope.panelArea.name
                };

                $scope.selectedOrg = null;
                $event.stopPropagation();
            };

            //添加现有机构到当前的维度
            $scope.addExistOrg = function () {
                $scope.selectedKeyItems = [];

                var selectedKeyItem = $scope.panelArea.organizationIDList;

                $scope.selectedKeyItems = selectedKeyItem;
                $scope.addExistOrgOperateType = constant.Operation.Add;
                $scope.addExistOrgIsUpdate = false;
                $scope.addExistOrgDimensionValueID = $scope.panelArea.id;

            };

            // add exist org succes and refresh page
            $scope.$watch('addExistOrgIsUpdate', function (newValue, oldValue) {
                if (newValue) {

                    if ($scope.selectedExistOrgList && $scope.selectedExistOrgList.length > 0) {
                        orgService.updateOrgToDimension($scope.panelArea.id, $scope.parentDimensionID, $scope.selectedExistOrgList).success(function (data) {
                            if (data && !data.result) {

                                SweetAlert.warning($translate.instant(data.resultMsg));
                                return;
                            }

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

            // 添加或者编辑机构成功之后,刷新当前页面的数据
            $scope.$watch('isOrgUpdate', function (newValue, oldValue) {
                if (newValue) {
                    init();
                }
            });

            //自定义显示内容修改
            $scope.$watch('isAttributeUpdate', function (newValue, oldValue) {
                if (newValue) {
                    getAreaStatistics();
                }
            });

            // 获取所有机构
            var getAllOrgList = function () {

                // var organizationList = [];

                // {
                //     areaList:[{
                //             id:'',
                //             name:'',
                //             cityStatistics:[
                //                 {
                //                     RegionID:'',
                //                     AreaID:'',
                //                     Name:'',
                //                     ProvinceName:'',
                //                     Longitude:'',
                //                     Latitude:'',
                //                 },
                //             ]
                //     }]
                //     organizationList:[{
                //             ID:'',
                //             Name:'',
                //             ParentID:'',
                //             BusinessUnitID:'',
                //             BusinessUnitName:'',
                //             UserCount:'',
                //             RegionID:'',
                //             IndustryID:'',
                //             IndustryName:'',
                //             StructureID:'',
                //             StructureName:'',
                //     }]
                // }

                if ($scope.originalData && $scope.originalData.areaList.length > 0) {
                    $scope.originalData.areaList.forEach(function (area) {
                        if (area.cityStatistics && area.cityStatistics.length > 0) {
                            area.cityStatistics.forEach(function (city) {
                                city.organizationBusinessUnitStatistics = _.filter($scope.originalData.organizationList, function (org) {
                                    return org.cityID === city.regionID;
                                });
                            });
                        }

                    });
                };

                return $scope.originalData.organizationList;
            };

            // 以区域划分s属性
            var showDimensionByArea = function (idcol, namecol, dimensionName, attributeID) {
                // 第一个纬度始终是区域
                $scope.organizationList = _.sortBy($scope.organizationList, 'areaName');
                var structureidList = _.uniq(_.pluck($scope.organizationList, 'areaID'));
                $scope.areaInfoList = [];
                var structureList = [];
                if ($scope.originalData.areaList && $scope.originalData.areaList.length > 0) {

                    $scope.originalData.areaList.forEach(function (row) {
                        var model = {};
                        model.id = row.id;
                        model.name = row.name;
                        model.organizationCount = 0;
                        model.userCount = row.userCount;
                        if (!model.name) {
                            model.name = defaultValue.unknownArea;
                            model.id = '';
                        }

                        var areaIDList = _.uniq(_.pluck(row.cityStatistics, 'areaID'));

                        var matchOrgList = _.filter($scope.organizationList, function (num) {
                            return num.areaID === row.id;
                        });

                        model.cityStatistics = [];

                        if (matchOrgList && matchOrgList.length > 0) {

                            model.orgIDList = _.pluck(matchOrgList, 'id');
                            if (attributeID) {
                                model.cityStatistics = getSelfAttributeCityStatistics(attributeID, matchOrgList);
                            } else {
                                model.cityStatistics = getSystemAttributeCityStatistics(row, idcol, namecol, matchOrgList);
                            }

                            $scope.areaInfoList.push(model);

                            model.organizationCount = matchOrgList.length;
                        }
                    });
                }

                // 未设置部分
                var notsetOrgList = _.filter($scope.organizationList, function (org) {
                    return !org.areaID;
                });

                if (notsetOrgList && notsetOrgList.length > 0) {
                    var model = {};
                    // model.id = 'noset' + idcol;
                    model.name = defaultValue.notSetAttribute;

                    if (attributeID) {
                        model.cityStatistics = getSelfAttributeCityStatistics(attributeID, notsetOrgList);
                    } else {
                        model.cityStatistics = getSystemAttributeCityStatistics(idcol, namecol, notsetOrgList);
                    }

                    $scope.areaInfoList.push(model);
                }

                renderUI();
            };

            // 按照系统属性构造数据
            var getSystemAttributeCityStatistics = function (area, idcol, namecol, matchOrgList) {
                var cityStatistics = [];
                if (!matchOrgList || matchOrgList.length === 0) {
                    return cityStatistics;
                }

                matchOrgList = sortAttribute(matchOrgList, namecol);

                var attributeList = [];


                if (idcol === 'businessUnitID') {
                    // 事业部
                    attributeList = $scope.originalData.businessUnitList;

                } else if (idcol === 'structureID') {

                    // 行业
                    attributeList = $scope.originalData.organizationStructureList;

                } else if (idcol === 'industryID') {
                    // 机构层级
                    attributeList = $scope.originalData.industryList;

                } else if (idcol === 'cityID') {

                    if (area.cityStatistics && area.cityStatistics.length > 0) {
                        area.cityStatistics.forEach(function (city) {
                            var cityItem = {};
                            cityItem.organizationBusinessUnitStatistics = _.filter(matchOrgList, function (org) {
                                return org.cityID === city.regionID;
                            });;
                            cityItem.name = city.name;
                            cityItem.id = city.regionID;
                            cityStatistics.push(cityItem);
                        });
                    }

                    return cityStatistics;
                }

                var setOrgIDList = [];
                if (attributeList && attributeList.length > 0) {
                    attributeList.forEach(function (attr) {
                        var cityItem = {};
                        cityItem.organizationBusinessUnitStatistics = _.filter(matchOrgList, function (num) {
                            return num[idcol] === attr.id;
                        });

                        cityItem.name = attr.name;
                        cityItem.id = attr.id;

                        if (cityItem.organizationBusinessUnitStatistics && cityItem.organizationBusinessUnitStatistics.length > 0) {
                            var orgidList = _.pluck(cityItem.organizationBusinessUnitStatistics, 'id');
                            setOrgIDList = _.union(setOrgIDList, orgidList);
                        }

                        cityStatistics.push(cityItem);
                    });

                    if (setOrgIDList && setOrgIDList.length === matchOrgList.length) {
                        // 全部设置完毕
                    } else {
                        // 未设置
                        var cityItem = {};
                        cityItem.id = idcol + 'notSet';
                        cityItem.name = defaultValue.notSetAttribute;
                        cityItem.organizationBusinessUnitStatistics = _.filter(matchOrgList, function (org) {
                            return setOrgIDList.indexOf(org.id) === -1;
                        });

                        cityStatistics.push(cityItem);
                    }
                }

                return cityStatistics;
            };

            // 按照自定义属性去构造数据
            var getSelfAttributeCityStatistics = function (attributeID, matchOrgList) {
                var dimensionID = $scope.statisticAttrList[0].belongDimensionID;
                var targetDimensionValueList = _.filter($scope.dimensionOrgList, function (data) {
                    return data.dimensionID === dimensionID;
                });
                var dimensionVauleIDList = _.uniq(_.pluck(targetDimensionValueList, 'dimensionValueID'));

                var cityStatistics = [];

                var setOrgIDList = [];
                if (dimensionVauleIDList && dimensionVauleIDList.length > 0) {
                    dimensionVauleIDList.forEach(function (valueID) {
                        var cityItem = {};
                        var relaventOrgList = _.filter(targetDimensionValueList, function (org) {
                            return org.dimensionValueID === valueID;
                        });

                        if (relaventOrgList && relaventOrgList.length > 0) {
                            cityItem.name = relaventOrgList[0].dimensionValue;

                            var orgidList = _.uniq(_.pluck(relaventOrgList, 'organizationID'));

                            cityItem.organizationBusinessUnitStatistics = _.filter(matchOrgList, function (num) {
                                return orgidList.indexOf(num.id) > -1;
                            });

                            if (orgidList && orgidList.length > 0) {
                                setOrgIDList = _.union(setOrgIDList, orgidList);
                            }

                            cityStatistics.push(cityItem);
                        }

                    });
                }

                if (setOrgIDList.length === matchOrgList.length) {
                    // 全部设置好属性的
                } else {

                    var notSetAttributeList = _.filter(matchOrgList, function (org) {
                        return setOrgIDList.indexOf(org.id) === -1;
                    });

                    if (notSetAttributeList && notSetAttributeList.length > 0) {
                        var cityItem = {};
                        cityItem.name = defaultValue.notSetAttribute;
                        cityItem.organizationBusinessUnitStatistics = notSetAttributeList;
                        cityStatistics.push(cityItem);
                    }

                }

                return cityStatistics
            };

            // 切换主 纬度的时候, 渲染UI
            var renderUI = function () {
                generateID();
                $scope.hideCard();
                //setColumns();


                // default choose all area
                var findArea = null;
                if ($scope.panelArea && $scope.panelArea.id) {

                    findArea = _.find($scope.areaInfoList, function (row) {
                        return row.id === $scope.panelArea.id;
                    });
                }

                if (findArea) {
                    $scope.chooseArea(findArea);
                } else {
                    $scope.chooseAllArea();
                }

            };

            // 获取所有机构设置的自定义纬度
            var getAllDimensionOrgList = function () {
                dimensionService.getAllDimensionOrgList().success(function (data) {
                    $scope.dimensionOrgList = data;
                });
            };

            // 初始化数据
            var init = function () {
                // 获取区域统计数据
                getAreaStatistics();

                // 获取所有机构设置的自定义纬度
                getAllDimensionOrgList();
            };

            // 排序方法,包含中英文
            var sortAttribute = function (data, colName) {
                if (data && data.length > 0) {
                    try {
                        var charList = [];
                        var nocharList = [];
                        var digitalReg = /^\d+/;
                        var charReg = /^[a-zA-Z]+/;
                        data.forEach(function (row) {
                            if (digitalReg.test(row[colName]) || charReg.test(row[colName])) {
                                charList.push(row);
                            } else {
                                nocharList.push(row);
                            }

                        });

                        charList = _.sortBy(charList, colName);

                        nocharList = nocharList.sort(function compareFunction(param1, param2) {
                            return param1[colName].localeCompare(param2[colName]);
                        });

                        var all = _.union(charList, nocharList);
                        return all;
                    } catch (e) {
                        $log.debug("sort exception:" + e);
                    }
                }

                return data;
            };

            // 出事化参数
            var initParams = function () {
                $scope.orgIdGeneralInfo = null;
                $scope.isRenderCompletedGeneralInfo = false;
                $scope.isShowUserCard = false;
                $scope.isShowCard = false;
                $scope.isShowOrgCard = false;
                $scope.isChooseAllArea = true;
            };

            // 显示机构缩略图,并设置好位置
            var showOrgCard = function (pop, row, topOffset, leftOffset) {

                pop.css("display", "block");
                var top = window.innerHeight - pop.height();
                if (row.offset().top + topOffset < window.innerHeight - pop.height()) {
                    top = row.offset().top + topOffset;
                }

                pop.css('top', top + 'px');

                var left = window.innerWidth - pop.width();
                if (row.offset().left + leftOffset < window.innerWidth - pop.width()) {
                    left = row.offset().left - leftOffset;
                }

                pop.css('left', left + 'px');

                pop.show();

                $(document).one('click', function () {
                    hideOrgGeneralInfo();
                });
            };

            //show自定义显示属性
            $scope.showCustomAttriute = function () {

                $scope.statisticAttrListCopy = $scope.statisticAttrList;
                $scope.attributeOperateType = constant.Operation.Edit;
                $scope.showAttributeDimensionID = $scope.parentDimensionID;
                $scope.isAttributeUpdate = false;
            };

            // 获取机构区域统计
            var getAreaStatistics = function () {
                orgService.getAreaStatistics().success(function (data) {
                    $scope.originalData = data;
                    $scope.organizationList = data.organizationList;
                    $scope.areaInfoList = data.areaList;

                    $scope.statisticAttrList = data.attributeList;

                    renderUI();
                    //getStatisticAttribute();
                });
            };

            // 获取设置过的纬度值
            var getStatisticAttribute = function () {
                statisticAttributeService.getByParentDimensionID($scope.parentDimensionID).success(function (data) {
                    if (data) {

                        //$scope.statisticAttrList = data;
                        //renderUI();
                        // switchByCustomAttriute();
                    }
                });
            };


            $scope.userBUSetting = function () {
                $scope.userBUOperateType = constant.Operation.Edit;
                $scope.userBUIsUpdate = false;
                $scope.userBUDimensionID = $scope.parentDimensionID;
                $scope.userBUDimensionValueID = $scope.panelArea.id; //dimensionValueID,如事业部1,事业部2,产品线1 等
            };

            // 获取用户权限
            var getUserPermission = function () {

                var list = [];
                var editRegionCode = constant.adminPermission.basicData.areaManage.editCode;
                var orgPermission = constant.adminPermission.infrastructure.organizationManage.addCode;
                //自定义显示属性的权限
                var tempAttr = constant.adminPermission.infrastructure.customAttribute;
                list.push(editRegionCode);
                list.push(orgPermission.addCode);
                list.push(orgPermission.editCode);
                list.push(tempAttr.queryCode);

                //权限设置的权限
                var tempAcess = constant.adminPermission.infrastructure.accessSetting;
                list.push(tempAcess.queryCode);
                list.push(tempAcess.editCode);

                $scope.$root.checkUserPermissionList(list).success(function (data) {
                    $scope.hasEditRegionPermission = data[editRegionCode];
                    $scope.hasAddOrgPermission = data[orgPermission.addCode];
                    $scope.hasEditOrgPermission = data[orgPermission.addCode];
                    $scope.hasAttributeQueryPermission = data[tempAttr.queryCode];


                    $scope.hasAccessSettingQueryPermission = data[tempAcess.queryCode];
                    $scope.hasAccessSettingEditPermission = data[tempAcess.editCode];
                });
            };

            //用户权限更新,刷新orgchart
            $scope.$watch('userBUIsUpdate', function (newValue, oldValue) {
                if (newValue) {
                    showUserSumCard();
                    $scope.userBUIsUpdate = false;
                }
            });

            // UI 服务
            var thisCardService = {

                closeALLCard: function () {

                    // 用户和机构卡片
                    $('.card').css('visibility', 'hidden');

                    // 机构general
                    $(orgGeneralInfoPopId).hide();
                } 
            };

            (function initialize() {
                $log.debug('OrganizationAreaViewController.ctor()...' + $state.params.dimensionID);
                $log.debug($state.params.dimensionID);
                var dimensionID = constant.dimensionID.areaID;

                $scope.parentDimensionID = $state.params.dimensionID || dimensionID;
                $scope.showAttributeDimensionID = $scope.parentDimensionID;
                $scope.panelArea = {};
                getUserPermission();

                // uigrid 定义
                init();

                initParams();

                // 总机构数统计
                areaORGGridInit();

                // 初始化维度展示列表
                areaDimensionORGGridListInit();

                // 用户卡片里面的devGrid
                initUserSumDevGrid();

                $scope.userRoleList = [];

                drawChinaMap();

                $scope.forceOrgUpdate = false;
            })();
        }
    ]);

infrastructureModule.directive('organizationAreaView', ['$log',
    function ($log) {
        'use strict';
        $log.debug('organizationAreaView.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/organizationAreaView/organization-area-view.html' + '?_=' + Math.random(),
            scope: {},
            replace: true,
            controller: 'OrganizationAreaViewController',
            link: function (scope, element) {

                // 可以拖拽
                $(".card").draggable({ containment: "parent", cursor: "cursor", handle: ".card-header" });

            }
        };
    }
]);
infrastructureModule
    .controller('organizationBusinessUnitViewController', ['$scope', '$log', 'SweetAlert', '$translate', 'uiGridTreeViewConstants', 'uiGridConstants', '$timeout', 'orgService', 'statisticAttributeService', 'dimensionService', '$state', '$stateParams', '$interval', 'roleService', '$q','userService',
        function ($scope, $log, SweetAlert, $translate, uiGridTreeViewConstants, uiGridConstants, $timeout, orgService, statisticAttributeService, dimensionService, $state, $stateParams, $interval, roleService, $q, userService) {
            'use strict';
            // 机构缩略图ID
            var orgGeneralInfoPopId = '#orgGeneralInfoPop';

            var template = {
                topNodeTemplate: $("#dimension-topNode").html(),  //最顶层节点
                nameNodeEdit: $("#dimension-node-name-edit").html(),  //机构名称
                nameNodeQuery: $("#dimension-node-name-query").html(),  //机构名称
                hightNode: $("#dimension-hight-node").html(), //子分公司,高亮部分
                rowNode: $("#dimension-row-node").html() //普通行
            };

            var ReplaceObj = {
                //顶部节点
                topNodeName: '{{#topNodeName#}}',
                //事业部名称
                dimensionValue: '{{#dimensionValue#}}',
                dimensionValueID: '{{#dimensionValueID#}}',
                createNewOrg: '{{#AddOrganization#}}',
                addExistOrg: '{{#AddExistOrganization#}}',
                //高亮部分统计
                //hightNodeCount: '{{#dimensionValueCount#}}', //比如 '100'
                //hightNodeName: '{{#attributeName#}}',   //比如'分公司'
                //普通维度统计
                attributeID: '{{#attributeID#}}',
                attributeName: '{{#attributeName#}}',  //维度名字,如用户数,覆盖区域,所属行业等
                attributeValueCount: '{{#attributeValueCount#}}',      //对于维度的统计
                attributeType: '{{#attributeType#}}'             //维度的类型区分值,如1:事业部,2:分公司
            };

            var showWarning = function (resultMsg) {

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

            var showSuccessMsg = function (resultMsg) {

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

            var createNewOrg = $translate.instant('AddOrganization');
            var addExistOrg = $translate.instant('AddExistOrganization');
            var unassisgnText = $translate.instant('UnAssignText');
            $scope.unassisgnText = unassisgnText;
            //构造Echart模板,并且初始化数据
            var PopulateChartDatasource = function () {
                //如果没有编辑维度值的权限,则不显示编辑的笔icon
                var templateNameNode = template.nameNodeQuery;
                if ($scope.hasDimensionValueEditPermission) {
                    templateNameNode = template.nameNodeEdit;
                };

                orgService.getOrgDashboard($scope.parentDimensionID).success(function (data) {
                    //重置 orgchart
                    $scope.renderOrgChart({});

                    if (data !== undefined && data !== null && data.length > 0) {
                        //console.log(JSON.stringify(data));
                        var topNodeName = template.topNodeTemplate.replace(ReplaceObj.topNodeName, $scope.parentDimensionName);

                        var datascource = {
                            'name': topNodeName,
                            'children': []
                        };

                        data.forEach(function (row) {
                            var temp = [];
                            var node = {
                                'name': templateNameNode.replaceToEnd(ReplaceObj.dimensionValue, row.dimensionValue)
                                    .replaceToEnd(ReplaceObj.dimensionValueID, row.dimensionValueID),

                                'title': (function () {

                                    row.orgDtoList.forEach(function (item, index) {

                                        if (index == 0) //第一条数据为高亮数据
                                        {
                                            temp = template.hightNode.replaceToEnd(ReplaceObj.attributeName, item.attributeName)
                                                .replaceToEnd(ReplaceObj.attributeValueCount, item.attributeValueCount)
                                                .replaceToEnd(ReplaceObj.dimensionValueID, row.dimensionValueID)
                                                .replaceToEnd(ReplaceObj.dimensionValue, row.dimensionValue)
                                                .replaceToEnd(ReplaceObj.attributeID, item.attributeID)
                                                .replaceToEnd(ReplaceObj.createNewOrg, createNewOrg)
                                                .replaceToEnd(ReplaceObj.addExistOrg, addExistOrg)
                                               .replaceToEnd(ReplaceObj.attributeType, item.attributeType);
                                        }
                                        else {
                                            temp += template.rowNode.replaceToEnd(ReplaceObj.attributeName, item.attributeName)
                                                  .replaceToEnd(ReplaceObj.attributeValueCount, item.attributeValueCount)
                                                  .replaceToEnd(ReplaceObj.dimensionValueID, row.dimensionValueID)
                                                  .replaceToEnd(ReplaceObj.dimensionValue, row.dimensionValue)
                                                 .replaceToEnd(ReplaceObj.attributeID, item.attributeID)
                                                 .replaceToEnd(ReplaceObj.attributeType, item.attributeType);
                                        }
                                    });
                                    return temp;

                                })()
                            }

                            datascource.children.push(node);
                        });

                        //生成orgchart
                        $scope.renderOrgChart(datascource);
                    }
                });
            };

            //将角色列表换成逗号分隔
            var formatRoleList = function (roleInfoList) {
                var newList = "";
                roleInfoList.forEach(function (row) {
                    if (row) {
                        newList += row.name + constant.comma;
                    }
                });
                if (newList.length > 0) {
                    newList = newList.substr(0, newList.length - 1);
                }

                return newList;
            };


            var array_unique = function (array) {
                var unique = [];
                for (var i = 0 ; i < array.length ; ++i) {
                    if (unique.indexOf(array[i]) == -1)
                        unique.push(array[i]);
                }
                return unique;
            }

            //用户卡片弹框
            var getUserStatisCard = function (dimensionValueID, dimensionValue, attributeName, attributeID) {

                $scope.userBUDimensionValueID = dimensionValueID;
                $scope.dimensionValue = dimensionValue;
                $scope.attributeName = attributeName;

                userService.getDimensionUserRoleList($scope.parentDimensionID, dimensionValueID).success(function (data) {
                    if (data) {

                        var groupByRole = _.groupBy(data, function (item) {
                            return item.roleID;
                        });

                        var dataRoleList = _.map(groupByRole, function (group) {
                            return {
                                roleID: group[0].roleID,
                                roleName: group[0].roleName
                            }
                        });
                        //角色下面,多少个用户
                        var roleSource = [];
                        dataRoleList.forEach(function (row) {
                            var filterData = _.filter(data, function (item) { return item.roleID == row.roleID; });
                            var userData = array_unique(_.pluck(filterData, 'userID'));  //用户下 去重复,一个用户,2个机构,同一个角色,统计算一个角色
                            var roleName = row.roleName;
                            var object = {
                                name: roleName,
                                count: userData.length
                            }
                            roleSource.push(object);
                        });

                        $scope.roleCountDataSource = roleSource;

                        //用户下面多个角色,多少个机构
                        var groupByUser = _.groupBy(data, function (item) {
                            return item.userID;
                        });

                        var dataUserList = _.map(groupByUser, function (group) {
                            return {
                                userID: group[0].userID,
                                userName: group[0].userName
                            }
                        });

                        var userSource = [];
                        dataUserList.forEach(function (row) {
                            var filterData = _.filter(data, function (item) { return item.userID == row.userID; });
                            var roleNames = array_unique(_.pluck(filterData, 'roleName')); //用户下的角色
                            var orgIDList = array_unique(_.pluck(filterData, 'orgID')); //用户下的访问机构数

                            var object = {
                                userID: row.userID,
                                userName: row.userName,
                                roleInfo: roleNames.join(constant.comma),
                                orgCount: orgIDList.length
                            }
                            userSource.push(object);
                        });

                        $scope.userDatagridDataSource = userSource;

                    }
                });
            };

            //所属行业弹框,也是通用模板
            var getCommonCard = function (dimensionValueID, dimensionValue, attributeName, attributeID) {
                var deferred = $q.defer();
                $scope.gridApi.treeBase.collapseAllRows();
                $scope.commonUIGridList.data = [];
                //参数,维度值的ID,如事业部1,事业部2 ,然后是顶层事业部,如事业部
                orgService.getOrgCustomDashbord(dimensionValueID, $scope.parentDimensionID, attributeID).success(function (data) {
                    if (data) {
                        //console.log(JSON.stringify(data));
                        data.orgDtoList.forEach(function (row) {
                            if (row.level != null) {
                                row.$$treeLevel = parseInt(row.level);
                            }
                        });

                        $scope.orgCustomList = data.orgCustomDtoList;
                        $scope.orgList = data.orgDtoList;

                        for (var i = 0; i < $scope.orgList.length; i++) {
                            var row = $scope.orgList[i];

                            //自定义显示属性
                            if ($scope.attributeList && $scope.attributeList.length > 0) {

                                for (var j = 0; j < $scope.attributeList.length; j++) {
                                    //只有是自定义的属性才构造新列
                                    if ($scope.attributeList[j].attributeType === constant.attributeType.SelfDimension) {
                                        var targetVaule = _.find($scope.orgCustomList, function (data) {
                                            return data.orgID === row.orgID && data.dimensionID === $scope.attributeList[j].belongDimensionID;
                                        });

                                        if (targetVaule) {
                                            row["selfDimension" + j] = targetVaule.dimensionValueName;
                                        } else {
                                            row["selfDimension" + j] = '';
                                        }
                                    }
                                }
                            }
                        };

                        $scope.dimensionValue = dimensionValue;
                        $scope.attributeName = attributeName;
                        $scope.commonUIGridList.data = $scope.orgList;
                        $scope.commonCountDataSource = data.orgCountList;
                        //console.log("Org: "+JSON.stringify($scope.orgList));
                        // console.log("cusomer:" + JSON.stringify(data.orgCustomDtoList));
                        //console.log("111:" + JSON.stringify($scope.attributeList));
                        //console.log("orgcountList:" + JSON.stringify(data.orgCountList));
                        deferred.resolve(data);
                    }
                });

                return deferred.promise;
            };

            //ng-repeat,根据字符串转换为json对象
            var getJson = function (obj) {
                if (obj) {
                    return JSON.parse(obj);
                }
            };

            var initOrgChartData = function () {
                PopulateChartDatasource();
            };

            // 添加或者编辑机构成功之后,刷新当前页面的数据
            $scope.$watch('isOrgUpdate', function (newValue, oldValue) {
                if (newValue) {
                    initOrgChartData();
                    notifyTopPage();
                }
            });

            // 添加或者编辑事业部成功之后,刷新当前页面的数据
            $scope.$watch('isBusinessUpdate', function (newValue, oldValue) {
                if (newValue) {
                    initOrgChartData();
                    notifyTopPage();
                }
            });

            // 添加或者编辑机构层级成功之后,刷新当前页面的数据
            $scope.$watch('isOrgStructureUpdate', function (newValue, oldValue) {
                if (newValue) {
                    initOrgChartData();
                    notifyTopPage();
                }
            });

            //自定义显示属性更新后,刷新当前页面的orgchart
            $scope.$watch('isAttributeUpdate', function (newValue, oldValue) {
                if (newValue) {
                    initOrgChartData();
                    populateUIGridColumns();
                }
            });

            //自定义维度值(添加)更新后,刷新当前页面的orgchart
            $scope.$watch('isDimensionValueUpdate', function (newValue, oldValue) {
                if (newValue) {
                    initOrgChartData();
                    notifyTopPage();
                }
            });

            //用户权限更新,刷新orgchart
            $scope.$watch('userBUIsUpdate', function (newValue, oldValue) {
                if (newValue) {
                    initOrgChartData();
                }
            });

            //添加现有机构
            $scope.$watch('addExistOrgIsUpdate', function (newValue, oldValue) {
                if (newValue) {
                    if ($scope.selectedExistOrgList && $scope.selectedExistOrgList.length > 0) {
                        // console.log(JSON.stringify($scope.selectedExistOrgList));
                        UpdateOrgToDimensionValue($scope.selectedExistOrgList).then(function (data) {
                            if (data) {
                                initOrgChartData();
                                notifyTopPage();
                            }
                        });
                    }
                }
            });

            //顶部的维度状态改变,更新orgchart
            $scope.$on('DimensionUpdate', function (event, data) {
                initOrgChartData();
                setParentDimension();
            })

            //通知父层去更新统计
            var notifyTopPage = function () {
                $scope.$emit("hasDimensionUpdated", { isupdated: true });
            };


            //添加现有机构到当前维度
            var UpdateOrgToDimensionValue = function (existOrgList) {
                var deferred = $q.defer();
                orgService.updateOrgToDimension($scope.addExistOrgDimensionValueID, $scope.parentDimensionID, existOrgList).success(function (data) {
                    if (data) {
                        deferred.resolve(data);
                    }
                });
                return deferred.promise;
            };

            // 新增机构
            $scope.editOrg = function (buID) {
                $scope.orgOperateType = constant.Operation.Add;
                $scope.selectedOrg = null;
                $scope.isOrgUpdate = false;
                $scope.organization = {
                    businessUnitID: buID
                };
            };
            //添加现有机构到当前的维度
            $scope.addExistOrg = function (demensionValueID, attributeID) {
                $scope.selectedKeyItems = [];

                getCommonCard(demensionValueID, '', '', attributeID).then(function (data) {

                    var selectedKeyItem = [];
                    $scope.commonUIGridList.data.forEach(function (row) {
                        selectedKeyItem.push(row.orgID);
                    });
                    $scope.selectedKeyItems = selectedKeyItem;
                    $scope.addExistOrgOperateType = constant.Operation.Add;
                    $scope.addExistOrgIsUpdate = false;
                    $scope.addExistOrgDimensionValueID = demensionValueID;
                });
            };

            //编辑事业部
            $scope.editBu = function (buID) {
                $scope.orgOperateBusinessType = constant.Operation.Edit;
                $scope.businessUnitID = buID;
                $scope.isBusinessUpdate = false;
            };

            //编辑机构层级
            $scope.editOrgStructureType = function (selectedId) {
                $scope.orgOperateOrgStructureType = constant.Operation.Edit;
                $scope.selectedOrgStructureID = selectedId;
                $scope.isOrgStructureUpdate = false;
            };

            //添加事业部,机构层级,自定义维度的值等等
            $scope.addDimensionValue = function () {
                if ($scope.parentDimensionType == constant.dimensionType.BusinessUnit) {
                    $scope.orgOperateBusinessType = constant.Operation.Add;
                    $scope.businessUnitID = null;
                    $scope.isBusinessUpdate = false;
                }
                if ($scope.parentDimensionType == constant.dimensionType.OrganizationStructure) {
                    $scope.orgOperateOrgStructureType = constant.Operation.Add;
                    $scope.selectedOrgStructureID = null;
                    $scope.isOrgStructureUpdate = false;
                }
                else if ($scope.parentDimensionType == constant.dimensionType.SelfDimension) {
                    $scope.dimensionValueOperateType = constant.Operation.Add;
                    $scope.dimensionID = $scope.parentDimensionID;
                    $scope.dimensionName = $scope.parentDimensionName;
                    $scope.isDimensionValueUpdate = false;
                    $scope.selectedDimensionValueID = null;
                }
            };

            //编辑自定义显示属性
            $scope.showCustomAttriute = function () {
                $scope.attributeOperateType = constant.Operation.Edit;
                $scope.showAttributeDimensionID = $scope.parentDimensionID;
                $scope.isAttributeUpdate = false;
            };
            //编辑自定义维度的值,功能如编辑事业部的,事业部1,事业部2 的值
            $scope.editCustomDimensionValue = function (dimensionValueID) {
                $scope.dimensionValueOperateType = constant.Operation.Edit;
                $scope.dimensionID = $scope.parentDimensionID;
                $scope.dimensionName = $scope.parentDimensionName;
                $scope.isDimensionValueUpdate = false;
                $scope.selectedDimensionValueID = dimensionValueID;
            };
            //点击机构名称,显示详细信息
            $scope.showOrgGenerateInfo = function (row) {
               // $scope.isRenderCompletedGeneralInfo = false;
                $scope.orgIdGeneralInfo = row.entity.orgID;

                var orgGeneralInfoPopup = $(orgGeneralInfoPopId);
                var rowId = $('#' + row.entity.orgID);
                showOrgCard(orgGeneralInfoPopup, rowId, 30, 50);
            };

            //用户权限设置,乘用车事业部
            $scope.userBUSetting = function () {
                $scope.userBUOperateType = constant.Operation.Edit;
                $scope.userBUIsUpdate = false;
                $scope.userBUDimensionID = $scope.parentDimensionID;
                $scope.userBUDimensionValueID; //dimensionValueID,如事业部1,事业部2,产品线1 等
            };


            //隐藏机构general info
            var hideOrgGeneralInfo = function () {
                $(orgGeneralInfoPopId).hide();
            };

            // 显示机构general info,并设置好位置
            var showOrgCard = function (popCard, row, topOffset, leftOffset) {

                popCard.css("display", "block");

                var top = row.offset().top + topOffset;
                if (top + popCard.height() > window.innerHeight) {
                    top = window.innerHeight - popCard.height() - topOffset;
                    //top = row.offset().top - topOffset - popCard.height();
                }

                popCard.css('top', top + 'px');

                var left = row.offset().left + leftOffset;
                if (left + popCard.width() > window.innerWidth) {
                    left = row.offset().left - popCard.width() - leftOffset;
                }

                popCard.css('left', left + 'px');

                popCard.show();

                $(document).one('click', function (e) {
                    hideOrgGeneralInfo();
                });
            };

            var InitDXDataGrid = function () {
                loadUserDatagrid();
            };


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

                $scope.userdatagridOptions = {
                    bindingOptions: {
                        dataSource: 'userDatagridDataSource'
                    },
                    selection: {
                        mode: "single"
                    },
                    columns: [
                        {
                            dataField: "userName",
                            caption: $translate.instant('UserDesc'),
                            width:"30%",
                            cellTemplate: function (container, options) {
                                try {
                                    $('<a>' + options.value + '</a>')
                                        .attr('href', '#/userDetail/' + options.row.data.userID)
                                        .appendTo(container);
                                }
                                catch (e) {
                                    $log.error(e);
                                }
                            }
                        },
                        {
                            dataField: "roleInfo",
                            caption: $translate.instant('Role'),
                            width: "50%",
                        },
                        {
                            dataField: "orgCount",
                            caption: $translate.instant('OrganizationCount'),
                            alignment: 'center',
                            width: "20%",

                        },
                    ],
                    loadPanel: {
                        enabled: false
                    },
                    scrolling: {
                        mode: "virtual"
                    },
                    allowColumnResizing: true,
                    noDataText: $translate.instant('NoDataText'),
                    showColumnLines: false,
                    showRowLines: false,
                    rowAlternationEnabled: true,
                    showBorders: false,
                    sorting: {
                        mode: "none"
                    }
                };
            };


            //根据自定义维度设置显示的卡片的列
            var populateUIGridColumns = function () {
                //获取维度值数据
                statisticAttributeService.getByParentDimensionID($scope.parentDimensionID).success(function (result) {
                    if (result) {

                        $scope.attributeList = result;
                        var column = {};
                        $scope.uigridColumns.splice(1);

                        var index = 0;
                        result.forEach(function (attr) {
                            if (attr.attributeType == constant.attributeType.BusinessUnit) {
                                column = {
                                    field: 'businessUnitName',
                                    name: attr.attributeName,
                                    headerCellClass: 'text-align-left',
                                    cellTemplate: '<div class="text-align-left-padding"><span title="{{row.entity.businessUnitName}}">{{row.entity.businessUnitName}}</span></div>'
                                };
                                $scope.uigridColumns.push(column);
                            }
                            else if (attr.attributeType == constant.attributeType.OrganizationStructure) {
                                column = {
                                    type: 'string',
                                    field: 'structureName',
                                    name: attr.attributeName,
                                    headerCellClass: 'text-align-left',
                                    cellTemplate: '<div class="text-align-left-padding"><span title="{{row.entity.structureName}}">{{row.entity.structureName}}</span></div>'
                                };
                                $scope.uigridColumns.push(column);
                            }
                            else if (attr.attributeType == constant.attributeType.Industry) {
                                column = {
                                    type: 'string',
                                    field: 'industryName',
                                    name: attr.attributeName,
                                    headerCellClass: 'text-align-left',
                                    cellTemplate: '<div class="text-align-left-padding"><span title="{{row.entity.industryName}}">{{row.entity.industryName}}</span></div>'
                                };
                                $scope.uigridColumns.push(column);
                            }
                            else if (attr.attributeType == constant.attributeType.Area) {
                                column = {
                                    type: 'string',
                                    field: 'areaName',
                                    name: attr.attributeName,
                                    headerCellClass: 'text-align-left',
                                    cellTemplate: '<div class="text-align-left-padding"><span title="{{row.entity.areaName}}">{{row.entity.areaName}}</span></div>'
                                };
                                $scope.uigridColumns.push(column);
                            }
                            else if (attr.attributeType == constant.attributeType.SelfDimension) {
                                var column = {
                                    field: 'selfDimension' + index,
                                    name: attr.attributeName,
                                    headerCellClass: 'text-align-left',
                                    cellTemplate: '<div class="text-align-left-padding"><span title="{{row.entity.selfDimension' + index + '}}">{{row.entity.selfDimension' + index + '}}</span></div>'
                                };

                                $scope.uigridColumns.push(column);
                            }

                            index++;
                        });
                    }
                });

            };
            var initUIGrid = function () {
                commonUIGridInit();
                populateUIGridColumns();
            };

            //设置维度的名称和值,和类型
            var setParentDimension = function () {
                var deferred = $q.defer();
                dimensionService.getDimensionById($scope.parentDimensionID).success(function (data) {
                    if (data) {
                        $scope.parentDimensionName = data.name;
                        $scope.parentDimensionType = data.dimensionType;
                        deferred.resolve(data);
                    }
                });
                return deferred.promise;
            }

            //通用的ui grid 模板
            var commonUIGridInit = function () {
                $scope.uigridColumns = [{
                    field: 'orgName',
                    name: $translate.instant('OrganizationName'),
                    //cellTemplate: '<div ng-mouseover="grid.appScope.showOrgGenerateInfo(row)" ng-class="{true: \'text-align-left\', false: \'text-align-left-padding\'}[row.entity.level==' + constant.level.First + ']">\
                    //<a title="{{row.entity.orgName}}" href="#/organization/{{row.entity.orgID}}" target="_blank" id="{{row.entity.orgID}}">{{row.entity.orgName|limitString:16}}</a>\
                    //</div>'
                    cellTemplate: '<div ng-class="{true: \'text-align-left\', false: \'text-align-left-padding\'}[row.entity.level==' + constant.level.First + ']"><span title="{{row.entity.orgName}}" id="{{row.entity.orgID}}" ng-click="grid.appScope.showOrgGenerateInfo(row)">{{row.entity.orgName==null||row.entity.orgName==""?"' + unassisgnText + '":row.entity.orgName}}</span></div>'
                }
                ];

                $scope.commonUIGridList = {
                    data:[],
                    enableRowSelection: true,
                    enableSelectAll: false,
                    rowHeight: 30,
                    enableRowHeaderSelection: false,
                    modifierKeysToMultiSelect: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    enableVerticalScrollbar: uiGridConstants.scrollbars.enableVerticalScrollbar,

                    enableColumnResizing: true,
                    enableSorting: true,
                    enableColumnMenus: false,
                    enableFiltering: false,
                    showTreeExpandNoChildren: false,
                    enableFullRowSelection: true, //是否点击行任意位置后选中,默认为false
                    multiSelect: false, // 是否可以选择多个,默认为true; 
                    columnDefs: $scope.uigridColumns,

                    onRegisterApi: function (gridApi) {

                        $scope.gridApi = gridApi;

                        //$scope.gridSelectCount = $scope.gridApi.selection.getSelectedRows().length;

                        // call resize every 500 ms for 5 s after modal finishes opening - usually only necessary on a bootstrap modal
                        $interval(function () {
                            $scope.gridApi.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);

                    }
                };

            };

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

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

                $scope.hasAttributeQueryPermission = false;

                $scope.hasAccessSettingQueryPermission = false;
                $scope.hasAccessSettingEditPermission = false;
           
                //查看机构的权限
                var tempOrg = constant.adminPermission.infrastructure.organizationManage;
                list.push(tempOrg.addCode);
                list.push(tempOrg.queryCode);
                list.push(tempOrg.editCode);

                //自定义显示属性的权限
                var tempAttr = constant.adminPermission.infrastructure.customAttribute;
                list.push(tempAttr.queryCode);

                //权限设置的权限
                var tempAcess = constant.adminPermission.infrastructure.accessSetting;
                list.push(tempAcess.queryCode);
                list.push(tempAcess.editCode);

                $scope.hasDimensionValueEditPermission = false;
                  //编辑自定义维度值的时候的权限
                if ($scope.parentDimensionType == constant.dimensionType.BusinessUnit) {
                    var tempDV = constant.adminPermission.basicData.businessUnit;
                    list.push(tempDV.editCode);
                }
                else {
                    //自定义维度的权限
                    var tempDV = constant.adminPermission.basicData.selfDimension;
                    list.push(tempDV.editCode);
                }

                $scope.$root.checkUserPermissionList(list).success(function (data) {
                    // console.log('data: ' + JSON.stringify(data));
                    $scope.hasAddPermission = data[tempOrg.addCode];
                    $scope.hasQueryPermission = data[tempOrg.queryCode];
                    $scope.hasEditPermission = data[tempOrg.editCode];

                    $scope.hasAttributeQueryPermission = data[tempAttr.queryCode];

                    $scope.hasAccessSettingQueryPermission = data[tempAcess.queryCode];
                    $scope.hasAccessSettingEditPermission = data[tempAcess.editCode];

                    $scope.hasDimensionValueEditPermission = data[tempDV.editCode];

                    if ($scope.hasQueryPermission) {
                        initOrgChartData();
                    }
                });
            };


            (function initialize() {
                $log.debug('organizationBusinessUnitViewController.ctor()...');
                $log.debug($state.params.dimensionID);
                var dimensionID = 'c61a5bd6-a996-4952-9869-d053995237e5'; //集团为事业部
                //  $scope.parentDimensionID = $state.params.dimensionID || 'c61a5bd6-a996-4952-9869-d053995237e8';
                var parentDimensionID = $state.params.dimensionID || dimensionID;
                $scope.parentDimensionID = parentDimensionID;
                $scope.showAttributeDimensionID = $scope.parentDimensionID;
                initUIGrid();
                InitDXDataGrid();
                //事业部和自定义维度的权限
                setParentDimension().then(function (data) {
                    checkUserPermission();
                });;

                $scope.getCommonCard = getCommonCard;
                $scope.getUserStatisCard = getUserStatisCard;

            })();
        }
    ]);
infrastructureModule.directive('organizationBusinessUnitView', ['$log', '$compile', '$timeout', '$interval',
   function ($log, $compile, $timeout, $interval) {
        'use strict';
        $log.debug('organizationBusinessUnitView.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/organizationBusinessUnitView/organization-business-unit-view.html' + '?_=' + Math.random(),
            scope: {},
            replace: true,
            controller: 'organizationBusinessUnitViewController',
            link: function (scope, element) {
               
                $(".card").draggable({ containment: "parent", cursor: "cursor", handle: ".card-header" });

                var showCardSeleted = '.show-card';
                // 机构缩略图ID
                var orgGeneralInfoPopId = '#orgGeneralInfoPop';

                //$(document).off('click');
                element.off('click');
                scope.renderOrgChart = function (datasource) {
                    $('.card').css('visibility', 'hidden');
                    $('#chart-container').html('');
                    //渲染orgchart
                    $('#chart-container').orgchart({
                        'data': datasource,
                        'pan': false,
                        'zoom': false,
                        "draggable": false,
                        'exportButton': false,
                        'nodeContent': 'title',
                        'exportFilename': 'SportsChart',
                        'parentNodeSymbol': 'fa-th-large'
                    });
                    //var chartWidth = $('#chart-container').width()
                    //var chartWidth = ($(window).width() - $(this).outerWidth()) / 2;
                    var horizontalCenter = Math.floor(window.innerWidth / 2);
                    console.log('horizontalCenter: ' + horizontalCenter);
                    $("#chart-container").scrollLeft(horizontalCenter);
                }


                //点击header,选中高亮
                element.on('click', '.title-header', function () {
                    $('.title-header').removeClass('title-header-active');
                    $(this).toggleClass("title-header-active");
                });

                var hideDropdownMenu = function () {
                    $('.title-header .dropdown-menu').css('display', 'none');
                };

                //点击高亮部分弹框,弹框去选择新增机构或者添加现有机构
                element.on('mouseenter', '.title-header .add-org', function () {
           
                    if (!scope.hasAddPermission) {
                        return false;
                    }
     
                    $('.title-header .dropdown-menu').css('display', 'none');

                    var thisCard = $(this).closest('.dropdown').find('.dropdown-menu');
                    thisCard.css('display', 'block');

                    element.one("click", function () {
                        thisCard.css('display', 'none');
                    });

                     stopPropagation();
                });

               element.on('mouseleave', '.title-header', function () {
                    $('.title-header .dropdown-menu').css('display', 'none');
                    stopPropagation();
               });
               element.on('click', showCardSeleted, function () {
                   $(orgGeneralInfoPopId).css('display', 'none');
                   stopPropagation();
               });

                //点击高亮部分新增机构
                element.on('click', '.title-header .add-new-org', function () {
                    stopPropagation();
                    hideCard();
                    //事业部ID
                    var demensionValueID = $(this).attr("data-demension-value-id"); //维度的值,如产品,事业部等
                    var attrbutetype = $(this).attr("data-attribute-type"); //自定义属性枚举值,如分公司,产品等
                    console.log("demensionValueID: " + demensionValueID);
                    //前提:高亮部分为分公司(机构)才触发这个事件
                    //if (attrbutetype == constant.dimensionType.OrgSubChildren) {
                    if (scope.parentDimensionType == constant.dimensionType.BusinessUnit) {
                        scope.editOrg(demensionValueID);
                    }
                    else {
                        scope.editOrg('');
                    }
                });


                //点击高亮部分添加现有机构
                element.on('click', '.title-header  .add-exist-org', function () {
                    stopPropagation();
                    hideCard();
                    //事业部ID
                    var demensionValueID = $(this).attr("data-demension-value-id"); //维度的值,如产品,事业部等
                    var attrbutetype = $(this).attr("data-attribute-type"); //自定义属性枚举值,如分公司,产品等
                    var attributeID = $(this).attr("data-attribute-id");
                    console.log("demensionValueID: " + demensionValueID);
                    //前提:高亮部分为分公司(机构)才触发这个事件
                   // if (attrbutetype == constant.dimensionType.OrgSubChildren) {
                    scope.addExistOrg(demensionValueID, attributeID);
                   // }
              
                });

                //如果维度是事业部,编辑事业部名称,如果是自定义维度,则编辑其定义维度的值
                element.on('click', '.edit-dimension-value', function () {
                    hideCard();
          
                    if (!scope.hasDimensionValueEditPermission) {
                        return false;
                    }
                    //事业部ID
                    var demensionValueID = $(this).attr("data-dimension-value-id");
                    if (demensionValueID) {
                        console.log("demensionValueID: " + demensionValueID);
                        if (scope.parentDimensionType == constant.dimensionType.BusinessUnit) {
                            scope.editBu(demensionValueID);
                        }
                            //如果是机构层级
                        else if (scope.parentDimensionType == constant.dimensionType.OrganizationStructure) {
                            scope.editOrgStructureType(demensionValueID);
                        }
                          //如果是自定义的维度
                        else if (scope.parentDimensionType == constant.dimensionType.SelfDimension) {
                            scope.editCustomDimensionValue(demensionValueID);
                        }
                    }
                    return false;
                  //  stopPropagation();
                });

                //点击不同的属性显示卡片
                element.on('click', showCardSeleted, function (e) {

                    stopPropagation();
                  
                    $(showCardSeleted).removeClass('row-highlight');
                    var $this = $(this);
                    $this.addClass('row-highlight');

                     //维度,如用户数,覆盖区域,所属行业等
                    var attributeType = $this.attr("data-attribute-type");
                    //维度值的ID,相当于某个事业部ID,
                    var dimensionValueID = $this.attr("data-demension-value-id");
                    var dimensionValue = $this.attr('data-demension-value');
                    var attributeName = $this.attr('data-attribute-name');
                    var attributeID = $this.attr("data-attribute-id");
                    //data-attribute-name
                    //如果是用户数
                    if (attributeType == constant.attributeType.User)
                    {
                        scope.getUserStatisCard(dimensionValueID, dimensionValue, attributeName, attributeID);
                        showCard('.user-card', $this.closest('.node'));
                    }  
                     //自定义维度,如产品线1,产品线2,通用,分公司,机构层级
                    else {
                        scope.getCommonCard(dimensionValueID, dimensionValue, attributeName, attributeID);
                        showCard('.common-card',$this.closest('.node'));
                    }

                    stopPropagation();
                });


                $(".card").on("click", function (e) {
                    stopPropagation();
                });
                $(".close-card").on("click", function (e) {
                    hideCard();
                    //$(this).closest('.card').css('visibility', 'hidden');
                });
                var hideCard = function () {
                    $(".card").css('visibility', 'hidden');
                    $(orgGeneralInfoPopId).hide();
                };

                var showCard = function (thisCard,node) {

                    hideCard();
                   var nodeOffset = $(node).offset();

                    // var nodeOuterWidth = $("#chart-container  .node").first().outerWidth();
                    var nodeOuterWidth = $(node).outerWidth();
                    var leftLen = nodeOffset.left + nodeOuterWidth + 10;
                    if (leftLen + $(thisCard).width() > window.innerWidth) {
                        leftLen = leftLen - nodeOuterWidth - $(thisCard).width() - 20;
                    }

                    $(thisCard).css("left", leftLen);
                    $(thisCard).css("top", nodeOffset.top);

                    if ($(thisCard + ":hidden")) {
                        $(thisCard).css('visibility', 'visible');

                    } else {
                        $(thisCard).css('visibility', 'hidden');
                    }
                };

                scope.fullScreenText = '全屏展示';
                scope.showFullScreen = function () {

                    $('.business-unit-view').parent().toggleClass('fullScreen');
                    if ($('.business-unit-view').parent().hasClass('fullScreen')) {
                        scope.fullScreenText = '退出全屏';
                        scope.isShowFullScreen = true;
                    } else {
                        scope.fullScreenText = '全屏展示';
                        scope.isShowFullScreen = false;
                    }
                }

                var stopPropagation = function (event) {
                    event = event || window.event;
                    if (event.stopPropagation) {
                        event.stopPropagation();
                    } else {
                        event.cancelBubble = true;
                    }
                }  
            }
        };
    }
]);


infrastructureModule
   .controller('OrganizationListViewController', ['$location', '$scope', '$log', 'SweetAlert', '$translate', 'areaRegionService', 'uiGridTreeViewConstants', '$timeout', 'dimensionService', '$interval', 'orgService', '$q','loginContext',
        function ($location, $scope, $log, SweetAlert, $translate, areaRegionService, uiGridTreeViewConstants, $timeout, dimensionService, $interval, orgService, $q, loginContext) {

            $scope.expanded = true;
            var translate={
                Enabled:$translate.instant('BusinessUnitActive'),  //已启用
                Disabled: $translate.instant('BusinessUnitDisabled'),//已停用
            };
            $scope.showOperateLogPop = function () {
                $scope.isShowLog = true;
                // $('#showOperatePop').modal('show');
            };

            //添加过滤下拉列表
            var InitFilterList = function () {
                //初始化选择器为空
                $scope.filter = {};
                $scope.filter.selected = [];

                var datasource = constant.taxpayerNumberFilter.dataSource;

                datasource.forEach(function (row) {
                    row.value = $translate.instant(row.value);
                });
                $scope.taxPayerFilterList = datasource;
            };


            //筛选的时候,ng-check event will be triggered
            $scope.stateChanged = function ($event, data) {
                $scope.filter.selected = [];
                var checkbox = $event.target;
                if (checkbox.checked && $scope.filter.selected.indexOf(data.key) < 0) {
                    $scope.filter.selected.push(data.key);
                }

                taxPayerFilterChanged();
            };

            var taxPayerFilterChanged = function () {
                var selectedList = $scope.filter.selected;
                if (selectedList.length == 0) return;
                
                var selectedID = $scope.filter.selected[0] || constant.taxpayerNumberFilter.key_0;
                var oldData = angular.copy($scope.oldData);
                switch (selectedID) {
                    //所有对应状态,取默认值
                    case constant.taxpayerNumberFilter.key_0:  //all data
                        $scope.DataGridSource = oldData;
                        break;
                        //have taxpayerNumber
                    case constant.taxpayerNumberFilter.key_1:
                        var findResult = _.filter(oldData, function (item) {
                            return item.taxPayerNumber !== null && item.taxPayerNumber != '';
                        });
                        $scope.DataGridSource = findResult;
                        break;
                        //Don't have taxpayerNumber
                    case constant.espAccountFilter.key_2:
                        var findResult = _.filter(oldData, function (item) {
                            return item.taxPayerNumber == null || item.taxPayerNumber == '';
                        });
                        $scope.DataGridSource = findResult;
                        break;
                }

                $scope.orgTreeListInstance.refresh();
            };


            $scope.createOrg = function ()
            {
                $scope.orgOperateType = constant.Operation.Add;
                $scope.selectedOrg = null;
                $scope.isOrgUpdate = false;
            };

            // 添加或者编辑机构成功之后,刷新当前页面的数据
            $scope.$watch('isOrgUpdate', function (newValue, oldValue) {
                if (newValue) {
                    getOrgList();
                }
            });

            var getOrgList = function () {
                orgService.getOrgListLevel().success(function (data) {
                    if (data) {
                        //data.forEach(function (row) {
                        //    if (row.userList) {
                        //        row.userListStr = _.map(row.userList, function (x) { return x.userName; }).join(constant.comma);
                        //    }
                        //});
                        //console.log("dat:" + JSON.stringify(data));
                        if (loginContext.userName && loginContext.userName.toLowerCase() === "simon") {
                            data = _.filter(data, function (row) {
                                return row && row.industryID === "10";
                            });
                        }
                        $scope.DataGridSource = data;
                        $scope.oldData = angular.copy(data);
                        $scope.setGridHeight();
                    }
                });
            };

            
            $scope.collapseAll = function () {
                var treeList = $scope.orgTreeListInstance;
                treeList.beginUpdate();
                $scope.DataGridSource.forEach(function (item) {

                    treeList.collapseRow(item.id);
                });
          
                treeList.endUpdate();
                $scope.expanded = false;
            }

            $scope.expandAll = function () {
                var treeList = $scope.orgTreeListInstance;
                treeList.beginUpdate();
                $scope.DataGridSource.forEach(function (item) {

                    treeList.expandRow(item.id);
                });

                treeList.endUpdate();
                $scope.expanded = true;
            }

            var loadDatagrid = function () {

                $scope.orgUserTreeOptions = {
                    bindingOptions: {
                        dataSource: 'DataGridSource'
                    },
                    columns: [
                            {
                                dataField: "name",
                                caption: $translate.instant('OrganizationName'),
                                allowHeaderFiltering:false,
                                cellTemplate: function (container, options) {
                                    try {
                                        $('<a class="hyper-link">' + options.value + '</a>')
                                            .attr('href', '#/organization/' + options.row.data.id)
                                            .appendTo(container);
                                    }
                                    catch (e) {
                                        $log.error(e);
                                    }
                                }
                            },
                            {
                                dataField: "code",
                                allowHeaderFiltering: false,
                                caption: $translate.instant('OrganizationCode')
                            },
                            {
                                dataField: "taxPayerNumber",
                                allowHeaderFiltering: true,
                                caption: $translate.instant('TaxPayerNumber'),
                                //headerFilter: {
                                //    dataSource: {
                                //        load: function () {
                                //            return [{
                                //                text: hasTaxpayNumer,
                                //                 value: [['taxPayerNumber', '<>', null],'and', ['taxPayerNumber', '<>', '']]
                                //            }, {
                                //                text: noTaxpayNumer,
                                //                value: [['taxPayerNumber', '=', null], 'or', ['taxPayerNumber', '=', '']]
                                //            }];
                                //        }
                                //    }
                                //},

                            },
                            {
                                dataField: "structureName",
                                caption: $translate.instant('OrganizationStructureDesc')
                            },
                            {
                                dataField: "regionName",
                                caption: $translate.instant('AreaRegionTitle'),
                                allowHeaderFiltering: false,
                            },
                             {
                                 dataField: "businessUnitName",
                                 caption: $scope.businessName,
                                 allowHeaderFiltering: false,
                             },
                            {
                                dataField: "areaName",
                                caption: $scope.areaName,
                                allowHeaderFiltering: false,
                            },
                            {
                                dataField: "industryName",
                                caption: $translate.instant('PIndustry'),
                                allowHeaderFiltering: false,
                            },
                            {
                                dataField: "isActive",
                                caption: $translate.instant('EnableStatus'),
                                allowHeaderFiltering: false,
                                cellTemplate: function (container, options) {
                                    try {
                                        if (options.data.isActive) {
                                            $('<span>').text(translate.Enabled).appendTo(container);
                                        }
                                        else {
                                            $('<span style="color:gray">').text(translate.Disabled).appendTo(container);
                                        }
                                    }
                                    catch (e) {
                                        $log.error(e);
                                    }
                                }
                            }
                    ],
                    onContentReady: function (e) {
                        $scope.orgTreeListInstance = e.component;
                        var totalCount =e.component.totalCount();
                        if(totalCount>0)
                        {
                            $scope.totalCount=totalCount;
                        }
                    },
                    loadPanel: {
                        enabled: false
                    },
                    scrolling: {
                        mode: "virtual"
                    },
                    keyExpr: "id",
                    parentIdExpr: "parentID",
                    selection: {
                        mode: "single"
                    },
                    autoExpandAll:true,
                    allowColumnResizing: true,
                    columnAutoWidth: true,
                    showRowLines: true,
                    showColumnLines: true,
                    rowAlternationEnabled: true,  //单双行颜色
                    noDataText: $translate.instant('NoDataText'),
                    showBorders: true,
                    selectAllText: $translate.instant('SelectAll'),
                    searchPanel: {
                        placeholder: $translate.instant('Search'),
                        width: 518,
                        visible: true
                    },
                    headerFilter: {
                        visible: false,
                        texts: {
                            cancel: $translate.instant('Cancel'),
                            ok: $translate.instant('Confirm'),
                            emptyValue: $translate.instant('Empty'),
                            selectAllText: $translate.instant('SelectAll'),
                        }
                    },

                    //columnHidingEnabled: true, //自定义显示列
                    //columnChooser: {
                    //    enabled: true,
                    //    mode: "select"
                    //},
                };

            };

            var getDimensionList = function () {
                dimensionService.getDimensionList().success(function (data) {
                    if (data) {
                        $scope.customDimensionList = data;

                        $log.debug($scope.customDimensionList);

                        $scope.businessName = dimension.getBusinessUnitName();
                        $scope.areaName = dimension.getAreaName();
                        
                        loadDatagrid();
                    }
                });
            };

            var dimension = {
                getBusinessUnitName: function () {
                    var findResult = _.find($scope.customDimensionList, function (item) {
                        return item.id == constant.dimensionID.businessUnitID;
                    });
                    if (findResult) {
                        return findResult.name;
                    }
                    else {
                        return '';
                    }
                },
                getAreaName: function () {
                    var findResult = _.find($scope.customDimensionList, function (item) {
                        return item.id == constant.dimensionID.areaID;
                    });
                    if (findResult) {
                        return findResult.name;
                    }
                    else {
                        return '';
                    }
                }
            };

            var initData = function () {
                InitFilterList();
                getDimensionList();
                getOrgList();
            };

            var checkUserPermission = function () {

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

                var temp = constant.adminPermission.infrastructure.organizationManage;
                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.hasAddPermission = data[temp.addCode];
                    $scope.hasEditPermission = data[temp.editCode];
                    if ($scope.hasQueryPermission) {
                        initData();
                    }
                });
            };


            (function initialize() {
                $log.debug('OrganizationListViewController.ctor()...');
      
                checkUserPermission();
            })();
        }
   ]);
infrastructureModule.directive('organizationListView', ['$log', '$compile', '$timeout', '$interval',
    function ($log, $compile, $timeout, $interval) {
        'use strict';
        $log.debug('organizationListView.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/organizationListView/organization-list-view.html' + '?_=' + Math.random(),
            scope: {},
            replace: true,
            controller: 'OrganizationListViewController',
            link: function (scope, element) {

                scope.setGridHeight = function () {
                    var pageWrapSelector = ".organization-list-view";
                    var menuSelector = ".menu-header";
                    var contentHeader = '.content-container .header';
                    var dxGridSelctor = "#orgGridContainer";

                    var contentHeaderHeight = parseInt($(contentHeader).css('height').replace('px', ''));
                    var pageHeight = parseInt($(pageWrapSelector).css('height').replace('px', ''));
                    var menuHeight = parseInt($(menuSelector).css('height').replace('px', ''));
                    var height = pageHeight - menuHeight - contentHeaderHeight - 40 + 'px';

                    $(dxGridSelctor).css('max-height', height);
                };


                $(window).resize(function () {
                    scope.setGridHeight();
                });


                var filterSelector = '.filter-select';

                $(filterSelector).on("click", function (e) {
                    e.stopPropagation();
                });

                scope.showFilter = function () {
                    if ($(filterSelector).is(":hidden")) {
                        $(filterSelector).show();
                    } else {
                        $(filterSelector).hide();
                    }

                    $(document).one("click", function () {
                        $(filterSelector).hide();
                    });
                    event.stopPropagation();
                };


            }//# end of link
        }
    }
]);
infrastructureModule
    .controller('OrganizationManageController', ['$scope', '$log', 'orgService', '$interval', 'uiGridTreeViewConstants', 'uiGridConstants', 'SweetAlert', 'projectService', '$translate', '$timeout', 'organizationStructureService', 'areaRegionService', 'apiInterceptor', 'enterpriseAccountService', 'businessUnitService', 'userService', 'roleService', '$q', 'permissionService', 'dimensionService','region',
        function ($scope, $log, orgService, $interval, uiGridTreeViewConstants, uiGridConstants, SweetAlert, projectService, $translate, $timeout, organizationStructureService, areaRegionService, apiInterceptor, enterpriseAccountService, businessUnitService, userService, roleService, $q, permissionService, dimensionService, region) {
            'use strict';


            var showWarning = function (resultMsg) {

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

            var showSuccessMsg = function (resultMsg) {

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

            //jack
            $scope.getBottomHeight = function () {

                if ($scope.isLoadComplete) {
                    var y = $(".company-detail").height();
                    var parent = $('.org-right-container').height();
                    return { height: parent - y + 'px' };
                }

                return {};
            };

            var getDimensionList = function () {
                dimensionService.getDimensionList().success(function (data) {
                    if (data) {
                        $scope.customDimensionList = data;

                        $log.debug($scope.customDimensionList);

                        $scope.businessName = dimension.getBusinessUnitName();
                        $scope.areaName = dimension.getAreaName();
                    }
                });
            };

            var dimension = {
                getBusinessUnitName: function () {
                    var findResult = _.find($scope.customDimensionList, function (item) {
                        return item.id == constant.dimensionID.businessUnitID;
                    });
                    if (findResult) {
                        return findResult.name;
                    }
                    else {
                        return '';
                    }
                },
                getAreaName: function () {
                    var findResult = _.find($scope.customDimensionList, function (item) {
                        return item.id == constant.dimensionID.areaID;
                    });
                    if (findResult) {
                        return findResult.name;
                    }
                    else {
                        return '';
                    }
                }
            };

            ////添加企业账套
            //$scope.newAccountSetModal = function ()
            //{
            //    $scope.accountSetOperateType = constant.Operation.Add;
            //    $scope.accountSetIsUpdate = false;

            //};

            // 机构树
            var tree;

            // 是佛启用禁用Map
            var isActiveMap = {
                false: 'Enable',
                true: 'Disable'
            };

            // 获取账套
            var loadEnterpriseAccountSetList = function () {
                enterpriseAccountService.getEnterpriseAccountSetList().success(function (data) {
                    // 只获取启用状态的账套
                    //data = _.filter(data, function (num) { return num.isActive });
                    $scope.enterpriseAccountSetList = sortByEnterpriseName(data);
                    if (data && data.length > 0) {
                        $scope.hasEnterpriseAccountSet = true;

                    } else {
                        $scope.hasEnterpriseAccountSet = false;
                    }
                });
            };

            var dataType = {
                isPrefixNumber: function (value) {
                    var reg = /^\d+/;
                    if (reg.test(value)) {
                        return true;
                    } else {
                        return false;
                    }
                },
                isPrefixChar: function (value) {
                    var reg = /^[a-zA-Z]+/;
                    if (reg.test(value)) {
                        return true;
                    } else {
                        return false;
                    }
                },
                isPrefixNumberOrChar: function (value) {
                    if (dataType.isPrefixNumber(value)) {
                        return true;
                    }

                    if (dataType.isPrefixChar(value)) {
                        return true;
                    }

                    return false;
                }
            };

            var sortByEnterpriseName = function (data) {
                if (data && data.length > 0) {

                    var charList = [];
                    var nocharList = [];

                    data.forEach(function (row) {
                        if (dataType.isPrefixNumberOrChar(row.name)) {

                            row.nameSort = row.name;

                            if (row.nameSort) {
                                row.nameSort = row.nameSort.toLowerCase();
                            }
                            charList.push(row);
                        } else {
                            nocharList.push(row);
                        }

                    });

                    charList = _.sortBy(charList, 'nameSort');

                    nocharList = nocharList.sort(function compareFunction(param1, param2) {
                        return param1.name.localeCompare(param2.name, 'zh');
                    });

                    var all = _.union(charList, nocharList);
                    return all;
                }

                return data;
            };

            // 初始化函数
            var initOrg = function () {
                getDimensionList();
                loadorgTree();
                loadEnterpriseAccountSetList();
                getServiceList();
            };

            // 保存启用、启用的操作结果
            $scope.updateIsActive = function () {
                $scope.isCanOrganizationIsActiveBtn = false;
                var isActive = !$scope.selectCompany.isActive;
                if (isActive) {
                    orgService.enableOrgs($scope.selectCompany.id).success(function () {
                        SweetAlert.success($translate.instant('EnableUserSuccess'));

                        $scope.selectCompany.isActive = !$scope.selectCompany.isActive;
                        $scope.selectCompany.isActiveStr = $translate.instant(isActiveMap[$scope.selectCompany.isActive]);
                        $log.debug('enabled success!');
                        $scope.organizationId = $scope.selectCompany.id;
                        loadorgTree();
                    })['finally'](function () {
                        $scope.isCanOrganizationIsActiveBtn = true;

                    });
                } else {
                    var list = [];
                    list.push($scope.selectCompany.id);
                    orgService.disableOrgs(list).success(function () {
                        SweetAlert.success($translate.instant('DisableUserSuccess'));

                        $scope.selectCompany.isActive = !$scope.selectCompany.isActive;
                        $scope.selectCompany.isActiveStr = $translate.instant(isActiveMap[$scope.selectCompany.isActive]);
                        $log.debug('disabled orgs success!');
                        $scope.organizationId = $scope.selectCompany.id;
                        loadorgTree();
                    })['finally'](function () {
                        $scope.isCanOrganizationIsActiveBtn = true;
                    });
                }

            };

            // 进入高级配置编辑状态
            $scope.editAdvancedConfigurationStatus = function () {
                $scope.selectCompany.isUpdate = true;
                setEnterpriseOrgRowList($scope.selectCompany);

                if ($scope.selectCompany.organizationServiceTemplateGroupList && $scope.selectCompany.organizationServiceTemplateGroupList.length > 0) {

                    $scope.selectCompany.organizationServiceTemplateGroupList.forEach(function (row) {

                        row.templateGroupList = _.find($scope.serviceList, function (num) {
                            return num.id === row.serviceTypeID
                        }).templateGroupList;
                    });
                }

            };

            // 添加服务模板
            $scope.addOrganizationServiceTemplateGroupRow = function () {
                var row = {};

                $scope.selectCompany.isUpdate = true;
                $scope.selectCompany.organizationServiceTemplateGroupList.push(row);
            };

            // 验证账套
            $scope.checkEnterpriseAccountSetSelect = function (row) {
                if (!row.enterpriseAccountSetID && !row.effectiveDateStr && !row.expiredDateStr) {
                    row.enterpriseAccountSetSelectError = null;
                    return;
                }


                if (!row.enterpriseAccountSetID) {
                    row.enterpriseAccountSetSelectError = $scope.resources.OrganizationMsgEnterpriseAccountSetRequired;
                } else {
                    row.enterpriseAccountSetSelectError = null;
                }
            };

            // 删除企业账套
            $scope.deleteAccountSet = function (row) {
                var index = jQuery.inArray(row, $scope.selectCompany.enterpriseAccountSetOrgList);
                $scope.selectCompany.enterpriseAccountSetOrgList.splice(index, 1);
            };

            // 删除服务
            $scope.deleteService = function (row) {
                var index = jQuery.inArray(row, $scope.selectCompany.organizationServiceTemplateGroupList);
                $scope.selectCompany.organizationServiceTemplateGroupList.splice(index, 1);
            };

            // 保存高级配置修改
            $scope.saveAdvancedConfiguration = function () {

                if (checkEnterpriseSetOrg() || checkTemplateList() || checkServiceTypeList()) {
                    return;
                }

                var branch = {
                    data: {
                        id: $scope.selectCompany.id
                    }
                };

                orgService.updateOrg($scope.selectCompany).success(function (data) {
                    if (data && !data.result) {
                        SweetAlert.warning($translate.instant(data.resultMsg));
                        return;
                    }

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

                    $scope.selectOrganization(branch);
                });
            };

            // 取消高级配置修改
            $scope.cancelAdvancedConfiguration = function () {
                $scope.selectCompany.enterpriseAccountSetOrgList = angular.copy($scope.backups.enterpriseAccountSetOrgList);
                $scope.selectCompany.organizationServiceTemplateGroupList = angular.copy($scope.backups.organizationServiceTemplateGroupList);
                $scope.selectCompany.isUpdate = false;
            };

            // 关于日志部分
            $scope.showOperateLogPop = function () {
                $scope.isShowLog = true;
            };

            // 添加机构
            $scope.addOrg = function () {
                $scope.orgOperateType = constant.Operation.Add;
                $scope.isAdd = true;
                $scope.selectedOrg = null;
            };

            // 添加机构
            $scope.updateOrg = function () {
                $scope.isAdd = false;
                $scope.orgOperateType = constant.Operation.Edit;
                $scope.selectedOrg = $scope.selectCompany;
            };

            // 添加或者编辑机构成功之后,刷新当前页面的数据
            $scope.$watch('isOrgUpdate', function (newValue, oldValue) {
                if (newValue) {
                    if ($scope.selectCompany && !$scope.isAdd) {
                        $scope.organizationId = $scope.selectCompany.id;
                    } else {
                        $scope.organizationId = null;
                    }

                    initOrg();
                    $scope.isOrgUpdate = false;
                }
            });

            // 选中服务更改时
            $scope.serviceTypeChange = function (service) {
                if ($scope.selectCompany.organizationServiceTemplateGroupList && $scope.selectCompany.organizationServiceTemplateGroupList.length > 0) {
                    var sameServiceTypeIDList = _.filter($scope.selectCompany.organizationServiceTemplateGroupList, function (num) {
                        return num.serviceTypeID === service.serviceTypeID;
                    });

                    if (sameServiceTypeIDList && sameServiceTypeIDList.length > 1) {
                        service.serviceTypeError = $scope.resources.ServiceExists;
                    } else {
                        service.serviceTypeError = null;
                    }
                } else {
                    service.serviceTypeError = null;
                }

                service.templateGroupList = _.find($scope.serviceList, function (num) {
                    return num.id === service.serviceTypeID
                }).templateGroupList;

                service.templateGroupID = '';
            };

            // 判断服务的选择是否有错误
            var checkServiceTypeList = function () {
                var hasError = false;
                if ($scope.selectCompany.organizationServiceTemplateGroupList && $scope.selectCompany.organizationServiceTemplateGroupList.length > 0) {

                    var serviceTypeIDList = [];

                    $scope.selectCompany.organizationServiceTemplateGroupList.forEach(function (row) {
                        if (serviceTypeIDList.indexOf(row.serviceTypeID) > -1) {
                            row.serviceTypeError = $scope.resources.ServiceExists;
                            hasError = true;
                        } else {
                            row.serviceTypeError = null;
                        }

                        if (!row.templateGroupID) {
                            hasError = true;
                            row.selectedTemplateError = $scope.resources.OrganizationMsgTemplateRequired;
                        } else {
                            row.selectedTemplateError = null;
                        }

                        serviceTypeIDList.push(row.serviceTypeID);
                    });

                    // 有错误
                    return hasError;
                }

                // 没有错误
                return hasError;
            };

            var loadRootOrg = function () {
                orgService.getSingleOrg(constant.guid.empty).success(function (rootOrg) {
                    $scope.rootOrg = rootOrg;
                });
            };
            //加载用户权限list
            var loadUserRoleList = function (orgID) {
                roleService.getUserRoleList(orgID, '', '').success(function (data) {
                    // 构造用户信息
                    var roleStaticsList = [];

                    var userRoleShowList = [];
                    if (data && data.length > 0) {
                        data.forEach(function (row) {

                            var uniqRoleList = _.uniq(row.roleInfoList, function (item) { return item.name });
                            row.roleNameList = _.map(uniqRoleList, function (x) { return x.name; }).join(constant.comma);

                            //var roleNames = _.pluck(row.roleInfoList, 'name');
                            //row.roleNameList = roleNames.join(',');

                            if (!row.isAccessible) {
                                row.roleNameList = $translate.instant('UnAccessable');
                            }

                            row.hasEditPermission = $scope.hasEditPermission;

                            userRoleShowList.push({ id: row.id, userName: row.userName, roleNameList: row.roleNameList });
                            row.roleInfoList.forEach(function (role) {
                                var one = _.find(roleStaticsList, function (data) {
                                    return data.id === role.id;
                                });

                                if (one) {
                                    one.count++;
                                } else {
                                    role.count = 1;
                                    roleStaticsList.push(role);
                                }
                            });
                        });
                    }

                    $scope.roleStaticsList = roleStaticsList;

                    $scope.userRoleList = JSON.stringify(userRoleShowList);
                    $scope.userRoleGridOptions.data = data;
                    //用户数统计
                    $scope.userCount = data.length || 0;
                });
            };

            // 选中机构
            $scope.selectOrganization = function (branch) {

                var org = branch.data;
                $scope.output = "You selected: " + org.id;

                var suborgList = getSubOrgList(branch);
                $scope.selectedOrgID = org.id;

                // 选中事件
                // $scope.selectCompany = org;
                orgService.getSingleOrg(org.id).success(function (data) {
                    $scope.selectCompany = data;
                    $scope.selectCompany.isActiveStr = $translate.instant(isActiveMap[$scope.selectCompany.isActive]);
                    //$log.debug("org.regionID: " + org.regionID);
                    $scope.selectCompany.suborgList = suborgList;
                    $scope.backups = {};
                    $scope.backups.enterpriseAccountSetOrgList = angular.copy($scope.selectCompany.enterpriseAccountSetOrgList);
                    $scope.backups.organizationServiceTemplateGroupList = angular.copy($scope.selectCompany.organizationServiceTemplateGroupList);

                    var orgAttributeList = _.filter(data.dimensionValueOrgList, function (attr) {
                        if (attr.id) {
                            return true;
                        } else {
                            return false;
                        }
                    });

                    var orgAttributeRowList = [];

                    if (orgAttributeList && orgAttributeList.length > 0) {

                        $scope.firstAttribute = orgAttributeList[0];

                        for (var i = 1; i < orgAttributeList.length; i = i + 2) {
                            var model = {
                                left: orgAttributeList[i],

                            };
                            if (i + 1 < orgAttributeList.length) {
                                model.right = orgAttributeList[i + 1];
                            }

                            orgAttributeRowList.push(model);
                        }
                    }

                    $scope.selectCompany.orgAttributeRowList = orgAttributeRowList;

                    //加载用户权限list
                    loadUserRoleList(org.id);

                });
            };

            $scope.resources = {
                EffectiveDateRequired: $translate.instant('EffectiveDateRequired'),
                ExpiredDateRequired: $translate.instant('ExpiredDateRequired'),
                EffectiveDateAreaProblem: $translate.instant('EffectiveDateAreaProblem'),
                OrganizationMsgTemplateRequired: $translate.instant('OrganizationMsgTemplateRequired'),
                OrganizationMsgProjectIndustryRequired: $translate.instant('OrganizationMsgProjectIndustryRequired'),
                ServiceExists: $translate.instant('ServiceExists'),
                DateMonthFormatError: $translate.instant('DateMonthFormatError')
            };

            // 验证开始时间
            $scope.checkStartDate = function (row) {


                // if (!row.effectiveDateStr) {
                //     row.startDateError = $scope.resources.EffectiveDateRequired;
                // } else {
                //     row.startDateError = null;
                // }

                if (row.effectiveDateStr && !window.PWC.checkMonth(row.effectiveDateStr)) {
                    row.startDateError = $scope.resources.DateMonthFormatError;
                    return;
                } else {
                    row.startDateError = null;
                }

                if (!row.enterpriseAccountSetID && !row.effectiveDateStr && !row.expiredDateStr) {
                    row.startDateError = null;
                    return;
                }

                if (row.effectiveDateStr && row.expiredDateStr) {

                    if (!validateDate(row.effectiveDateStr, row.expiredDateStr)) {
                        row.startDateError = $scope.resources.EffectiveDateAreaProblem;
                    } else {
                        row.startDateError = null;
                    }
                }
            };

            // 验证结束时间
            $scope.checkEndDate = function (row) {

                //结束时间可为空,默认9999-12
                // if (!row.expiredDateStr) {
                //     row.endDateError = $scope.resources.ExpiredDateRequired;
                // } else {
                //     row.endDateError = null;
                // }

                if (row.expiredDateStr && !window.PWC.checkMonth(row.expiredDateStr)) {
                    row.endDateError = $scope.resources.DateMonthFormatError;
                    return;
                } else {
                    row.endDateError = null;
                }

                if (!row.enterpriseAccountSetID && !row.effectiveDateStr && !row.expiredDateStr) {
                    row.endDateError = null;
                    return;
                }

                if (row.effectiveDateStr && row.expiredDateStr) {
                    if (!validateDate(row.effectiveDateStr, row.expiredDateStr)) {
                        row.startDateError = $scope.resources.EffectiveDateAreaProblem;
                    } else {
                        row.startDateError = null;
                    }
                }
            };

            // 加载机构树
            $scope.my_tree = tree = {};

            var loadorgTree = function () {

                $scope.orgList = [];
                $scope.doing_async = true;

                $scope.showOrgTree = false;

                orgService.getOrgListToJson(1).success(function (data) {
                    $scope.orgList = data;
                    $log.debug(data);
                    // 设置默认选中机构
                    if (data && data.length > 0) {

                        var selectOrg = data[0];
                        if ($scope.organizationId) {
                            selectOrg = findBranch($scope.organizationId, $scope.orgList);
                            if (!selectOrg) {
                                selectOrg = data[0];
                            }
                        }

                        $scope.selectOrganization(selectOrg);
                    }

                    $scope.doing_async = false;

                    return $timeout(function () {
                        $scope.my_tree.expand_level_function();
                        $scope.my_tree.select_branch(selectOrg);
                        $scope.showOrgTree = true;
                    }, 200);

                    return tree.expand_level_function();

                }).error(function (data) {

                    $log.debug(JSON.stringify(data));
                });
            };

            // 查找选中的分支
            var findBranch = function (orgid, orgTree) {
                if (orgTree && orgTree.length > 0) {

                    for (var i = 0; i < orgTree.length; i++) {
                        var row = orgTree[i];

                        // 查看当前节点
                        if (row.data.id === orgid) {
                            target = row;
                            return target;
                        }

                        // 查看子节点
                        var target = findBranch(orgid, row.children);
                        if (target) {
                            return target;
                        }
                    }

                    return null;
                } else {
                    return null;
                }
            };

            // Copy Array
            var copyArray = function (data) {
                var ret = [];
                data.forEach(function (row) {

                    ret.push(row);
                });

                return ret;
            };

            // 修改机构时,设置账套设置的值
            var setEnterpriseOrgRowList = function (enterpriseAccountSetData) {
                $scope.orgAccountList = [];
                if (!enterpriseAccountSetData.enterpriseAccountSetOrgList || enterpriseAccountSetData.enterpriseAccountSetOrgList.length === 0) {
                    return;
                }
                var enterpriseAccountSetList = copyArray($scope.enterpriseAccountSetList);

                var index = 1;
                $scope.OrgAccountRowIndex = index;
                enterpriseAccountSetData.enterpriseAccountSetOrgList.forEach(function (row) {

                    row.fromID = 'advancedSetFrom' + index;
                    row.toID = 'advancedSetTo' + index;

                    index++;
                    $scope.OrgAccountRowIndex = index;

                    $timeout(function () {
                        setDatepickerRow(row);
                    }, 100);
                });

            };

            var setDatepickerRow = function (rowData) {
                $("#" + rowData.fromID).datepicker({
                    minViewMode: 1,
                    autoclose: true,
                    language: region,
                    format: "yyyy-mm"
                });

                $("#" + rowData.toID).datepicker({
                    minViewMode: 1,
                    autoclose: true,
                    language: region,
                    format: "yyyy-mm"
                });

                $("#" + rowData.fromID).on('changeDate', function () {
                    var fromValue = $("#" + rowData.fromID).val();
                    var toValue = $("#" + rowData.toID).val();
                    if (fromValue) {
                        // 如果结束值为空,或者有效时间是一个时间段,则设置结束时间的开始时间
                        if (!toValue || validateDate(fromValue, toValue)) {
                            $("#" + rowData.toID).datepicker('setStartDate', fromValue);
                        }
                    }
                });

                // 默认的错误信息先设置为空
                rowData.startDateError = null;
                rowData.endDateError = null;
            };

            // 获取所有服务列表
            var getServiceList = function () {
                projectService.getServiceList().success(function (serviceListData) {
                    $scope.serviceList = serviceListData;
                });
            };

            // 验证是否为时间段
            var validateDate = function (from, to) {
                var fromDate = new Date(from + '-01');
                var toDate = new Date(to + '-01');
                toDate.setMonth(toDate.getMonth() + 1);
                toDate.setDate(toDate.getDate() - 1);

                if (fromDate <= toDate) {
                    return true;
                } else {
                    return false;
                }
            };

            // 验证账套修改
            var checkEnterpriseSetOrg = function () {

                var enterpriseSetList = [];
                if ($scope.selectCompany.enterpriseAccountSetOrgList && $scope.selectCompany.enterpriseAccountSetOrgList.length > 0) {
                    $scope.selectCompany.enterpriseAccountSetOrgList.forEach(function (row) {

                        $scope.checkEnterpriseAccountSetSelect(row);
                        $scope.checkStartDate(row);
                        $scope.checkEndDate(row);

                        if (row.enterpriseAccountSetID) {
                            enterpriseSetList.push(row);
                        }
                    });
                }

                $scope.selectCompany.enterpriseAccountSetOrgList = enterpriseSetList;

                var errorList = _.filter($scope.selectCompany.enterpriseAccountSetOrgList, function (num) {

                    return num.enterpriseAccountSetSelectError || num.startDateError || num.endDateError;
                });

                if (errorList && errorList.length > 0) {
                    return true;
                } else {
                    return false;
                }
            };

            // 验证模板列表
            var checkTemplateList = function () {
                var hasError = false;
                if ($scope.selectCompany.organizationServiceTemplateGroupList && $scope.selectCompany.organizationServiceTemplateGroupList.length > 0) {
                    $scope.selectCompany.organizationServiceTemplateGroupList.forEach(function (row) {
                        $scope.checkTemplate(row);
                        if (row.selectedTemplateError) {
                            hasError = true;
                        }
                    });
                }

                return hasError;
            };

            // 验证模板方法
            $scope.checkTemplate = function (row) {
                if (!row.templateGroupID) {

                    row.selectedTemplateError = $scope.resources.OrganizationMsgTemplateRequired;

                } else {
                    row.selectedTemplateError = null;
                }
            };

            // 获取当前机构下的子机构
            var getSubOrgList = function (branch) {

                var orgList = [];

                if (branch.children && branch.children.length > 0) {
                    branch.children.forEach(function (row) {
                        orgList.push(row.data);
                        var tempList = getSubOrgList(row);
                        if (tempList && tempList.length > 0) {
                            orgList = _.union(orgList, tempList);
                        }
                    });
                }

                return orgList;
            };



            var showUserTab = function () {


                var generateData = function (count) {
                    var i;
                    var surnames = ['Smith', 'Johnson', 'Brown', 'Taylor', 'Anderson', 'Harris', 'Clark', 'Allen', 'Scott', 'Carter'];
                    var names = ['James', 'John', 'Robert', 'Christopher', 'George', 'Mary', 'Nancy', 'Sandra', 'Michelle', 'Betty'];
                    var gender = ['Male', 'Female'];
                    var items = [];

                    for (i = 0; i < 10; i++) {

                        var nameIndex = i;
                        var item = {
                            id: i + 1,
                            userName: names[nameIndex],
                            roleNameList: surnames[nameIndex],

                        };
                        items.push(item);
                    }
                    return items;
                };

                var generateData2 = function () {

                    //showUserTab();
                    return dataSource;
                };



                $scope.showRowLines = true;
                $scope.showBorders = false;
                $scope.showColumnLines = false;

                $scope.BUDataGridOptions = {
                    dataSource: 'userRoleList',
                    rowTemplate: $("#gridRow"),
                    bindingOptions: {
                        showBorders: 'showBorders',
                        showColumnLines: 'showColumnLines',
                        showRowLines: 'showRowLines',
                    },
                    selection: {
                        mode: "single"
                    },
                    columns: [{
                        dataField: "userName",
                        caption: $translate.instant('UserTitleName'),
                        width: '40%',
                    }, {
                        dataField: "roleNameList",
                        caption: $translate.instant('RoleDesc'),
                        width: '50%',
                    }, {
                        caption: $translate.instant('Operation'),
                        width: '10%',
                    }],

                    //,
                    //loadPanel: {
                    //    enabled: false
                    //},
                    //scrolling: {
                    //    mode: "virtual"
                    //},
                    //sorting: {
                    //    mode: "none"
                    //}
                };
            };

            var setUserRoleUIGridColumns = function () {
                //  $scope.uigridColumns.splice(1);


            };

            var initUserRoleUIGrid = function () {



                $scope.UIGridColumns = [{
                    field: 'userName',
                    name: $translate.instant('UserTitleName'),
                    width: '30%',
                    headerCellClass: 'right',
                    enableFiltering: false,
                    cellTemplate: '<div class="ui-grid-cell-contents right"><span title="{{row.entity.userName}}">{{row.entity.userName}}<span></div>'
                }];

                if ($scope.hasEditPermission) {

                    var colum = {
                        field: 'roleNameList',
                        name: $translate.instant('RoleDesc'),
                        width: '60%',
                        headerCellClass: '',
                        cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.roleNameList}}<span></div>'
                    };

                    $scope.UIGridColumns.push(colum);

                    colum = {
                        name: $translate.instant('Operation'),
                        width: '10%',
                        field: 'Operation',
                        headerCellClass: 'center',
                        enableFiltering: false,
                        cellTemplate: '<div class="project-manage-grid-operation ui-grid-cell-contents">' +
                            '<span ng-click="grid.appScope.updateUserRole(row.entity)" class="operate-span" role="button" tabindex="0" aria-hidden="false" style=""><i class="material-icons middle black-color">create</i></span>' +
                            '<span ng-click="grid.appScope.deleteUserRole(row.entity)" class="operate-span" role="button" tabindex="0" aria-hidden="false" style=""><i class="material-icons button-icons icon-delete">delete</i></span>' +
                            '</div>'
                    };
                    $scope.UIGridColumns.push(colum);

                } else {
                    var columns = {
                        field: 'roleNameList',
                        name: $translate.instant('RoleDesc'),
                        width: '70%',
                        headerCellClass: '',
                        cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.roleNameList}}<span></div>'
                    };
                    $scope.UIGridColumns.push(columns);
                }

                $scope.userRoleGridOptions = {
                    rowHeight: 30,
                    selectionRowHeaderWidth: constant.UIGrid.selectionRowHeaderWidth,
                    enableFullRowSelection: true,
                    enableRowSelection: true,
                    enableSorting: false,
                    enableFiltering: false,
                    enableColumnMenus: false,
                    enableRowHeaderSelection: false,
                    multiSelect: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    columnDefs: $scope.UIGridColumns,
                    onRegisterApi: function (gridApi) {
                        $scope.gridApi = gridApi;
                        $interval(function () {
                            $scope.gridApi.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);
                    }
                };
            };


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

            //为当前机构添加用户
            var addUserToOrg = function (selectedUserArray) {

                var selectedArr = [];

                if (selectedUserArray && selectedUserArray.length > 0) {
                    for (var i = 0; i < selectedUserArray.length; i++) {
                        ////用户的角色列表
                        //var roleList = selectedUserArray[i].roleInfoList;

                        //去掉在当前机构下存在的用户,当前用户的权限可能已经改动过
                        var isUserExist = _.find($scope.userRoleGridOptions.data, function (num) {
                            return num.userID == selectedUserArray[i].userID;
                        });

                        if (isUserExist) {
                            continue;
                        }

                        var selectedObject = {
                            id: PWC.newGuid(),
                            userID: selectedUserArray[i].userID,
                            organizationID: $scope.selectedOrgID,
                            IsAccessible: true,
                            hasOriginalRole: true
                        };

                        selectedArr.push(selectedObject);
                    }
                }

                if (selectedArr.length > 0) {
                    userService.updateUserRoleForOrg(selectedArr).success(function (data) {
                        if (data) {
                            showSuccessMsg("SaveSuccess");
                            //重新加载用户list
                            loadUserRoleList($scope.selectedOrgID);
                        }
                    });
                } else {
                    showWarning('UserExists');
                }
            };

            //添加用户,弹框,call指令 add-exist-user-modal
            $scope.addUser = function () {
                var selectedKeyItem = [];
                $scope.userRoleGridOptions.data.forEach(function (row) {
                    selectedKeyItem.push(row.id);
                });
                $scope.addUserOperateType = constant.Operation.Add;
                $scope.addUserIsUpdate = false;
                $scope.selectedKeyItems = selectedKeyItem;
            };
            $scope.permissionPopover = {
                //content: $scope.permissionList,
                templateUrl: 'permissionPopoverTemplate.html',
                title: $translate.instant('TPermission')
            };

            //Jack
            $scope.showPermission = function (item) {

                var roleID = item.id;
                $scope.permissionList = [];
                var currentPermission = _.find($scope.allRolePermission, function (row) {
                    return row.roleID == roleID;
                });
                if (currentPermission && currentPermission.permissionList) {
                    $scope.permissionList = currentPermission.permissionList;
                    var copyData = angular.copy(currentPermission.permissionList);
                    copyData.forEach(function (item) {
                        var findParent = _.find(currentPermission.permissionList, function (num) {
                            return num.id === item.parentID;
                        });
                        if (!findParent) {
                            item.parentID = null;
                        }
                    });

                    $scope.permissionTreeViewData = copyData;// currentPermission.permissionList;
                    // console.log(JSON.stringify($scope.permissionTreeViewData));
                }
                // console.log(JSON.stringify(item));
            };




            var getAllRolePermission = function () {
                roleService.getAllRolePermission(constant.serviceType.VAT).success(function (data) {
                    if (data) {
                        $scope.allRolePermission = data;
                        //console.log('all permission: '+JSON.stringify(data));
                    }
                });
            };

            //$scope.showRoleInfo = function (data) {
            //    $scope.currentEmployee = data.model.employee;
            //    $scope.visiblePopup = true;
            //};


            var confirmWarningWindow = function (title, text) {
                var deferred = $q.defer();
                SweetAlert.swal({
                    title: title,
                    text: text,
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    allowOutsideClick: false,
                    confirmButtonText: $translate.instant('Confirm'),
                    cancelButtonText: $translate.instant('Cancel'),
                    closeOnConfirm: false,
                    closeOnCancel: true
                },
                    function (isConfirm) {
                        deferred.resolve(isConfirm);
                    });

                return deferred.promise;
            };


            //删除用户角色
            $scope.deleteUserRole = function (userModel) {

                var confirmToDelete = $translate.instant('ConfirmToDelete');

                confirmWarningWindow(confirmToDelete, '').then(function (data) {
                    if (data) {
                        var userOrgDto = {
                            userID: userModel.id,
                            OrgID: $scope.selectedOrgID
                        }
                        //$log.debug(JSON.stringify(userModel));
                        userService.deleteUserRoleForOrg(userOrgDto).success(function (data) {
                            showSuccessMsg("OrganizationStructureDeleteSuccess");
                            //重新加载用户list
                            loadUserRoleList($scope.selectedOrgID);

                        });
                    }
                });
            };

            // 添加或者编辑机构成功之后,刷新当前页面的数据
            $scope.$watch('userRolesIsUpdate', function (newValue, oldValue) {
                if (newValue) {
                    //重新加载用户list
                    loadUserRoleList($scope.selectedOrgID);
                }
            });

            //编辑用户角色
            $scope.updateUserRole = function (userRole) {
                $scope.userRoleOperateType = constant.Operation.Edit;
                $scope.selectedOrgID = $scope.selectedOrgID;
                $scope.selectedUserID = userRole.id;
                $scope.userRolesIsUpdate = false;
            };

            // 添加一行账套设置 (jack)
            $scope.newOrgAccountRow = function () {
                var index = $scope.OrgAccountRowIndex;
                var enterpriseAccountSetList = copyArray($scope.enterpriseAccountSetList);
                var d = new Date();
                var now = d.formatDateTime('yyyy-MM');

                var row = {
                    enterpriseAccountSetName: '',
                    effectiveDateStr: null,
                    expiredDateStr: null,
                    organizationID: $scope.selectedOrgID,
                    fromID: 'advancedSetFrom' + index,
                    toID: 'advancedSetTo' + index
                };

                $scope.OrgAccountRowIndex++;
                $scope.selectCompany.enterpriseAccountSetOrgList.push(row);
                $timeout(function () {
                    setDatepickerRow(row);
                }, 200);
            };


            $scope.getGridHeight = function () {
                return { height: $(".dx-viewport").height() + "px" };
            };

            //获取当前角色对应的权限列表
            var loadPermissionTree = function () {
                $scope.permissionTreeViewOptions = {
                    bindingOptions: {
                        dataSource: 'permissionTreeViewData',
                        expandAllEnabled: 'expandAll'
                    },
                    dataStructure: "plain",
                    selection: {
                        mode: "single"
                    },
                    loadPanel: {
                        enabled: true
                    },
                    scrolling: {
                        mode: "virtual"
                    },
                    parentIdExpr: "parentID",
                    keyExpr: "id",
                    displayExpr: 'name',
                    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'),
                    onInitialized: function (e) {
                        $scope.permissionTreeViewInstance = e.component;
                        // $scope.widgetInstance.selectItem($scope.itemElement.id);
                    }
                };
            };

            var checkUserPermission = function () {

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

                $scope.hasUserQueryPermission = false;
                $scope.hasUserEditPermission = false;

                ////查看用户角色的权限
                //var tempUser = constant.adminPermission.infrastructure.userManage;
                //list.push(tempUser.queryCode);
                //list.push(tempUser.editCode);

                var temp = constant.adminPermission.infrastructure.organizationManage;
                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.hasAddPermission = data[temp.addCode];
                    $scope.hasEditPermission = data[temp.editCode];

                    //$scope.hasUserQueryPermission = data[tempUser.queryCode];
                    //$scope.hasUserEditPermission = data[tempUser.editCode];

                    if ($scope.hasQueryPermission) {

                        initUserRoleUIGrid();
                        loadPermissionTree();
                        initOrg();
                        getAllRolePermission();

                    }

                });
            };


            (function initialize() {
                $scope.showRowLines = true;
                $log.debug('organizationManageController.ctor()...');
                //scope model
                $scope.title = $translate.instant('OrganizationManageTitle');
                $scope.orgList = [];
                $scope.checkedOrgsSet = {};
                $scope.set = [];
                $scope.maxTitleLength = 10;
                $scope.maxValueLength = 20;
                $scope.selectCompany = {};
                $scope.showAttributeDimensionID = 'orgmanage';

                $scope.searchText = '';

                $scope.isCanOrganizationIsActiveBtn = true;

                $scope.currentNavItem = 'page1';
                $scope.userRoleList = "[]";
                //showUserTab();

                checkUserPermission();
                $timeout(function () {

                    $scope.isLoadComplete = true;

                }, 500);
            })();
        }
    ]);

infrastructureModule.directive('organizationManage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('organizationManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/organizationManage/organization-manage.html' + '?_=' + Math.random(),
            replace: true,
            scope: {
                organizationId: '@'
            },
            controller: 'OrganizationManageController',
            link: function (scope, element, attrs, $element) {

                //https://github.com/nathancahill/Split.js/
                Split(['#org-left-container', '#org-right-container'], {
                    //An array of initial sizes of the elements, specified as percentage values. Example: Setting the initial sizes to 25% and 75%.
                    sizes: [20, 80],

                    //An array of minimum sizes of the elements, specified as pixel values. Example: Setting the minimum sizes to 100px and 300px, respectively.
                    minSize: [200, 750],

                    onDragEnd: function () {
                        //$timeout(function () {
                        //    $rootScope.$broadcast(enums.vatEvent.layoutChanged, {});
                        //}, 700);
                    }
                }) 
            }
        };
    }
]);

infrastructureModule.directive('taxPayerNumberUnique', ['$q','orgService',function ($q, orgService) {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            if (!ctrl) return;

            ctrl.$asyncValidators.taxPayerNumberUnique = function (modelValue, viewValue) {
                if (ctrl.$isEmpty(modelValue)) {
                    $q.resolve();
                }

                var def = $q.defer();

                var id = scope.isAdd ? "" : scope.selectCompany.id;
                orgService.taxPayerNumberUniqueValidate(id, viewValue)
                    .success(function (data, status, headers, config) {
                        if (data) {
                            def.resolve();
                        } else {
                            def.reject();
                        }
                    })
                    .error(function (data, status, headers, config) {
                        def.reject();
                    });

                return def.promise;
            };
        }
    }
}]);

infrastructureModule.directive('codeUnique', ['$q','orgService',function ($q, orgService) {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            if (!ctrl) return;

            ctrl.$asyncValidators.codeUnique = function (modelValue, viewValue) {
                if (ctrl.$isEmpty(modelValue)) {
                    $q.resolve();
                }

                var def = $q.defer();

                var id = scope.isAdd ? "" : scope.selectCompany.id;
                orgService.codeUniqueValidate(id, viewValue)
                    .success(function (data, status, headers, config) {
                        if (data) {
                            def.resolve();
                        } else {
                            def.reject();
                        }
                    })
                    .error(function (data, status, headers, config) {
                        def.reject();
                    });

                return def.promise;
            };
        }
    }
}]);
infrastructureModule
   .controller('OrganizationSubsidiaryViewController', ['$scope', '$log', 'SweetAlert', 'dimensionService', 'statisticAttributeService', 'regionService', '$translate', 'areaRegionService', 'uiGridTreeViewConstants', '$timeout', 'areaService', 'uiGridConstants', '$interval', 'orgService', '$q', '$state', '$filter', 'roleService',
        function ($scope, $log, SweetAlert, dimensionService, statisticAttributeService, regionService, $translate, areaRegionService, uiGridTreeViewConstants, $timeout, areaService, uiGridConstants, $interval, orgService, $q, $state, $filter, roleService) {
            'use strict';

            var orgGeneralInfoPopId = '#orgGeneralInfoPop';
            var unassisgnText = $translate.instant('UnAssignText');
            $scope.unassisgnText = unassisgnText;

            // 系统级别的纬度id列表
            var systemDimensionIdList = [
                constant.attributeID.businessUnitID,
                constant.attributeID.areaID,
                constant.attributeID.organizationStructureID,
                constant.attributeID.userID,
                constant.attributeID.industryID,
                constant.attributeID.rgSubChildrenID
            ];

            var template = {
                topNodeTemplate: $("#dimension-topNode").html(),  //最顶层节点
                nameNodeQuery: $("#dimension-org-node-name-query").html(),  //机构名称 
                nameNodeEdit: $("#dimension-org-node-name-edit").html(),  //机构名称 
                rowNode: $("#dimension-row-node").html() //普通行
            };

            //设置维度的名称和值,和类型
            var setParentDimension = function () {
                dimensionService.getDimensionById($scope.parentDimensionID).success(function (data) {
                    if (data) {
                        $scope.parentDimensionName = data.name;
                        $scope.parentDimensionType = data.dimensionType;
                    }
                });
            };

            //隐藏机构general info
            var hideOrgGeneralInfo = function () {
                $(orgGeneralInfoPopId).hide();
            };


            // 显示机构general info,并设置好位置
            var showOrgCard = function (popCard, row, topOffset, leftOffset) {

                popCard.css("display", "block");

                var top = row.offset().top + topOffset;
                if (top + popCard.height() > window.innerHeight) {
                    top = window.innerHeight - popCard.height() - topOffset;
                }

                popCard.css('top', top + 'px');

                var left = row.offset().left + leftOffset;
                if (left + popCard.width() > window.innerWidth) {
                    left = row.offset().left - popCard.width() - leftOffset;
                }

                popCard.css('left', left + 'px');

                popCard.show();

                $(document).one('click', function () {
                    hideOrgGeneralInfo();
                });
            };

            //添加事业部,机构层级,自定义维度的值等等
            $scope.addDimensionValue = function () {
                if ($scope.parentDimensionType == constant.dimensionType.BusinessUnit) {
                    $scope.orgOperateBusinessType = constant.Operation.Add;
                    $scope.businessUnitID = null;
                    $scope.isBusinessUpdate = false;
                }
                if ($scope.parentDimensionType == constant.dimensionType.OrganizationStructure) {
                    $scope.orgOperateOrgStructureType = constant.Operation.Add;
                    $scope.selectedOrgStructureID = null;
                    $scope.isOrgStructureUpdate = false;
                }
                else if ($scope.parentDimensionType == constant.dimensionType.SelfDimension) {
                    $scope.dimensionValueOperateType = constant.Operation.Add;
                    $scope.dimensionID = $scope.parentDimensionID;
                    $scope.dimensionName = $scope.parentDimensionName;
                    $scope.isDimensionValueUpdate = false;
                    $scope.selectedDimensionValueID = null;
                }
            };

            $scope.AddOrg = function () {
                $scope.orgOperateType = constant.Operation.Add;
                $scope.selectedOrg = null;
                $scope.isOrgUpdate = false;
                $scope.organization = {

                };
            };

            $scope.EditOrg = function (orgID) {
                $scope.orgOperateType = constant.Operation.Edit;
                //$scope.selectedOrg = orgID;
                $scope.isOrgUpdate = false;
                $scope.selectedOrg = {
                    id: orgID
                };
            };

            //点击机构名称,显示详细信息
            $scope.showOrgGenerateInfo = function (row) {
                //  $scope.isRenderCompletedGeneralInfo = false;
                $scope.orgIdGeneralInfo = row.entity.orgID;

                var orgGeneralInfoPopup = $(orgGeneralInfoPopId);
                var rowId = $('#' + row.entity.orgID);
                showOrgCard(orgGeneralInfoPopup, rowId, 30, 50);
            };

            // 添加或者编辑机构成功之后,刷新当前页面的数据
            $scope.$watch('isOrgUpdate', function (newValue, oldValue) {
                if (newValue) {
                    initOrgChartData();
                    notifyTopPage();
                }
            });

            //自定义显示属性更新后,刷新当前页面的orgchart
            $scope.$watch('isAttributeUpdate', function (newValue, oldValue) {
                if (newValue) {
                    initOrgChartData();
                    populateUIGridColumns();
                }
            });

            // 添加或者编辑事业部成功之后,刷新当前页面的数据
            $scope.$watch('isBusinessUpdate', function (newValue, oldValue) {
                if (newValue) {
                    initOrgChartData();
                }
            });

            //修改机构成功之后 通知父层去更新机构数的统计
            var notifyTopPage = function () {
                $scope.$emit("hasOrgUpdated", { isupdated: true });
            };

            //所属行业弹框,也是通用模板
            var getCommonCard = function (dimensionValueID, dimensionValue, attributeName, attributeID) {

                populateUIGridColumns();

                //参数,维度值的ID,如事业部1,事业部2 ,然后是顶层事业部,如事业部
                orgService.getOrgCustomDashbord(dimensionValueID, $scope.parentDimensionID, attributeID).success(function (data) {
                    if (data) {

                        console.log('data:');
                        console.log(JSON.stringify(data));

                        data.orgDtoList.forEach(function (row) {
                            if (row.level != null) {
                                row.$$treeLevel = parseInt(row.level);
                            }
                        });

                        $scope.orgCustomList = data.orgCustomDtoList;
                        $scope.orgList = data.orgDtoList;

                        for (var i = 0; i < $scope.orgList.length; i++) {
                            var row = $scope.orgList[i];

                            if ($scope.attributeList && $scope.attributeList.length > 0) {

                                for (var j = 0; j < $scope.attributeList.length; j++) {
                                    if (systemDimensionIdList.indexOf($scope.attributeList[j].attributeID) === -1) {
                                        var targetVaule = _.find($scope.orgCustomList, function (data) {
                                            return data.orgID === row.orgID && data.dimensionID === $scope.attributeList[j].belongDimensionID;
                                        });

                                        if (targetVaule) {
                                            row["selfDimension" + j] = targetVaule.dimensionValueName;
                                        } else {
                                            row["selfDimension" + j] = '';
                                        }
                                    }
                                }
                            }

                        };

                        $scope.dimensionValue = dimensionValue;
                        $scope.attributeName = attributeName;
                        $scope.commonUIGridList.data = $scope.orgList;
                        $scope.commonCountDataSource = data.orgCountList;
                        console.log(JSON.stringify($scope.orgList));
                        console.log("cusomer:" + JSON.stringify(data.orgCustomDtoList));
                        console.log("111:" + JSON.stringify($scope.attributeList));
                    }
                });
            };

            //将角色列表换成逗号分隔
            var formatRoleList = function (roleInfoList) {
                var newList = "";
                roleInfoList.forEach(function (row) {
                    if (row) {
                        newList += row.name + constant.comma;
                    }
                });
                if (newList.length > 0) {
                    newList = newList.substr(0, newList.length - 1);
                }

                return newList;
            };

            //用户卡片弹框
            var getUserStatisCard = function (dimensionValueID, dimensionValue, attributeName, attributeID) {

                $scope.userBUDimensionValueID = dimensionValueID;
                $scope.dimensionValue = dimensionValue;
                $scope.attributeName = attributeName;


                //用户下面多个角色,多少个机构
                roleService.getDimensionUserRoleList($scope.parentDimensionID, dimensionValueID).success(function (data) {
                    if (data) {
                        for (var i = 0; i < data.length; i++) {
                            var row = data[i];
                            data[i].userID = row.userID;
                            data[i].userName = row.userName;
                            data[i].roleInfo = formatRoleList(row.roleList);
                            data[i].orgCount = row && row.orgList && row.orgList.length;
                        }
                        //用户数据绑定
                        $scope.userDatagridDataSource = data;
                    }

                });
                //角色统计,角色下面多少个用户
                roleService.getDimensionRoleUserList($scope.parentDimensionID, dimensionValueID).success(function (data) {
                    if (data) {
                        for (var i = 0; i < data.length; i++) {
                            var row = data[i];
                            data[i].count = row && row.userList && row.userList.length;
                            data[i].name = row.roleName;
                        }

                        $scope.roleCountDataSource = data;
                    }
                });
            };

            var ReplaceObj = {
                //顶部节点
                topNodeName: '{{#topNodeName#}}',
                //事业部名称
                dimensionValue: '{{#dimensionValue#}}',
                dimensionValueID: '{{#dimensionValueID#}}',
                //高亮部分统计
                //hightNodeCount: '{{#dimensionValueCount#}}', //比如 '100'
                //hightNodeName: '{{#attributeName#}}',   //比如'分公司'
                //普通维度统计
                attributeID: '{{#attributeID#}}',
                attributeName: '{{#attributeName#}}',  //维度名字,如用户数,覆盖区域,所属行业等
                attributeValueCount: '{{#attributeValueCount#}}',      //对于维度的统计
                attributeType: '{{#attributeType#}}',             //维度的类型区分值,如1:事业部,2:分公司
                firstAttrName: '{{#firstAttr}}',
                secondAttrName: '{{#secondAttr}}',
                firstAttrTitle: '{{#firstAttrTitle}}',
                secondAttrTitle: '{{#secondAttrTitle}}'
            };

            //构造Echart模板,并且初始化数据
            $scope.populateChartDatasource = function (parentOrgID, expandedList) {
                $scope.renderOrgChart({});
                console.log('expandedOrgList', expandedList);
                $scope.pLevel = 0;
                orgService.getOrgDashboard($scope.parentDimensionID, parentOrgID, expandedList).success(function (data) {
                    if (data !== undefined && data !== null && data.length > 0) {

                        var topNodeName = '集团'; //template.topNodeTemplate.replace(ReplaceObj.topNodeName, $scope.parentDimensionName);

                        var datascource = {
                            'id': 'topid',
                            'name': topNodeName,
                            'pLevel': $scope.pLevel,
                            'children': [],
                            'relationship': '111'
                        };

                        data.forEach(function (row) {

                            var newNode = createNewNode(row);
                            datascource.children.push(newNode);

                            if (row.children !== null && row.children.length > 0) {
                                $scope.pLevel = $scope.pLevel + 1;
                                createNodeRecursion(row.children, newNode);
                            }
                        });

                        //生成orgchart
                        $scope.renderOrgChart(datascource);
                    }
                });
            };

            var createNodeRecursion = function (childrenList, parentNode) {

                if (childrenList.length == 0) return;

                childrenList.forEach(function (row) {
                    var newNode = createNewNode(row);
                    parentNode.children.push(newNode);

                    if (row.children !== null && row.children.length > 0) {
                        $scope.pLevel = $scope.pLevel + 1;
                        createNodeRecursion(row.children, newNode);
                    }

                });
            };

            //创建orgchart节点
            var createNewNode = function (row) {

                var templateNameNode = template.nameNodeQuery;
                if ($scope.hasEditPermission) {
                    templateNameNode = template.nameNodeEdit;
                }

                var temp = [];
                var relationship = '110';
                if (row.hasChildren !== undefined && row.hasChildren) {
                    relationship = '111';
                }

                var node = {
                    'id': row.dimensionValueID,
                    'pLevel': $scope.pLevel,
                    'name': templateNameNode.replaceToEnd(ReplaceObj.dimensionValue, row.dimensionValue)
                        .replaceToEnd(ReplaceObj.dimensionValueID, row.dimensionValueID)
                        .replaceToEnd(ReplaceObj.dimensionValueID, row.dimensionValueID)
                        .replaceToEnd(ReplaceObj.firstAttrName, row.firstAttrName === null ? ' 未指定 &nbsp;' : $filter('limitString')(row.firstAttrName, 10))
                        .replaceToEnd(ReplaceObj.secondAttrName, row.secondAttrName === null ? ' 未指定 &nbsp;' : $filter('limitString')(row.secondAttrName, 10))
                        .replaceToEnd(ReplaceObj.firstAttrTitle, row.firstAttrName === null ? ' 未指定 &nbsp;' : row.firstAttrName)
                        .replaceToEnd(ReplaceObj.secondAttrTitle, row.secondAttrName === null ? ' 未指定 &nbsp;' : row.secondAttrName),

                    'title': (function () {

                        row.orgDtoList.forEach(function (item, index) {

                            temp += template.rowNode.replaceToEnd(ReplaceObj.attributeName, item.attributeName)
                                    .replaceToEnd(ReplaceObj.attributeValueCount, item.attributeValueCount)
                                    .replaceToEnd(ReplaceObj.dimensionValueID, row.dimensionValueID)
                                    .replaceToEnd(ReplaceObj.dimensionValue, row.dimensionValue)
                                   .replaceToEnd(ReplaceObj.attributeID, item.attributeID)
                                   .replaceToEnd(ReplaceObj.attributeType, item.attributeType);
                        });
                        return temp;

                    })(),
                    'children': [],
                    'relationship': relationship
                };

                //特殊处理,如果没有子机构,只显示本身即可
                if (row.hasChildren === undefined || !row.hasChildren) {
                    node.title = '';
                }

                return node;
            };

            //编辑自定义显示属性
            $scope.showCustomAttriute = function () {

                $scope.attributeOperateType = constant.Operation.Edit;
                $scope.showAttributeDimensionID = $scope.parentDimensionID;;
                $scope.isAttributeUpdate = false;
            };

            //自定义显示属性更新后,刷新当前页面的orgchart
            $scope.$watch('isAttributeUpdate', function (newValue, oldValue) {
                if (newValue) {
                    initOrgChartData();
                    populateUIGridColumns();
                }
            });

            //通用的ui grid 模板
            var commonUIGridInit = function () {
                $scope.uigridColumns = [{
                    field: 'orgName',
                    name: $translate.instant('OrganizationName'),
                    cellTemplate: '<div id="{{row.entity.orgID}}" ng-click="grid.appScope.showOrgGenerateInfo(row)" ng-class="{true: \'text-align-left\', false: \'text-align-left-padding\'}[row.entity.level==' + constant.level.First + ']"><span title="{{row.entity.orgName}}" >{{row.entity.orgName==null||row.entity.orgName==""?"' + unassisgnText + '":row.entity.orgName}}</span></div>'
                }];

                $scope.commonUIGridList = {
                    enableRowSelection: true,
                    enableSelectAll: false,
                    rowHeight: 30,
                    enableRowHeaderSelection: false,
                    modifierKeysToMultiSelect: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    enableVerticalScrollbar: uiGridConstants.scrollbars.enableVerticalScrollbar,

                    enableColumnResizing: true,
                    enableSorting: true,
                    enableColumnMenus: false,
                    enableFiltering: false,
                    showTreeExpandNoChildren: false,
                    enableFullRowSelection: true, //是否点击行任意位置后选中,默认为false
                    multiSelect: false, // 是否可以选择多个,默认为true; 
                    columnDefs: $scope.uigridColumns,

                    onRegisterApi: function (gridApi) {

                        $scope.gridApi = gridApi;

                        $scope.gridSelectCount = $scope.gridApi.selection.getSelectedRows().length;

                        // call resize every 500 ms for 5 s after modal finishes opening - usually only necessary on a bootstrap modal
                        $interval(function () {
                            $scope.gridApi.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);

                    }
                };

            };


            //添加过滤下拉列表
            var InitFilterList = function () {
                //初始化选择器为空
                $scope.filter = {};
                $scope.filter.selected = [];

                var datasource = constant.taxpayerNumberFilter.dataSource;

                datasource.forEach(function (row) {
                    row.value = $translate.instant(row.value);
                });
                $scope.taxPayerFilterList = datasource;
            };


            //筛选的时候,ng-check event will be triggered
            $scope.stateChanged = function ($event, data) {
                $scope.filter.selected = [];
                var checkbox = $event.target;
                if (checkbox.checked && $scope.filter.selected.indexOf(data.key) < 0) {
                    $scope.filter.selected.push(data.key);
                }

                orgDashboardFilterChanged();
            };

            var orgDashboardFilterChanged = function () {

                $('#orgName-search').find('input').val('')

                var selectedList = $scope.filter.selected;
                if (selectedList.length == 0) return;

                var selectedID = $scope.filter.selected[0] || constant.taxpayerNumberFilter.key_0;
                $scope.orgDashboardFilteredID = selectedID;

                var oldData = [];

                switch (selectedID) {
                    //所有对应状态,取默认值
                    case constant.taxpayerNumberFilter.key_0:  //all data
                        $scope.populateChartDatasource(0);
                        break;
                        //have taxpayerNumber
                    case constant.taxpayerNumberFilter.key_1:
                        $scope.populateChartDatasource(1);
                        break;
                    case constant.taxpayerNumberFilter.key_2:
                        $scope.populateChartDatasource(2);
                        break;
                }
            };


            var InitDXDataGrid = function () {
                loadUserDatagrid();
            };


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

                $scope.userdatagridOptions = {
                    bindingOptions: {
                        dataSource: 'userDatagridDataSource'
                    },
                    selection: {
                        mode: "single"
                    },
                    columns: [
                          {
                              dataField: "userName",
                              caption: $translate.instant('UserDesc'),
                              width: "30%",
                              cellTemplate: function (container, options) {
                                  try {
                                      $('<a>' + options.value + '</a>')
                                          .attr('href', '#/userDetail/' + options.row.data.userID)
                                           .appendTo(container);
                                  }
                                  catch (e) {
                                      $log.error(e);
                                  }
                              }
                          },
                        {
                            dataField: "roleInfo",
                            caption: $translate.instant('Role'),
                            width: "50%"
                        },
                        {
                            dataField: "orgCount",
                            caption: $translate.instant('OrganizationCount'),
                            alignment: 'center',
                            width: "20%"

                        },
                    ],
                    loadPanel: {
                        enabled: false
                    },
                    scrolling: {
                        mode: "virtual"
                    },
                    noDataText: $translate.instant('NoDataText'),
                    showColumnLines: false,
                    showRowLines: false,
                    allowColumnResizing: true,
                    rowAlternationEnabled: true,
                    showBorders: false,
                    sorting: {
                        mode: "none"
                    }
                };
            };


            //根据自定义维度设置显示的卡片的列
            var populateUIGridColumns = function () {
                //获取维度值数据
                statisticAttributeService.getByParentDimensionID($scope.parentDimensionID).success(function (result) {
                    if (result) {

                        $scope.attributeList = result;
                        var column = {
                        };
                        $scope.uigridColumns.splice(1);

                        var j = 0;
                        result.forEach(function (attr) {
                            if (attr.attributeType == constant.attributeType.BusinessUnit) {
                                column = {
                                    field: 'businessUnitName',
                                    name: attr.attributeName,
                                    cellTemplate: '<div class="text-align-left"><span title="{{row.entity.businessUnitName}}">{{row.entity.businessUnitName}}</span></div>'
                                };
                                $scope.uigridColumns.push(column);
                            }
                            else if (attr.attributeType == constant.attributeType.OrganizationStructure) {
                                column = {
                                    type: 'string',
                                    field: 'structureName',
                                    name: attr.attributeName,
                                    cellTemplate: '<div class="text-align-left"><span title="{{row.entity.structureName}}">{{row.entity.structureName}}</span></div>'
                                };
                                $scope.uigridColumns.push(column);
                            }
                            else if (attr.attributeType == constant.attributeType.Industry) {
                                column = {
                                    type: 'string',
                                    field: 'industryName',
                                    name: attr.attributeName,
                                    cellTemplate: '<div class="text-align-left"><span title="{{row.entity.industryName}}">{{row.entity.industryName}}</span></div>'
                                };
                                $scope.uigridColumns.push(column);
                            }
                                //else if (attr.attributeType == constant.attributeType.User) {
                                //    column = {
                                //        type: 'string',
                                //        field: 'industryName',
                                //        name: attr.attributeName,
                                //        cellTemplate: '<div class="text-align-left"><span title="{{row.entity.businessUnitName}}">{{row.entity.businessUnitName}}</span></div>'
                                //    };
                                //    $scope.uigridColumns.push(column);
                                //}
                            else if (attr.attributeType == constant.attributeType.Area) {
                                column = {
                                    type: 'string',
                                    field: 'areaName',
                                    name: attr.attributeName,
                                    cellTemplate: '<div class="text-align-left"><span title="{{row.entity.areaName}}">{{row.entity.areaName}}</span></div>'
                                };
                                $scope.uigridColumns.push(column);
                            }
                            else if (attr.attributeType == constant.attributeType.SelfDimension) {
                                //column = {
                                //    type: 'string',
                                //    field: 'dimensionValueName',
                                //    name: attr.attributeName,
                                //    cellTemplate: '<div class="text-align-left"><span title="{{row.entity.dimensionValueName}}">{{row.entity.dimensionValueName}}</span></div>'
                                //};
                                var column = {
                                    field: 'selfDimension' + j,
                                    name: attr.attributeName,
                                    cellTemplate: '<div class="text-align-left"><span title="{{row.entity.selfDimension' + j + '}}">{{row.entity.selfDimension' + j + '}}</span></div>'
                                };

                                $scope.uigridColumns.push(column);
                            }

                            j++;
                        });
                    }
                });

            };

            var initUIGrid = function () {
                commonUIGridInit();

            };

            var initOrgChartData = function () {
                $scope.orgDashboardFilteredID = constant.taxpayerNumberFilter.key_0;
                InitFilterList();
                $scope.populateChartDatasource('');
            };

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

                var list = [];
                $scope.hasQueryPermission = false;
                $scope.hasEditPermission = false;
                $scope.hasAddPermission = false;
                $scope.hasAttributeQueryPermission = false;

                var temp = constant.adminPermission.infrastructure.organizationManage;
                list.push(temp.queryCode);
                list.push(temp.addCode);
                list.push(temp.editCode);

                //自定义显示属性的权限
                var tempAttr = constant.adminPermission.infrastructure.customAttribute;
                list.push(tempAttr.queryCode);


                $scope.$root.checkUserPermissionList(list).success(function (data) {
                    $scope.hasQueryPermission = data[temp.queryCode];
                    $scope.hasEditPermission = data[temp.editCode];
                    $scope.hasAddPermission = data[temp.addCode];

                    $scope.hasAttributeQueryPermission = data[tempAttr.queryCode];

                    if ($scope.hasQueryPermission) {
                        initOrgChartData();
                        getOrgList();
                    }
                });
            };

            var getOrgList = function () {
                orgService.getOrgListLevel().success(function (orgList) {
                    if (orgList) {

                        var orgNameList = _.pluck(orgList, 'name');
                        $("#orgName-search").dxAutocomplete({
                            dataSource: orgNameList,
                            placeholder: "请输入机构名",
                            showClearButton: true,
                            onContentReady: function (e) {
                                //var btn = $("<button class='fa fa-cogs'></button>"); 
                                //e.element.find(".dx-texteditor-buttons-container").append(btn);
                            },
                            onValueChanged: function (data) {
                                var org = _.find(orgList, function (item) { return item.name == data.value; });
                                if (org && org.id) {
                                    $scope.populateChartDatasource('@@Current@@' + org.id);
                                } else if (data.value == '') {
                                    $scope.populateChartDatasource('');
                                }
                            }
                        });
                    }
                });
            };

            (function initialize() {
                $log.debug('OrganizationSubsidaryViewController.ctor()...');
                $log.debug('$state.params.dimensionID:' + $state.params.dimensionID);
                $scope.dimensionId = $state.params.dimensionID === null ? 'c61a5bd6-a996-4952-9869-d053995237e7' : $state.params.dimensionID;

                var parentDimensionID = $state.params.dimensionID || $scope.dimensionId;
                $scope.parentDimensionID = parentDimensionID;
                $scope.showAttributeDimensionID = $scope.parentDimensionID;

                $scope.orgID = '';
                $scope.createNewNode = createNewNode;
                $scope.template = template;
                $scope.ReplaceObj = ReplaceObj;
                $scope.showOrgCard = showOrgCard;
                setParentDimension();
                InitDXDataGrid();
                initUIGrid();

                checkUserPermission();

                $scope.getCommonCard = getCommonCard;
                $scope.getUserStatisCard = getUserStatisCard;
            })();
        }
   ]);
infrastructureModule.directive('organizationSubsidiaryView', ['$log', '$compile', '$timeout', '$interval', '$q', 'orgService', 'loginContext',
    function ($log, $compile, $timeout, $interval, $q, orgService, loginContext) {
        'use strict';
        $log.debug('organizationSubsidiaryView.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/organizationSubsidiaryView/organization-subsidiary-view.html' + '?_=' + Math.random(),
            scope: {},
            replace: true,
            controller: 'OrganizationSubsidiaryViewController',
            link: function (scope, element) {

                var getId = function () {
                    return (new Date().getTime()) * 1000 + Math.floor(Math.random() * 1001);
                };

                $(".card").draggable({ containment: "parent", cursor: "cursor", handle: ".card-header" });

                var title = $('#node-title').html();
                title = title.replace('{{#OrgID}}', 'test')
                                            .replace('{{#SubsidiaryCount}}', '0')
                                            .replace('{{#AreaCount}}', '0');

                //渲染orgchart
                var ajaxURLs = {
                    'children': function (nodeData) {

                        var dimensionID = scope.parentDimensionID;
                        var webApiHostUrl = loginContext.apiHost + constant.webapi.prefix + '/org/getOrgDashboardOnly?dimensionID=' + dimensionID + '&parentOrgID=' + nodeData.id + '&filterFlag=' + scope.orgDashboardFilteredID
                        return webApiHostUrl;
                    }
                };

                var showCardSeleted = '.show-card';
                // 机构缩略图ID
                var orgGeneralInfoPopId = '#orgGeneralInfoPop';
                element.on('click', showCardSeleted, function () {
                    $(orgGeneralInfoPopId).css('display', 'none');
                    stopPropagation();
                });

                scope.fullScreenText = '全屏展示';
                scope.showFullScreen = function () {

                    $('.organization-subsidiary-view').parent().toggleClass('fullScreen');
                    if ($('.organization-subsidiary-view').parent().hasClass('fullScreen')) {
                        scope.fullScreenText = '退出全屏';
                        scope.isShowFullScreen = true;
                    } else {
                        scope.fullScreenText = '全屏展示';
                        scope.isShowFullScreen = false;
                    }
                }

                scope.renderOrgChart = function (datasource) {
                    $('#subsidiary-chart').html('');
                    $('#subsidiary-chart').orgchart({
                        'ajaxURL': ajaxURLs,
                        'nodeId': 'id',
                        'data': datasource,
                        'pan': true,
                        'zoom': false,
                        "draggable": true,
                        'exportButton': false,
                        'nodeContent': 'title',
                        'exportFilename': 'SportsChart',
                        'parentNodeSymbol': 'fa-th-large',
                        'depth': 999,
                        'createNode': function ($node, data) {
                            $node[0].id = getId();
                            if (data.pLevel == 0) {
                                $node.find('.title').addClass('orgchart-background-0').attr('pLevel', data.pLevel);
                            }
                            else if (data.pLevel == 1) {
                                $node.find('.title').addClass('orgchart-background-1').attr('pLevel', data.pLevel);;
                            }
                            else {
                                $node.find('.title').addClass('orgchart-background-2').attr('pLevel', data.pLevel);;
                            }
                        },
                        'initOrgChartData': scope.populateChartDatasource,
                        'hasEditPermission': scope.hasEditPermission,
                    })
                    .on('click', '.node', function () {
                        var $this = $(this);
                        var title = $this.find('.title').text();
                        $('#selected-node').val($.trim(title)).data('node', $this);
                    })
                    .on('click', '.orgchart', function (event) {
                        if (!$(event.target).closest('.node').length) {
                            $('#selected-node').val('');
                        }
                    });
                };

                var filterSelector = '.filter-select';

                $(filterSelector).on("click", function (e) {
                    stopPropagation();
                });

                scope.showFilter = function () {
                    if ($(filterSelector).is(":hidden")) {
                        $(filterSelector).show();
                    } else {
                        $(filterSelector).hide();
                    }

                    $(document).one("click", function () {
                        $(filterSelector).hide();
                    });
                    stopPropagation();
                };


                $('input[name="chart-state"]').on('click', function () {
                    $('.orgchart').toggleClass('view-state', this.value !== 'view');
                    $('#edit-panel').toggleClass('view-state', this.value === 'view');
                    if ($(this).val() === 'edit') {
                        $('.orgchart').find('tr').removeClass('hidden')
                          .find('td').removeClass('hidden')
                          .find('.node').removeClass('slide-up slide-down slide-right slide-left');
                    } else {
                        $('#btn-reset').trigger('click');
                    }
                });

                $('input[name="node-type"]').on('click', function () {
                    var $this = $(this);
                    if ($this.val() === 'parent') {
                        $('#edit-panel').addClass('edit-parent-node');
                        $('#new-nodelist').children(':gt(0)').remove();
                    } else {
                        $('#edit-panel').removeClass('edit-parent-node');
                    }
                });

                $('#btn-add-input').on('click', function () {
                    $('#new-nodelist').append('<li><input type="text" class="new-node"></li>');
                });

                $('#btn-remove-input').on('click', function () {
                    var inputs = $('#new-nodelist').children('li');
                    if (inputs.length > 1) {
                        inputs.last().remove();
                    }
                });

                //添加节点
                $('#btn-add-nodes').on('click', function () {
                    var $chartContainer = $('#subsidiary-chart');
                    var nodeVals = [];
                    $('#new-nodelist').find('.new-node').each(function (index, item) {
                        var validVal = item.value.trim();
                        if (validVal.length) {
                            nodeVals.push(validVal);
                        }
                    });
                    var $node = $('#selected-node').data('node');
                    if (!nodeVals.length) {
                        alert('Please input value for new node');
                        return;
                    }
                    var nodeType = $('input[name="node-type"]:checked');
                    if (!nodeType.length) {
                        alert('Please select a node type');
                        return;
                    }
                    if (nodeType.val() !== 'parent' && !$('.orgchart').length) {
                        alert('Please creat the root node firstly when you want to build up the orgchart from the scratch');
                        return;
                    }
                    if (nodeType.val() !== 'parent' && !$node) {
                        alert('Please select one node in orgchart');
                        return;
                    }
                    if (nodeType.val() === 'parent') {
                        if (!$chartContainer.children().length) {// if the original chart has been deleted
                            $chartContainer.orgchart({
                                'data': { 'name': nodeVals[0] },
                                'exportButton': true,
                                'exportFilename': 'SportsChart',
                                'parentNodeSymbol': 'fa-th-large',
                                'createNode': function ($node, data) {
                                    $node[0].id = getId();
                                }
                            })
                            .find('.orgchart').addClass('view-state');
                        } else {

                            $chartContainer.orgchart('addParent', $chartContainer.find('.node:first'), { 'name': nodeVals[0], 'Id': getId() });
                        }
                    } else if (nodeType.val() === 'siblings') {
                        $chartContainer.orgchart('addSiblings', $node,
                          {
                              'siblings': nodeVals.map(function (item) {
                                  var name = $('#node-name').html();
                                  name = name.replace('{{#OrgName}}', item)
                                                              .replace('{{#BusinessUnitName}}', 'xxx事业部')
                                                              .replace('{{#AreaName}}', 'xx区域')
                                                              .replace('{{#OrgID}}', 'test');
                                  return {
                                      'name': name.replace('{{name}}', item), 'title': title, 'relationship': '110', 'Id': getId()
                                  };
                              })
                          });
                    } else {
                        var hasChild = $node.parent().attr('colspan') > 0 ? true : false;
                        if (!hasChild) {
                            var rel = nodeVals.length > 1 ? '110' : '100';
                            $chartContainer.orgchart('addChildren', $node, {
                                'children': nodeVals.map(function (item) {
                                    return { 'name': item, 'relationship': rel, 'Id': getId() };
                                })
                            }, $.extend({}, $chartContainer.find('.orgchart').data('options'), { depth: 0 }));
                        } else {
                            $chartContainer.orgchart('addSiblings', $node.closest('tr').siblings('.nodes').find('.node:first'),
                              {
                                  'siblings': nodeVals.map(function (item) { return { 'name': item, 'relationship': '110', 'Id': getId() }; })
                              });
                        }
                    }
                });

                //删除节点
                $('#btn-delete-nodes').on('click', function () {
                    var $node = $('#selected-node').data('node');
                    if (!$node) {
                        alert('Please select one node in orgchart');
                        return;
                    } else if ($node[0] === $('.orgchart').find('.node:first')[0]) {
                        if (!window.confirm('Are you sure you want to delete the whole chart?')) {
                            return;
                        }
                    }
                    $('#subsidiary-chart').orgchart('removeNodes', $node);
                    $('#selected-node').val('').data('node', null);
                });

                //重置节点输入框
                $('#btn-reset').on('click', function () {
                    $('.orgchart').find('.focused').removeClass('focused');
                    $('#selected-node').val('');
                    $('#new-nodelist').find('input:first').val('').parent().siblings().remove();
                    $('#node-type-panel').find('input').prop('checked', false);
                });

                var drag_start = function (event) {
                    var style = window.getComputedStyle(event.target, null);
                    event.dataTransfer.setData("text",
                    (parseInt(style.getPropertyValue("left"), 10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"), 10) - event.clientY));
                }

                var drag_over = function (event) {
                    event.preventDefault();
                    return false;
                }

                var drop = function (event) {
                    var offset = event.dataTransfer.getData("text").split(',');
                    var dm = document.getElementById('edit-panel');
                    dm.style.left = (event.clientX + parseInt(offset[0], 10)) + 'px';
                    dm.style.top = (event.clientY + parseInt(offset[1], 10)) + 'px';
                    event.preventDefault();
                    return false;
                }

                var dm = document.getElementById('edit-panel');
                dm.addEventListener('dragstart', drag_start, false);
                document.body.addEventListener('dragover', drag_over, false);
                document.body.addEventListener('drop', drop, false);

                var orgAreaIndustryPopup, orgGeneralInfoPopup, row;
                var oldOrgId, oldOprType;
                var oldGeneralOrgId, oldGeneralOprType;
                var self, isGeneral;

                var stopPropagation = function (event) {
                    event = event || window.event;
                    if (event.stopPropagation) {
                        event.stopPropagation();
                    } else {
                        event.cancelBubble = true;
                    }
                }

                var showCard = function (thisCard, node) {

                    $(".card").css('visibility', 'hidden');
                    var nodeOffset = $(node).offset();

                    // var nodeOuterWidth = $("#chart-container  .node").first().outerWidth();
                    var nodeOuterWidth = $(node).outerWidth();
                    var leftLen = nodeOffset.left + nodeOuterWidth + 10;
                    if (leftLen + $(thisCard).width() > window.innerWidth) {
                        leftLen = leftLen - nodeOuterWidth - $(thisCard).width() - 20;
                    }

                    $(thisCard).css("left", leftLen);
                    $(thisCard).css("top", nodeOffset.top);

                    if ($(thisCard + ":hidden")) {
                        $(thisCard).css('visibility', 'visible');

                    } else {
                        $(thisCard).css('visibility', 'hidden');
                    }
                };

                //如果维度是事业部,编辑事业部名称,如果是自定义维度,则编辑其定义维度的值
                $(document).on('click', '.edit-dimension-value', function () {
                    if (!scope.hasEditPermission) {
                        return false;
                    }
                    //事业部ID
                    var demensionValueID = $(this).attr("data-dimension-value-id");
                    if (demensionValueID) {
                        console.log("demensionValueID: " + demensionValueID);
                        scope.EditOrg(demensionValueID);
                    }
                    return false;
                    //  stopPropagation();
                });

                //先判断directive中的uigrid是否渲染完成,如果完成那么就显示card 
                scope.$watch('isRenderCompleted', function (newValue, oldValue) {
                    if (newValue !== undefined && oldValue !== undefined) {
                        showCard(orgAreaIndustryPopup, row, 133, 286);
                    }

                });
                //点击卡片头显示机构general info
                scope.$watch('isRenderCompletedGeneralInfo', function (newValue, oldValue) {
                    if (newValue !== undefined && oldValue !== undefined && newValue) {
                        scope.showOrgCard($('#orgGeneralInfoPop'), row, 60, 0);

                        //$(document).one('click', function () {
                        //    orgAreaIndustryPopup.hide();
                        //    orgGeneralInfoPopup.hide();
                        //});
                    }

                });

                // 单击子公司个数,获取到pop对象,然后获取到当前点击的orgID
                // 绑定获取到机构ID,然后绑定给directive的OrgID,然后触发UIGRID数据获取和绑定
                // 如果数据获取成功且绑定, 那么isRenderCompleted=true
                $(document).on('click', '.item, .name-tpl', function (e) {

                    orgAreaIndustryPopup = $("#orgAreaIndustryPopup");
                    orgGeneralInfoPopup = $('#orgGeneralInfoPop');

                    row = $(this);
                    var orgId = row.find('#OrgID').text();
                    var oprType = row.find('#OrgID').attr('data-opr-type');
                    self = this;

                    if (oprType === 'enum.general') {

                        isGeneral = true;
                        scope.isRenderCompletedGeneralInfo = false;
                        scope.orgIdGeneralInfo = orgId;

                        oldGeneralOrgId = orgId;
                        oldGeneralOprType = oprType;

                    } else if (oprType === 'enum.orgAreaIndustry') {

                        isGeneral = false;
                        // 如果两个值不同,说明点击的是不同的机构,
                        // 需要给orgId赋值触发directive的watch更新uigrid的数据
                        if (orgId !== oldOrgId) {

                            //将当前的orgId复制给orgId
                            //从而触发directlive里面的watch操作,从而更新数据,
                            //更新数据成功之后,isRenderCompleted会变为true
                            //再次触发isRenderCompleted的watch操作显示卡片
                            scope.isRenderCompleted = false;
                            scope.orgId = orgId;  ////会触发directive的watch操作,从而更新数据
                        } else {
                            // 如果点击的是同一个子公司,需要直接显示

                            orgAreaIndustryPopup.toggle();

                            if (orgAreaIndustryPopup.is(':visible')) {
                                //如果当前是可视的那么再绑定一次
                                $(document).one('click', function () {
                                    orgAreaIndustryPopup.hide();
                                });
                            }
                        }

                        oldOrgId = orgId;
                        oldOprType = oprType;
                    }
                });

                $(document).on('click', '.node', function () {
                    $('.title').removeClass('node-active');
                    $(this).find('.title').toggleClass('node-active');
                });

                $(".close-card").on("click", function (e) {
                    $('.card').css('visibility', 'hidden');
                });

                $(".card").on("click", function (e) {
                    stopPropagation();
                });

                //点击不同的属性显示卡片
                element.on('click', '.show-card', function (e) {
                    //if (!scope.hasEditPermission) {
                    //    return false;
                    //}
                    var $this = $(this);
                    //维度,如用户数,覆盖区域,所属行业等
                    var attributeType = $this.attr("data-attribute-type");
                    //维度值的ID,相当于某个事业部ID,
                    var dimensionValueID = $this.attr("data-demension-value-id");
                    var dimensionValue = $this.attr('data-demension-value');
                    var attributeName = $this.attr('data-attribute-name');
                    var attributeID = $this.attr("data-attribute-id");


                    //如果是用户数
                    if (attributeType == constant.attributeType.User) {
                        scope.getUserStatisCard(dimensionValueID, dimensionValue, attributeName, attributeID);
                        showCard('.user-card', $this.closest('.node'));
                    }
                        //自定义维度,如产品线1,产品线2,通用,分公司,机构层级
                    else {
                        scope.getCommonCard(dimensionValueID, dimensionValue, attributeName, attributeID);
                        showCard('.common-card', $this.closest('.node'));
                    }
                    stopPropagation();
                });

            }//# end of link
        }
    }
]);
basicDataModule
    .controller('OrganizationViewInfrastructureController', ['$scope', '$log', 'SweetAlert', 'organizationStructureService', '$translate', 'businessUnitService', 'customerService', 'dimensionService', '$timeout', '$location', '$window', '$state',
        function ($scope, $log, SweetAlert, organizationStructureService, $translate, businessUnitService, customerService, dimensionService, $timeout, $location, $window, $state) {
            'use strict';

            var tabColor = ['orange', 'orange', 'orange', 'purple', 'pink', 'orange', 'purple', 'pink', 'orange'];

            var dimensionId = "#editDimensionModal";

            var dimensionFormValidator = null;

            var selected = null,
                previous = null;

            $scope.showOperateLogPop = function () {
                $scope.isShowLog = true;
            };

            var getDimensionStatics = function () {
                dimensionService.getDimensionStatics().success(function (data) {

                    // 个数一样,改了统计值
                    $scope.dimensionStatics = data;

                    if ($scope.tabItems && $scope.tabItems.length > 0) {

                        // 如果是修改维度值
                        updateTabItem();

                    } else {

                        // 如果是新增维度值
                        //$location.path(path);
                        initTabItem();
                    }
                });
            };

            var updateTabItem = function () {
                if ($scope.dimensionStatics && $scope.dimensionStatics.length > 0) {
                    for (var i = 0; i < $scope.dimensionStatics.length; i++) {
                        var row = $scope.dimensionStatics[i];

                        var existTab = _.find($scope.tabItems, function (tab) {
                            return tab.data.id === row.id;
                        });

                        if (existTab) {

                            existTab.data = row;
                            continue;
                        }
                        var item = {
                            id: i,
                            color: tabColor[row.dimensionType],
                            isEdit: true,
                            data: row,
                        };

                        // 变成灰色
                        if (row.dimensionType === constant.DimensionType.BusinessUnit) {
                            // 事业部
                            if ($scope.hasBuQueryPermission) {
                                item.iconCss = 'fa fa-bank fa-2x';
                                item.uiSref = '.organizationBusinessUnitView({dimensionID:"' + row.id + '"})';
                            }
                        } else if (row.dimensionType === constant.DimensionType.Area) {
                            // 区域
                            if ($scope.hasAreaQueryPermission) {
                                item.iconCss = 'material-icons';
                                item.iconText = 'place';
                                item.uiSref = '.organizationAreaView({dimensionID:"' + row.id + '"})';
                            }
                        }
                            //else if (row.dimensionType === constant.DimensionType.OrganizationStructure && $scope.hasOrgQueryPermission) {
                            //    //机构层级
                            //    item.iconCss = 'fa fa-building fa-2x';
                            //    item.uiSref = '.organizationSubsidiaryView({dimensionID:"' + row.id + '"})';
                            //}
                        else if (row.dimensionType === constant.DimensionType.OrgSubChildren) {
                            if ($scope.hasOrgQueryPermission) {
                                //机构 - 子分公司
                                item.iconCss = 'fa fa-building fa-2x';
                                item.uiSref = '.organizationSubsidiaryView({dimensionID:"' + row.id + '"})';
                            }
                        } //股权架构
                        else if (row.dimensionType === constant.DimensionType.Stock) {
                            if ($scope.hasOrgQueryPermission) {
                                //股权架构
                                item.iconCss = 'fa fa-building fa-2x';
                                item.uiSref = '.storeArchitectureView({dimensionID:"' + row.id + '"})';
                            }
                        } else {
                            if ($scope.hasDimensionQueryPermission) {
                                // 自定义维度和其他
                                item.iconCss = 'fa fa-cube fa-2x';
                                item.uiSref = '.organizationBusinessUnitView({dimensionID:"' + row.id + '"})';
                            }
                        }
                        if (item.uiSref) {

                            $scope.tabItems.push(item);
                        }
                    }
                }

            };

            var initTabItem = function () {
                var tabItems = [];
                if ($scope.dimensionStatics && $scope.dimensionStatics.length > 0) {
                    for (var i = 0; i < $scope.dimensionStatics.length; i++) {
                        var row = $scope.dimensionStatics[i];
                        var item = {
                            id: i,
                            color: tabColor[row.dimensionType],
                            isEdit: true,
                            canEdit: false,
                            data: row,
                        };

                        // 变成灰色
                        if (row.dimensionType === constant.DimensionType.BusinessUnit) {
                            // 事业部

                            item.iconCss = 'fa fa-bank fa-2x';
                            item.uiSref = '.organizationBusinessUnitView({dimensionID:"' + row.id + '"})';


                            item.canEdit = $scope.hasBuEditPermission;
                        } else if (row.dimensionType === constant.DimensionType.Area) {
                            // 区域

                            item.iconCss = 'material-icons';
                            item.iconText = 'place';
                            item.uiSref = '.organizationAreaView({dimensionID:"' + row.id + '"})';


                            item.canEdit = $scope.hasAreaEditPermission;
                        }
                            //else if (row.dimensionType === constant.DimensionType.OrganizationStructure && $scope.hasOrgQueryPermission) {
                            //    //机构层级
                            //    item.iconCss = 'fa fa-building fa-2x';
                            //    item.uiSref = '.organizationSubsidiaryView({dimensionID:"' + row.id + '"})';
                            //}
                        else if (row.dimensionType === constant.DimensionType.OrgSubChildren) {

                            //机构 - 子分公司
                            item.iconCss = 'fa fa-building fa-2x';
                            item.uiSref = '.organizationSubsidiaryView({dimensionID:"' + row.id + '"})';

                            item.canEdit = $scope.hasOrgEditPermission;
                        } else if (row.dimensionType === constant.DimensionType.Stock) {
                            if ($scope.hasOrgQueryPermission) {
                                //股权架构
                                item.iconCss = 'fa fa-building fa-2x';
                                item.uiSref = '.storeArchitectureView({dimensionID:"' + row.id + '"})';
                            }
                        } else {
                            // 自定义维度和其他
                            item.iconCss = 'fa fa-cube fa-2x';
                            item.uiSref = '.organizationBusinessUnitView({dimensionID:"' + row.id + '"})';

                            item.canEdit = $scope.hasDimensionEditPermission;
                        }
                        if (item.uiSref) {
                            tabItems.push(item);
                        }

                    }
                }

                var item = {
                    id: $scope.dimensionStatics.length,
                    color: 'gray-style',
                    iconCss: 'fa fa-plus fa-2x',
                    uiSref: '',
                    isEdit: false,
                    data: {
                        dimensionValueCount: '',
                        name: '添加维度',
                        isActive: true,
                        isMandatory: false,
                    }
                };

                item.canEdit = $scope.hasDimensionEditPermission;

                tabItems.push(item);

                $scope.tabItems = tabItems;
            };

            var watchSelectedIndex = function () {
                $scope.$watch('selectedIndex', function (current, old) {
                    previous = selected;
                    if (!$scope.tabItems) {
                        return;
                    }

                    if (current) {
                        selected = $scope.tabItems[current];
                    }

                    if (old + 1 && (old != current) && previous) $log.debug('Goodbye ' + previous.data.name + '!');
                    if (current + 1 && selected) $log.debug('Hello ' + selected.data.name + '!');
                });
            };

            $scope.$on("hasDimensionUpdated", function (event, data) {
                // console.log('DimensionUpdate' + JSON.stringify(data));
                // 强制刷新机构部分

                console.log('before:selectedIndex' + $scope.selectedIndex);
                var oldselectedIndex = $scope.selectedIndex;
                $scope.selectedIndex = oldselectedIndex;
                getDimensionStatics();
                $scope.selectedIndex = oldselectedIndex;
            });

            $scope.$on("hasOrgUpdated", function (event, data) {
                // console.log('DimensionUpdate' + JSON.stringify(data));
                // 强制刷新机构部分
                getDimensionStatics();
            });


            $scope.getWidth = function () {
                var latitudeGroupWidth = $('.latitude-group').css('width');
                var width = 800;
                if (latitudeGroupWidth) {
                    width = parseInt(latitudeGroupWidth) - 20;

                    var latitudeWidth = parseInt((width - 124) / 4);
                    if (latitudeWidth > 200) {
                        $('.latitude').css('width', latitudeWidth + 'px');
                        // $('.md-tab').css('width', (latitudeWidth + 20) + 'px');
                    }
                }

                return { width: width + 'px' };
            };

            //添加维度,使用模态框实现编辑入口tabItems
            $scope.newDimension = function (data, $event) {

                if (!data.canEdit) {
                    return;
                }

                $scope.isEdit = false;
                $scope.editingObject = {
                    dimensionValueCount: 0,
                    name: '',
                    isActive: true,
                    isMandatory: false,
                };

                $scope.editingObject.name = '';
                resetDimensionField();
                $(dimensionId).modal('show');
                $event.stopPropagation();
            };

            $scope.editDimension = function (data, $event) {
                if (!data.canEdit) {
                    return;
                }

                $scope.isEdit = true;
                $scope.editingObject = angular.copy(data.data);
                resetDimensionField();
                $(dimensionId).modal('show');
                $event.stopPropagation();
            };

            //清空当前编辑字段值
            var resetDimensionField = function () {
                var elms = $(dimensionId).find("form:first div[data-for]");
                elms.html("");
                elms.attr("class", "validate-success");
            };

            //保存当前正在编辑数据行,经过界面初步校验后才会进入本功能
            $scope.saveDimension = function () {
                if ($scope.editingObject == null) {
                    showError("BusinessUnitNoSelected");
                    return;
                }

                if (!($(dimensionId).find("form").valid())) {

                    return;
                }

                var saveDimensionCallBack = function (data) {
                    if (data && data.result) {

                        SweetAlert.success($translate.instant('SaveSuccess'));
                        $(dimensionId).modal('hide');

                        if (!$scope.isEdit) {
                            // 如果是添加

                            var secondLast = $scope.tabItems.length - 1;
                            var row = data.data;
                            var item = {
                                id: $scope.tabItems.length,
                                color: tabColor[row.dimensionType],
                                isEdit: true,
                                data: row,

                            };

                            if ($scope.hasDimensionQueryPermission && row.isActive) {
                                item.iconCss = 'fa fa-cube fa-2x';
                                item.uiSref = '.organizationBusinessUnitView({dimensionID:"' + row.id + '"})';
                            }

                            $scope.tabItems.splice(secondLast, 0, item);

                            if (item.uiSref) {
                                $state.go('organizationView.organizationBusinessUnitView', { dimensionID: data.data.id });
                                return;
                            }
                        }

                        //$window.location.reload();
                        getDimensionStatics();

                        //注册一个向下传播的事件,eventName:'FromSelf', data:oneObject
                        $scope.$broadcast("DimensionUpdate", { isupdated: true });

                    } else {
                        swal($translate.instant('SaveFail'), $translate.instant(data.resultMsg), 'warning');
                    }
                };

                if (!$scope.isEdit) {
                    dimensionService.addDimension($scope.editingObject).success(saveDimensionCallBack);
                } else {
                    dimensionService.updateDimension($scope.editingObject).success(saveDimensionCallBack);
                }
            };

            var initValidateDimension = function () {
                $.validator.addMethod("dimensionNameRepeated", function (value, element, param) {
                    if ($scope.tabItems && $scope.tabItems.length > 0) {
                        var objects = $.grep($scope.tabItems, function (n, i) {
                            return $scope.editingObject.id != n.data.id && $.trim(n.data.name) == $.trim(value);
                        });

                        return objects.length < 1;
                    }

                    return true;

                });

                dimensionFormValidator = $(dimensionId).find("form").validate({
                    debug: true,

                    rules: {
                        name: {
                            required: true,
                            minlength: 2,
                            maxlength: 20,
                            dimensionNameRepeated: true
                        },
                        isActive: {
                            required: "input[name='isActive']:checked"
                        }
                    },
                    messages: {
                        name: {
                            required: $translate.instant('DimensionNameRequired'),
                            minlength: $translate.instant('DimensionNameRequired'),
                            maxlength: $translate.instant('DimensionNameOutOfLength'),
                            dimensionNameRepeated: $translate.instant('DimensionNameRepeated')
                        },
                        isActive: $translate.instant('DimensionStatusUnsureness')
                    },
                    errorPlacement: function (error, element) {
                        var elm = $(element).parents("form:first");
                        elm = elm.find("div[data-for='" + element.attr("name") + "']");
                        elm.html(error);
                        elm.attr("class", "validate-fail");
                    }
                });

            };

            var initParams = function () {
                // 设置默认tab选中项
                var url = $location.absUrl();
                // 只有第一次打开这个页面才会进来
                // console.log(url);
                if (url.indexOf('organizationAreaView') > -1) {
                    $scope.selectedIndex = 1;
                } else if (url.indexOf('organizationSubsidiaryView') > -1) {
                    $scope.selectedIndex = 2;
                } else if (url.indexOf('organizationSubsidiaryView') > -1) {
                    $scope.selectedIndex = 3;
                } else {


                    //$state.go('organizationView.organizationBusinessUnitView', { dimensionID: 'a971fe7c-079d-4722-820c-fe367a80d4cc' });
                    $scope.selectedIndex = 0;
                }
            };


            var checkUserPermission = function () {

                var list = [];

                $scope.hasDimensionQueryPermission = false;
                $scope.hasDimensionEditPermission = false;

                $scope.hasOrgQueryPermission = false;
                $scope.hasOrgEditPermission = false;

                $scope.hasAreaQueryPermission = false;
                $scope.hasAreaEditPermission = false;

                $scope.hasBuQueryPermission = false;
                $scope.hasBuEditPermission = false;

                var dimensionTemp = constant.adminPermission.basicData.selfDimension;
                list.push(dimensionTemp.queryCode);
                list.push(dimensionTemp.editCode);

                var orgTemp = constant.adminPermission.infrastructure.organizationManage;
                list.push(orgTemp.queryCode);
                list.push(orgTemp.editCode);

                var areaTemp = constant.adminPermission.basicData.areaManage;
                list.push(areaTemp.queryCode);
                list.push(areaTemp.editCode);

                var buTemp = constant.adminPermission.basicData.businessUnit;
                list.push(buTemp.queryCode);
                list.push(buTemp.editCode);

                $scope.$root.checkUserPermissionList(list).success(function (data) {
                    // console.log('data: ' + data);
                    $scope.hasDimensionQueryPermission = data[dimensionTemp.queryCode];
                    $scope.hasDimensionEditPermission = data[dimensionTemp.editCode];

                    $scope.hasOrgQueryPermission = data[orgTemp.queryCode];
                    $scope.hasOrgEditPermission = data[orgTemp.editCode];

                    $scope.hasAreaQueryPermission = data[areaTemp.queryCode];
                    $scope.hasAreaEditPermission = data[areaTemp.editCode];

                    $scope.hasBuQueryPermission = data[buTemp.queryCode];
                    $scope.hasBuEditPermission = data[buTemp.editCode];

                    if ($scope.hasOrgQueryPermission) {
                        getDimensionStatics();
                    }
                });
            };

            (function initialize() {
                $log.debug('OrganizationViewInfrastructureController.ctor()...');

                initParams();
                initValidateDimension();
                watchSelectedIndex();

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

infrastructureModule.directive('organizationViewInfrastructure', ['$log',
    function ($log) {
        'use strict';
        $log.debug('organizationViewInfrastructure.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/organizationViewInfrastructure/organization-view-infrastructure.html' + '?_=' + Math.random(),
            replace: true,
            scope: {
                state: '='
            },
            controller: 'OrganizationViewInfrastructureController',
            link: function (scope, element) {
                //$log.info(scope.state);
            }
        };
    }
]);
infrastructureModule
.controller('ProjectManageController', ['$scope', '$log', '$timeout', '$translate', 'projectService', 'userService', 'uiGridConstants', 'SweetAlert', 'orgService', 'roleService', 'templateGroupService',
    function ($scope, $log, $timeout, $translate, projectService, userService, uiGridConstants, SweetAlert, orgService, roleService, templateGroupService) {
        'use strict';

        var testModuleList = [{ id: '1', name: '2016' }, { id: '1', name: '2017' }];


        var loadProjectIndustryList = function () {
            orgService.getProjectIndustrys().success(function (data) {

                $scope.projectIndustryList = data;
            });
        };

        var loadAllTemplate = function () {
            templateGroupService.getall().success(function (data) {
                $scope.templateGroupList = data;
            });
        };

        var getTemplate = function (serviceTypeId) {

            return _.filter($scope.templateGroupList, function (num) { return num.serviceTypeID === serviceTypeId });
        };

        var initServiceList = function () {
            projectService.getServiceList().success(function (serviceListData) {
                $scope.serviceList = serviceListData;
                // $timeout(function () {
                //     initMultipleSelect();
                // }, 10);

                $scope.projectModuleList = [];
                $scope.newProjectModuleRow();
            });
        };

        $scope.newProjectModuleRow = function () {

            if ($scope.serviceList.length <= $scope.projectModuleList.length) {
                return;
            }

            var serviceList = copyArray($scope.serviceList);

            var row = {
                serviceList: serviceList,
                moduleList: [],
                selectedService: null,
                selectedModule: null
            };

            $scope.projectModuleList.push(row);
        };

        var setProjectModuleRowList = function (projectData) {
            $scope.projectModuleList = [];
            if ($scope.serviceList.length <= $scope.projectModuleList.length) {
                return;
            }

            if (projectData.serviceTypeTemplateGroupList && projectData.serviceTypeTemplateGroupList.length > 0) {
                projectData.serviceTypeTemplateGroupList.forEach(function (row) {
                    var serviceList = copyArray($scope.serviceList);

                    var moduleList = getTemplate(row.serviceTypeID);

                    var row = {
                        projectServiceTypeID: row.projectServiceTypeID,
                        serviceList: serviceList,
                        moduleList: moduleList,
                        selectedService: _.find(serviceList, function (num) { return num.id === row.serviceTypeID }),
                        selectedModule: _.find(moduleList, function (num) { return num.id === row.templateGroupID })
                    };

                    $scope.projectModuleList.push(row);
                });
            }
        };

        $scope.changeProjectService = function (projectModule) {

            var moduleList = getTemplate(projectModule.selectedService.id);

            projectModule.moduleList = moduleList;
            if (moduleList && moduleList.length > 0) {
                projectModule.selectedModule = moduleList[0];
            } else {
                projectModule.selectedModule = {};
            }
        };

        var copyArray = function (data) {
            var ret = [];
            data.forEach(function (row) {

                ret.push(row);
            });

            return ret;
        };

        $scope.deleteProjectModule = function (model) {
            if (model) {
                $scope.projectModuleList.splice(jQuery.inArray(model, $scope.projectModuleList), 1);
            };
        };

        $scope.getGridHeight = function () {
            return { height: ($(".system-manage #projectDataList").height() - $(".system-manage #projectDataList .project-manage-menu").height()) + "px" };
        }

        var initProjectList = function (orgID, serviceID, projectYear) {

            if (!orgID) {
                orgID = '';
            }

            if (!serviceID) {
                serviceID = '';
            }

            if (!projectYear) {
                projectYear = null;
            }

            projectService.getProjectList(orgID, serviceID, projectYear).success(function (projectListData) {

                if ($scope.projectId && $scope.serviceType) {
                    $log.debug('projectID:' + $scope.projectId + '; serviceType:' + $scope.serviceType);

                    projectListData = _.where(projectListData, {
                        id: $scope.projectId.toLowerCase(), serviceTypeID: parseInt($scope.serviceType)
                    });


                }



                //set index number, ui-grid have no $$index
                var projectIndex = 1;
                var curProject = null;
                projectListData.forEach(function (p) {
                    if (!curProject) {
                        curProject = p;
                        p.index = projectIndex++;
                        p.nameDisplay = p.name;
                        p.organizationNameDisplay = p.organizationName;
                        p.yearDisplay = p.year;
                        p.industryNameDisplay = p.industryName;
                    }
                    else {
                        if (p.id == curProject.id) {
                            p.nameDisplay = '';
                            p.organizationNameDisplay = '';
                            p.yearDisplay = '';
                            p.industryNameDisplay = '';
                        }
                        else {
                            curProject = p;
                            p.index = projectIndex++;
                            p.nameDisplay = p.name;
                            p.organizationNameDisplay = p.organizationName;
                            p.yearDisplay = p.year;
                            p.industryNameDisplay = p.industryName;
                        }
                    }

                });

                $scope.gridOptions.data = projectListData;

                $scope.gridOptions.noData = projectListData.length === 0;
            });
        };

        var initProjectYear = function () {
            var arrYear = '[';
            var curYear = new Date().getFullYear();
            for (var beginYear = curYear - 4; beginYear <= curYear + 4; beginYear++) {
                arrYear += '{"year"' + ':' + beginYear + '},';
            }
            arrYear = arrYear.substring(0, arrYear.length - 1) + ']';
            $scope.projectYearList = JSON.parse(arrYear);
        };


        var newProject = function () {
            $scope.isAdd = true;
            $scope.editProjectModel = {};
            $scope.editProjectModel.serviceSelectedList = [];
            $scope.editProjectModel.serviceSelectedList = [];
            $scope.projectModuleList = [];
            $scope.newProjectModuleRow();
            $scope.selectedIndustry = null;
            $scope.editProjectModel.selectedYear = null;
            $scope.editProjectModel.componentSelectedOrg = null;
            resetErrorStatus();
            $("#selectedOrgName-error").hide();
            $('#addProjectPop').modal('show');
        };

        //save project
        var saveProject = function () {
            if (!($('#projectForm').valid())) {
                return;
            }

            if (!$scope.editProjectModel) {
                return;
            }

            if ($scope.projectModuleList) {
                $scope.editProjectModel.serviceTypeTemplateGroupList = [];

                var iserror = false;
                $scope.projectModuleList.forEach(function (row) {
                    if (row.selectedService && row.selectedService.id && row.selectedModule && row.selectedModule.id && !iserror) {

                        // 先判断是否有一样的了
                        if (_.find($scope.editProjectModel.serviceTypeTemplateGroupList, function (num) { return num.serviceTypeID === row.selectedService.id && num.templateGroupID === row.selectedModule.id })) {

                            if (!iserror) {
                                iserror = true;
                                SweetAlert.warning(row.selectedService.name + '-' + row.selectedModule.name + $translate.instant('HasSelected'));
                            }

                        } else {
                            var serviceTypeTemplateGroup = {};
                            serviceTypeTemplateGroup.serviceTypeID = row.selectedService.id;
                            serviceTypeTemplateGroup.templateGroupID = row.selectedModule.id;
                            if (row.projectServiceTypeID) {
                                serviceTypeTemplateGroup.projectServiceTypeID = row.projectServiceTypeID;
                            }

                            serviceTypeTemplateGroup.serviceTypeName = row.selectedService.name;
                            serviceTypeTemplateGroup.templateGroupName = row.selectedModule.name;
                            $scope.editProjectModel.serviceTypeTemplateGroupList.push(serviceTypeTemplateGroup);
                        }
                    } else {
                        // 服务和模型都必须选择
                        // 这里可以提示
                        if (!iserror) {
                            iserror = true;
                            SweetAlert.warning($translate.instant('SelectBothServiceAndTemplate'));
                        }
                    }
                });

                if (iserror) {
                    return;
                }
            }

            if ($scope.selectedIndustry && $scope.selectedIndustry.id) {
                $scope.editProjectModel.industryID = $scope.selectedIndustry.id;
            }

            if ($scope.isAdd) {
                $scope.editProjectModel.year = $scope.editProjectModel.selectedYear.year;
                $scope.editProjectModel.OrganizationID = $scope.editProjectModel.organizationID;
                projectService.addProject($scope.editProjectModel).success(function (data) {
                    if (data && !data.result) {
                        swal($translate.instant('SaveFail'), $translate.instant(data.resultMsg), 'warning');
                        return;
                    }

                    $log.debug('add success' + projectID);
                    SweetAlert.success($translate.instant('SaveSuccess'));
                    $scope.editProjectModel = {};
                    initProjectList();
                });
            } else {

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

                              projectService.updateProject($scope.editProjectModel).success(function (data) {
                                  if (data && !data.result) {
                                      swal($translate.instant('SaveFail'), $translate.instant(data.resultMsg), 'warning');
                                      return;
                                  }

                                  SweetAlert.swal($translate.instant('Confirm') + $translate.instant('Change'), $translate.instant("SaveSuccess"), "success");
                                  $scope.editProjectModel = {};
                                  initProjectList();
                              });
                          }
                      });
                } else {

                    projectService.updateProject($scope.editProjectModel).success(function (data) {
                        if (data && !data.result) {
                            swal($translate.instant('SaveFail'), $translate.instant(data.resultMsg), 'warning');
                            return;
                        }

                        SweetAlert.success($translate.instant('SaveSuccess'));
                        $scope.editProjectModel = {};
                        initProjectList();
                    });

                }
            }
            $('#addProjectPop').modal('hide');
        };

        var ischangeProjectService = function () {

            var ischange = false;
            if ($scope.editProjectModel && $scope.editProjectModel.serviceTypeTemplateGroupList && $scope.currentProjectData && $scope.currentProjectData.serviceTypeTemplateGroupList) {

                $scope.currentProjectData.serviceTypeTemplateGroupList.forEach(function (row) {

                    var updateModel = _.find($scope.editProjectModel.serviceTypeTemplateGroupList, function (num) { return num.id === row.id });
                    if (!updateModel) {
                        ischange = true;
                    }

                    if (updateModel.serviceTypeID != row.serviceTypeID || updateModel.templateGroupID !== row.templateGroupID) {
                        ischange = true;
                    }
                });
            }

            return ischange;
        };

        //load project
        var loadProject = function (projectID) {
            $scope.isAdd = false;
            projectService.getSingleProject(projectID).success(function (projectData) {
                //set ServiceBelong
                $scope.editProjectModel = projectData;

                var first = _.find($scope.projectIndustryList, function (num) { return num.id + '' === $scope.editProjectModel.industryID });
                if (first) {
                    $scope.selectedIndustry = first;
                }

                $scope.currentProjectData = projectData;

                setProjectModuleRowList(projectData);

                //set ProjectYear
                $scope.editProjectModel.selectedYear = _.find($scope.projectYearList, function (num) { return num.year === projectData.year });

                // $scope.selectedIndustry = _.find($scope.projectIndustryList, function (num) { return num.id + '' === projectData.industryID });
            });

            resetErrorStatus();
            $('#addProjectPop').modal('show');
        };

        //Delete project info
        var deleteProject = function () {
            projectService.deleteProject($scope.toDeleteModel).success(function () {
                $('#deleteConfirmPop').modal('hide');
                //Reload project list
                initProjectList();
                $log.debug('delete success!');

            });
        };

        //Deleted projects
        var deleteProjects = function () {
            projectService.deleteProjects($scope.gridApi.selection.getSelectedRows()).success(function () {
                $('#deleteConfirmPop').modal('hide');
                initProjectList();
                $log.debug('delete projects success!');
            });
        };

        //delete project confirm
        var deleteProjectConfirm = function (project) {
            $scope.isMore = false;
            $scope.toDeleteModel = project;
            $scope.toDeleteName = project.projectName;
            $scope.toDeleteCode = project.projectCode;
            $('#deleteConfirmPop').modal('show');
        };

        //delete projects confirm
        var deleteProjectsConfirm = function () {
            if ($scope.gridApi.selection.getSelectedCount() > 0) {
                $scope.isMore = true;
                $('#deleteConfirmPop').modal('show');
            }
            else {
                $log.debug('plese select projects first!');
            }

        };


        var reloadProjectData = function () {
            var orgId = $scope.queryOrgId;
            var serviceId = $scope.queryService;
            var projectId = $scope.queryProjectYear;

            initProjectList(orgId, serviceId, projectId);
        };

        var toggleSub = function (roleNode) {
            if (roleNode.isChecked) {
                $scope.checkedRolesSet[roleNode.roleID] = roleNode;
            }
            else {
                delete $scope.checkedRolesSet[roleNode.roleID];
            }

            $scope.set = _.keys($scope.checkedMenusSet);
            if (!roleNode.subNodeList) {
                return;
            }
            roleNode.subNodeList.forEach(function (d) {
                d.isChecked = roleNode.isChecked;
                if (roleNode.isChecked) {
                    $scope.checkedRolesSet[d.roleID] = d;
                }
                else {
                    delete $scope.checkedRolesSet[d.roleID];
                }
            });

            $scope.set = _.keys($scope.checkedRolesSet);
        };

        var clearRoleIsChecked = function () {

            if ($scope.roleNodeList && $scope.roleNodeList.length > 0) {

                for (var i = $scope.roleNodeList.length - 1; i >= 0; i--) {
                    $scope.roleNodeList[i].isChecked = false;
                    toggleSub($scope.roleNodeList[i]);
                }
            }
        };

        var roleTreeLoad = function () {
            userService.getRoleDisplayList().success(function (roleDisplayTypeData) {

                if (roleDisplayTypeData && roleDisplayTypeData.length > 0) {
                    var group = _.groupBy(roleDisplayTypeData, function (n) { return n.roleTypeId; });

                    var roleNode = [];
                    var roleTypeIdList = [];
                    for (var i = roleDisplayTypeData.length - 1; i >= 0; i--) {
                        roleTypeIdList.push(roleDisplayTypeData[i].roleTypeId);
                    }

                    roleTypeIdList = _.uniq(roleTypeIdList);
                    for (var m = roleTypeIdList.length - 1; m >= 0; m--) {
                        var subList = group[roleTypeIdList[m]];

                        if (subList) {
                            var model = {
                                name: subList[0].roleTypeName,
                                roleTypeName: subList[0].roleTypeName,
                                roleTypeId: subList[0].roleTypeId,
                                description: '',
                                roleID: subList[0].roleTypeId,
                                subNodeList: subList
                            };

                            roleNode.push(model);
                        }
                    }

                    $scope.roleNodeList = roleNode;
                } else {
                    $scope.roleNodeList = [];
                }

            });
        };


        var assignUser = function (projectData) {
            $scope.assignProject = projectData;
            resetSelectedUser($scope.userList);
            $scope.selectUserSpan = {};

            userService.getUserListByProject(projectData.id, projectData.serviceTypeID).success(function (userData) {
                $scope.userList = userData;
                checkUser($scope.userList[0].subUsers[0]);

                $scope.assignUserSet = getUserSet(userData);
                $('#assignUserPop').modal('show');
            });
            roleService.getroletree(projectData.serviceTypeID).success(function (data) {
                $scope.roleTreeData = data;

            });
        };


        var getUserChecked = function (user, chk) {
            if (chk === true) {
                $scope.selectUserIDs += user.userID + ',';
            }
            else {
                $scope.selectUserIDs = $scope.selectUserIDs.replace(',' + user.userID + ',', ',');
            }
            $log.debug($scope.selectUserIDs);
        };

        var findRoleByRoleID = function (roleList, roleId) {

            var ret = _.find(roleList, function (num) {
                return num.roleID + '' === roleId;
            });

            return ret;
        };

        var findAllCheckedList = function (roleList) {
            var checkedList = _.filter(roleList, function (num) {
                return num.isChecked;
            });

            return checkedList;
        };

        var selectNode = function (roleNode) {
            $scope.selectedRole = roleNode;
        };

        var toggle = function (scope) {
            scope.toggle();
        };

        var initMultipleSelect = function () {
            var multiOption = {
                includeSelectAllOption: true,
                selectAllText: $translate.instant('allService'),
                nonSelectedText: $translate.instant('nonSelectedService'),
                allSelectedText: $translate.instant('allService')
            };

            $('#serviceTypeList').show().multiselect(multiOption);
        };

        var search = function () {
            $scope.gridApi.grid.refresh();
        };


        //Initial user list
        var initUser = function () {
            userService.getUserTreeList().success(function (userData) {
                $scope.userList = userData;
                checkUser($scope.userList[0].subUsers[0]);

                $scope.assignUserSet = getUserSet(userData);
            })
        };

        var getUserSet = function (userData) {
            var userSet = [];
            userData.forEach(function (row) {
                row.isSelected = row.isChecked;
                userSet.push(row);

                if (row.subUsers && row.subUsers.length > 0) {
                    var subUserSet = getUserSet(row.subUsers);
                    userSet = _.union(userSet, subUserSet);
                }
            });

            return userSet;
        };

        //select tree node event
        var checkUser = function (user) {

            var isSelected = !user.isSelected;

            // 设置子节点
            setUserRecursion(user, isSelected);

            // 设置父级节点状态
            setParentRecursion(user, isSelected);


        };

        var setUserRoleSetList = function (user) {

            if (!$scope.roleTreeData || $scope.roleTreeData.length === 0) {
                return;
            }

            // 都要设置成不选择
            $scope.roleTreeData[0].isChecked = false;
            $scope.roleTreeData[0].subRoles.forEach(function (row) {
                row.isChecked = false;
            });

            if (!user || !user.id) {
                return;
            }

            userService.getUserRoleSetList(user.id, $scope.assignProject.serviceTypeID, $scope.assignProject.id).success(function (data) {
                if (data && data.length) {
                    data.forEach(function (row) {

                        var filter = _.filter($scope.roleTreeData[0].subRoles, function (num) { return num.id === row.roleID });
                        if (filter && filter.length > 0) {
                            filter.forEach(function (row2) {
                                row2.isChecked = true;
                            });


                        }
                    });

                    var filter = _.filter($scope.roleTreeData[0].subRoles, function (num) { return num.isChecked });
                    if (filter.length === $scope.roleTreeData[0].subRoles.length) {
                        $scope.roleTreeData[0].isChecked = true;
                    }
                }
            });
        };

        var setUserRecursion = function (user, isSelected) {

            user.isSelected = isSelected;
            if (user.subUsers && user.subUsers.length > 0) {
                user.subUsers.forEach(function (row) {
                    setUserRecursion(row, isSelected);
                });
            }
        };

        var setParentRecursion = function (user, isSelected) {
            if (user.parent && user.parent.subUsers && user.parent.subUsers.length > 0) {
                var selectSubUserList = _.filter(user.parent.subUsers, function (num) { return num.isSelected === isSelected });

                if (user.parent.subUsers && selectSubUserList && user.parent.subUsers.length === selectSubUserList.length) {
                    user.parent.isSelected = isSelected;
                } else {
                    user.parent.isSelected = false;
                }

                if (user.parent.parent) {
                    setParentRecursion(user.parent, isSelected);
                }
            }
        };


        var resetSelectedUser = function (userList, parent) {
            userList.forEach(function (row) {
                row.isSelected = false;
                if (parent && !row.parent) {
                    row.parent = parent;
                }

                if (row.subUsers && row.subUsers.length > 0) {

                    resetSelectedUser(row.subUsers, row);
                }
            });
        };

        $scope.toggleRoleSub = function (role) {

            if (role.isChecked) {
                role.isChecked = false;
            } else {
                role.isChecked = true;
            }

            // 如果是父节点,同步设置子节点
            if (role.id === constant.guid.empty) {

                if (role.subRoles && role.subRoles.length > 0) {
                    role.subRoles.forEach(function (row) {
                        row.isChecked = role.isChecked;
                    });
                }
            } else {
                var selectedRoleList = _.filter($scope.roleTreeData[0].subRoles, function (num) { return num.isChecked });
                if (selectedRoleList && selectedRoleList.length === $scope.roleTreeData[0].subRoles.length) {
                    $scope.roleTreeData[0].isChecked = role.isChecked;
                } else {
                    $scope.roleTreeData[0].isChecked = false;
                }
            }
        };

        $scope.setProjectUserRole = function () {

            if (!$scope.roleTreeData || $scope.roleTreeData.length === 0) {
                $log.debug('no role list');
                return;
            }

            // 保存用户分配信息
            var selectedUser = _.filter($scope.assignUserSet, function (num) { return (!num.subUsers || num.subUsers.length === 0) && num.id !== $scope.selectUserSpan.id });

            if (!selectedUser || selectedUser.length === 0) {
                $log.debug('please select user....');
                return;
            }

            var inpara = [];

            // 选中checkbox 设置默认权限
            selectedUser.forEach(function (userInfo) {
                var para = {};
                para.UserID = userInfo.id;
                para.userName = userInfo.userName;
                para.projectID = $scope.assignProject.id;
                para.projectName = $scope.assignProject.name;
                para.serviceTypeID = $scope.assignProject.serviceTypeID;
                para.serviceTypeName = $scope.assignProject.serviceTypeName;
                para.isActive = userInfo.isSelected;
                inpara.push(para);
            });

            // 设置单选的用户的权限
            if ($scope.selectUserSpan && $scope.selectUserSpan.id) {
                $scope.roleTreeData[0].subRoles.forEach(function (roleInfo) {
                    var para = {};
                    para.UserID = $scope.selectUserSpan.id;
                    para.userName = $scope.selectUserSpan.userName;
                    para.roleID = roleInfo.id;
                    para.roleName = roleInfo.name;
                    para.projectID = $scope.assignProject.id;
                    para.projectName = $scope.assignProject.name;
                    para.serviceTypeID = $scope.assignProject.serviceTypeID;
                    para.serviceTypeName = $scope.assignProject.serviceTypeName;
                    para.isActive = roleInfo.isChecked;
                    inpara.push(para);
                });
            }

            userService.setProjectUserRole(inpara).success(function (data) {
                if (data && data.result) {

                    SweetAlert.success($translate.instant('SaveSuccess'));
                    $log.debug('setProjectUserRole success...');
                    $('#assignUserPop').modal('hide');
                } else {
                    swal($translate.instant('SaveFail'), $translate.instant(data.resultMsg), 'warning');
                }
            });
        };

        $scope.selectUserSpanClick = function (user) {
            if ($scope.selectUserSpan && $scope.selectUserSpan.id && $scope.selectUserSpan.id === user.id) {
                $scope.selectUserSpan = {};

            } else {
                $scope.selectUserSpan = user;
            }

            setUserRoleSetList($scope.selectUserSpan);
        };

        // form validate
        var resetErrorStatus = function () {
            var currentForm = $('#projectForm');
            currentForm.find('.has-error').removeClass('has-error');

            var settingForm = $('.project-modal-table')[0];

            $(settingForm).find('.has-error').removeClass('has-error');

            validator.resetForm();
        };

        var resources = {
            nameRequired: $translate.instant('ProjectNameRequired'),
            codeRequired: $translate.instant('ProjectCodeRequired'),
            selectOrganizationRequired: $translate.instant('SelectOrganizationRequired'),
            selectIndustryRequired: $translate.instant('SelectIndustryRequired'),
            selectedYearRequired: $translate.instant('SelectedYearRequired'),
            selectedServiceRequired: $translate.instant('SelectedServiceRequired'),
            selectedModuleRequired: $translate.instant('SelectedModuleRequired'),
        };


        var validator = $("#projectForm").validate({
            errorClass: "has-error",
            ignore: "",
            rules: {
                name: {
                    required: true
                },
                code: {
                    required: true
                },
                //orgName: {
                //    required: true
                //},
                selectedIndustry: {
                    required: true
                },
                selectedYear: {
                    required: true
                },
                selectedService: {
                    required: true
                },
                selectedModule: {
                    required: true
                },
                selectedOrgName: {
                    required: true,
                }
            },
            messages: {
                name: {
                    required: resources.nameRequired
                },
                code: {
                    required: resources.codeRequired
                },
                //orgName: {
                //    required: resources.selectOrganizationRequired
                //},
                selectedIndustry: {
                    required: resources.selectIndustryRequired
                },
                selectedYear: {
                    required: resources.selectedYearRequired
                },
                selectedService: {
                    required: resources.selectedServiceRequired
                },
                selectedModule: {
                    required: resources.selectedModuleRequired
                },
                selectedOrgName: {
                    required: resources.selectOrganizationRequired
                }
            },
            errorPlacement: function (error, element) {
                setErrorStyle(error, element);
            }
        });

        var setErrorStyle = function (error, element) {
            if (element.hasClass('has-error')) {
                element.parent().addClass('has-error');
                error.insertAfter(element);
                error.addClass('label');
                // error.addClass('label-danger');
            }
        };


        $scope.$watch('editProjectModel.organizationID', function (newValue, oldValue) {

            if (newValue !== oldValue && $scope.editProjectModel.componentSelectedOrg) {
                $log.debug('newValue:' + newValue + ',oldValue:' + oldValue);

                $scope.editProjectModel.industryID = $scope.editProjectModel.componentSelectedOrg.industryID;
                var first = _.find($scope.projectIndustryList, function (num) { return num.id === $scope.editProjectModel.industryID });
                if (first) {
                    $scope.selectedIndustry = first;
                }
            }

        });

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

        (function initialize() {
            $log.debug('projectManageController.ctor()...');
            //scope model
            $scope.title = '项目管理';
            $scope.serviceList = [];
            $scope.queryService = '';
            $scope.projectYearList = [];
            $scope.projectIndustryList = [];
            $scope.queryProjectYear = '';
            $scope.projectList = [];
            $scope.isAdd = false;
            $scope.editProjectModel = {};

            $scope.chk = false;
            $scope.userList = [];
            $scope.selectUserIDs = ',';

            $scope.checkedRolesSet = {};
            $scope.selectedIndustry = {};

            $scope.selectProject = {};
            $scope.set = [];
            $scope.searchText = '';
            $scope.selectUserSpan = {};

            $scope.gridOptions = {
                rowHeight: 50,
                selectionRowHeaderWidth: 50,
                enableFullRowSelection: false,
                enableRowSelection: false,
                enableSorting: false,
                enableFiltering: false,
                enableColumnMenus: false,
                enableRowHeaderSelection: false,
                enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                columnDefs: [
                {
                    field: 'index', name: $translate.instant('SequenceNoCol'), width: '10%', headerCellClass: 'right', enableFiltering: false,

                    cellTemplate: '<div class="ui-grid-cell-contents right"><span>{{row.entity.index}}<span></div>'
                },
                  {
                      field: 'name', name: $translate.instant('ProjectNameCol'), width: '20%', headerCellClass: '',

                      cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.nameDisplay}}<span></div>'
                  },

                  {
                      field: 'organizationName', name: $translate.instant('ProjectCompanyCol'), width: '25%', headerCellClass: '',

                      cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.organizationNameDisplay}}</span></div>'
                  },
                  {
                      field: 'industryName', name: $translate.instant('PIndustry'), width: '10%', headerCellClass: '',

                      cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.industryNameDisplay}}</span></div>'
                  },
                  {
                      field: 'year', name: $translate.instant('ProjectYearCol'), width: '10%', headerCellClass: '',

                      cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.yearDisplay}}</span></div>'
                  },
                   {
                       field: 'serviceTypeName', name: $translate.instant('ProjectServiceCol'), width: '15%', headerCellClass: '',

                       cellTemplate: '<div class="ui-grid-cell-contents"><span>{{row.entity.serviceTypeName}}</span></div>'
                   },
                  {
                      name: $translate.instant('OrganizationStructureOperation'), width: '10%', headerCellClass: 'center', enableFiltering: false,
                      cellTemplate: '<div class="project-manage-grid-operation ui-grid-cell-contents">' +
                          '<a class="operate-btn" href="javascript:void(0)" ng-click="grid.appScope.assignUser(row.entity)"> <i class="material-icons">person</i><span></span></a>' +

                          '<a class="operate-btn" href="javascript:void(0)" ng-click="grid.appScope.loadProject(row.entity.id)"> <i ng-if="row.entity.nameDisplay" class="material-icons">create</i><span></span></a>' +
                          '</div>'
                  }
                ],
                onRegisterApi: function (gridApi) {
                    $scope.gridApi = gridApi;
                    $scope.gridApi.grid.registerRowsProcessor($scope.singleFilter, 200);
                }
            };

            $scope.singleFilter = function (renderableRows) {
                var matcher = new RegExp($scope.searchProjectText);

                var isSelectYear = false;
                if ($scope.queryProjectYear && $scope.queryProjectYear.length > 0) {
                    isSelectYear = true;
                };

                renderableRows.forEach(function (row) {
                    var match = false;
                    if (isSelectYear && row.entity.year + '' !== $scope.queryProjectYear) {
                        match = false;
                    } else {
                        ['name', 'serviceTypeName', 'organizationName', 'industryName'].forEach(function (field) {
                            if (row.entity[field].match(matcher)) {
                                match = true;
                            }
                        });
                    }

                    if (!match) {
                        row.visible = false;
                    }
                });

                return renderableRows;
            };

            $scope.gridOptions.noData = false;

            $scope.newProject = newProject;

            $scope.saveProject = saveProject;

            $scope.loadProject = loadProject;

            $scope.deleteProject = deleteProject;

            $scope.deleteProjects = deleteProjects;

            $scope.deleteProjectConfirm = deleteProjectConfirm;

            $scope.deleteProjectsConfirm = deleteProjectsConfirm;

            $scope.reloadProjectData = reloadProjectData;

            $scope.assignUser = assignUser;

            $scope.getUserChecked = getUserChecked;

            $scope.initProjectList = initProjectList;

            $scope.roleTreeLoad = roleTreeLoad;

            $scope.selectNode = selectNode;

            $scope.toggle = toggle;

            $scope.toggleSub = toggleSub;
            $scope.search = search;

            $scope.checkUser = checkUser;

            //init project list
            //init service dropdown list
            initServiceList();

            initProjectList();

            //init project year dropdown list
            initProjectYear();

            loadProjectIndustryList();

            loadAllTemplate();

            // 加载用户列表
            // initUser();

        })();

    }
]);
infrastructureModule.directive('projectManage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('projectManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/projectManage/project-manage.html' + '?_=' + Math.random(),
            replace: true,
            scope: {
                projectId: '@',
                serviceType: '@'
            },
            controller: 'ProjectManageController',
        };
    }
]);
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();
        })();
    }
]);
infrastructureModule.directive('roleManage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('roleManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/roleManage/views/role-manage.html' + '?_=' + Math.random(),
            replace: true,
            scope: {},
            controller: 'RoleManageController',
            link: function (scope, element) {
                $(document).on({
                    mouseenter: function (e) {
                        $(this).css('font-weight', 'bold');
                    },
                    mouseleave: function (e) {
                        $(this).css('font-weight', 'normal');
                    }
                }, '.icon-role-category-modify,.icon-role-category-delete,.ng-inline-edit__button');

                $(document).on('click', '.ng-inline-edit__button--edit', function () {
                     
                });

                Split(['#left-container', '#right-container'], {
                    //An array of initial sizes of the elements, specified as percentage values. Example: Setting the initial sizes to 25% and 75%.
                    sizes: [22, 78],

                    //An array of minimum sizes of the elements, specified as pixel values. Example: Setting the minimum sizes to 100px and 300px, respectively.
                    minSize: [250, 750],

                    onDragEnd: function () {
                        //$timeout(function () {
                        //    $rootScope.$broadcast(enums.vatEvent.layoutChanged, {});
                        //}, 700);
                    }
                })
            }
        };
    }
]);


infrastructureModule.directive('roleNameUnique', ['$q', 'roleService', function ($q, roleService) {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            if (!ctrl) return;

            ctrl.$asyncValidators.roleNameUnique = function (modelValue, viewValue) {
                if (ctrl.$isEmpty(modelValue)) {
                    $q.resolve();
                }

                var def = $q.defer();

                var newRoleName = $('#EditRoleName').val(); //scope.roleUpdatedModel.editRoleName;
                var oldRoleName = scope.selectedRole.name;

                roleService.validateRoleNameUnique(newRoleName, oldRoleName)
                    .success(function (data, status, headers, config) {
                        if (data) {
                            def.resolve();
                        } else {
                            def.reject();
                        }
                    })
                    .error(function (data, status, headers, config) {
                        def.reject();
                    });

                return def.promise;
            };
        }
    }
}]);

infrastructureModule.directive("editableDiv", function () {
    return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, element, attrs, ngModel) {

            function read() {
                // view -> model
                var html = element.html();
                html = html.replace(/&nbsp;/g, "\u00a0");
                ngModel.$setViewValue(html);
            }
            // model -> view
            ngModel.$render = function () {
                element.html(ngModel.$viewValue || "");
            };

            element.bind("blur", function () {
                scope.$apply(read);
            });
            element.bind("keydown keypress", function (event) {
                if (event.which === 13) {
                    this.blur();
                    event.preventDefault();
                }
            });
        }
    };
});
infrastructureModule
    .controller('storeArchitectureViewController', ['$scope', '$log', 'SweetAlert', '$translate', '$timeout', 'stockService', '$document', '$state', '$stateParams', '$interval', 'roleService', '$q', 'userService', '$uibModal', 'dimensionService', 'CacheFactory','ackMessageBox','ackUibModal','ackLib',
        function ($scope, $log, SweetAlert, $translate, $timeout, stockService, $document, $state, $stateParams, $interval, roleService, $q, userService, $uibModal, dimensionService, CacheFactory, ackMessageBox, ackUibModal,ackLib) {
            'use strict';

            var charContainerID = '#store-chart-container';
             
            $scope.entity = {
                stockDate: new Date(),
                currentDate: new Date()
            };

            $scope.stockOptions = {
                empty: 0,
                modify: 1, //修改  
                addHistory: 2 //变更
            }

            $scope.stockStatus = $scope.stockOptions.empty;

            var template = {
                topNodeTemplate: $("#topNode-name").html(),  //最顶层节点
                nameNodeEdit: $("#node-name-edit").html(),  //name,机构名称
                nameNodeQuery: $("#node-name-query").html(),  //
                titleNode: $("#title-name-node").html() //普通行
            };

            var ReplaceObj = {
                //顶部节点
                topNodeName: '{{#topNodeName#}}',
                //机构名称
                organizationName: '{{#organizationName#}}',
                organizationID: '{{#organizationID#}}',
                moneyNumber: '{{#moneyNumber#}}',    //多少钱 stockPercent
                stockPercent: '{{#stockPercent#}}',
            };


            // 关于日志部分
            $scope.showOperateLogPop = function () {
                $scope.isShowLog = true;
            };


            $(document).on('blur', '#stockList .dx-texteditor-input', function (e) {
                $scope.stockGridInstance.focus($(this));
            });

            var orgchartService = {
                //获取stock架构的列表
                getDataSource: function () {
                    var deferred = $q.defer();
                    var param = {
                        currentDate: $scope.entity.stockDate || ''
                    };

                    stockService.getStockList(param).success(function (data) {
                        if (data) {
                            //console.log(JSON.stringify(data));
                            deferred.resolve(data);
                        }
                    });
                    return deferred.promise;
                },

                //创建orgchart节点
                createNewNode: function (row, templateNameNode, templateTitleNode) {

                    var temp = [];
                    var relationship = '110';
                    if (row.children && row.children.length > 0) {
                        relationship = '111';
                    }

                    var node = {
                        'name': templateNameNode.replaceToEnd(ReplaceObj.organizationName, row.name)
                                        .replaceToEnd(ReplaceObj.organizationID, row.id),
                        'stockAmount': row.stockAmount,
                        'capitalPercent': row.capitalPercent,
                        //'title': templateTitleNode.replaceToEnd(ReplaceObj.moneyNumber, row.capitalAmount).replaceToEnd(ReplaceObj.stockPercent, row.capitalPercent == undefined ? '0' : row.capitalPercent),

                        'children': [],
                        'relationship': relationship
                    };

                    return node;
                },

                //递归生成子节点
                createNodeRecursion: function (childrenList, parentNode, templateNameNode, templateTitleNode) {

                    if (childrenList.length == 0) return;

                    childrenList.forEach(function (row) {
                        var newNode = orgchartService.createNewNode(row, templateNameNode, templateTitleNode);
                        parentNode.children.push(newNode);

                        if (row.children && row.children.length > 0) {
                            orgchartService.createNodeRecursion(row.children, newNode, templateNameNode, templateTitleNode);
                        }
                    });
                },

                populateOrgChart: function () {

                    this.getDataSource().then(function (data) {

                        //如果没有编辑维度值的权限,则不显示编辑的笔icon
                        var templateNameNode = template.nameNodeQuery;
                        if ($scope.hasDimensionValueEditPermission) {
                            templateNameNode = template.nameNodeEdit;
                        };
                        var templateTitleNode = template.titleNode;

                        // orgService.getOrgDashboard($scope.parentDimensionID).success(function (data) {
                        orgchartService.renderOrgChart({});

                        if (data !== undefined && data !== null && data.length > 0) {
                            //console.log(JSON.stringify(data));
                            var topNodeName = template.topNodeTemplate.replace(ReplaceObj.topNodeName, data[0].name);

                            var datasource = {
                                'name': topNodeName,
                                'children': []
                            };
                            data.forEach(function (row) {

                                var newNode = orgchartService.createNewNode(row, templateNameNode, templateTitleNode);
                                datasource.children = newNode.children;

                                if (row.children && row.children.length > 0) {
                                    orgchartService.createNodeRecursion(row.children, newNode, templateNameNode, templateTitleNode);
                                }

                            });
                            //生成orgchart
                            if (datasource.children.length > 0) {
                                $scope.stockArchitectureCache = datasource;
                                orgchartService.renderOrgChart(datasource);
                            }
                        }
                    });
                },

                //开始生产org chart树
                renderOrgChart: function (datasource) {

                    $(charContainerID).html('');
                    //渲染orgchart
                    $(charContainerID).orgchart({
                        'data': datasource,
                        'pan': false,
                        'zoom': false,
                        "draggable": false,
                        'exportButton': false,
                        'direction': 'l2r',
                        'nodeContent': 'title',
                        'exportFilename': 'SportsChart',
                        'parentNodeSymbol': 'fa-th-large',
                        'zoomoutLimit': 2,
                        'zoominLimit': 7,
                        'depth': 5,
                        'createNode': function ($node, data) {
                            if (data.relationship != '001') {
                                var amount = data.stockAmount <= 0 ? '-' : data.stockAmount;
                                var leftMenu = '<div class="node-line-left"><span >' + amount + '</span>';
                                var rightMenu = '<div class="node-line-right"><span >' + data.capitalPercent + '%</span>';
                                $node.append(leftMenu).append(rightMenu);
                            }
                        }
                    });
                    var horizontalCenter = Math.floor(window.innerHeight / 2);
                    console.log('horizontalCenter: ' + horizontalCenter);
                    $(charContainerID).scrollTop(horizontalCenter + 'px');
                },

            };

            $scope.modalService = {
                stockModal: {
                    open: function () {
                        $scope.stockModalInstance = ackUibModal($scope, 'stockEdit.html', 'stockEditModal', '.store-architecture-view', 'static')
                        $scope.stockModalInstance.open();
                    },
                    save: function (result) {
                        
                        $scope.saveStock();
                
                       
                    },
                    cancel: function () {
                        $scope.stockModalInstance.cancel();
                    }
                }
            };

            var getService = {
                getStockListByOrgID: function (param) {
                    var deferred = $q.defer();
                    stockService.getStockListByOrgID(param).success(function (data) {
                        if (data) {
                            //console.log(JSON.stringify(data));
                            deferred.resolve(data);
                        }
                    });
                    return deferred.promise;
                }
            };

            var updateService = {
                updateStock: function (stock) {
                    var deferred = $q.defer();
                    stockService.updateStock(stock).success(function (data) {
                        if (data) {
                           // console.log(JSON.stringify(data));
                            deferred.resolve(data);
                        }
                    });
                    return deferred.promise;
                },
                //删除机构
                deleteOrgList: function (stockList, orgID) {
                    var deferred = $q.defer();
                    if (stockList.length > 0) {
                        stockService.deleteOrgList(stockList, orgID).success(function (data) {
                            if (data) {
                                deferred.resolve(data);
                            }
                        });
                    }
                    else {
                        deferred.resolve(true);
                    }
                    return deferred.promise;
                },
                //添加机构
                addOrgList: function (stockList, orgID) {
                    var deferred = $q.defer();
                    if (stockList.length > 0) {
                        stockService.addOrgList(stockList, orgID).success(function (data) {
                            if (data) {
                                deferred.resolve(data);
                            }
                        });
                    }
                    else {
                        deferred.resolve(true);
                    }
                    return deferred.promise;
                },
                updateOrgList: function (stockList, orgID) {
                    var deferred = $q.defer();
                    if (stockList.length > 0) {
                        stockService.updateOrgList(stockList, orgID).success(function (data) {
                            if (data) {
                                deferred.resolve(data);
                            }
                        });
                    }
                    else {
                        deferred.resolve(true);
                    }
                    return deferred.promise;
                }

            };


            $scope.fullScreenText = '全屏展示';
            $scope.showBefore = true;

            //顶部的维度状态改变,更新orgchart
            $scope.$on('DimensionUpdate', function (event, data) {
                initData();
                setParentDimension();
            });

            //通知父层去更新统计
            var notifyTopPage = function () {
                $scope.$emit("hasDimensionUpdated", { isupdated: true });
            };

            //隐藏机构general info
            var hideOrgGeneralInfo = function () {
                $(orgGeneralInfoPopId).hide();
            };

            // 显示机构general info,并设置好位置
            var showOrgCard = function (popCard, row, topOffset, leftOffset) {

                popCard.css("display", "block");

                var top = row.offset().top + topOffset;
                if (top + popCard.height() > window.innerHeight) {
                    top = window.innerHeight - popCard.height() - topOffset;
                    //top = row.offset().top - topOffset - popCard.height();
                }

                popCard.css('top', top + 'px');

                var left = row.offset().left + leftOffset;
                if (left + popCard.width() > window.innerWidth) {
                    left = row.offset().left - popCard.width() - leftOffset;
                }

                popCard.css('left', left + 'px');

                popCard.show();

                $(document).one('click', function (e) {
                    hideOrgGeneralInfo();
                });
            };


            //设置维度的名称和值,和类型
            var setParentDimension = function () {
                var deferred = $q.defer();
                dimensionService.getDimensionById($scope.parentDimensionID).success(function (data) {
                    if (data) {
                        $scope.parentDimensionName = data.name;
                        $scope.parentDimensionType = data.dimensionType;
                        deferred.resolve(data);
                    }
                });
                return deferred.promise;
            }
     

            //点击编辑的时候,弹框编辑
            $scope.editOrgStock = function (orgID) {

                $scope.selectedOrgID = orgID;
                $scope.editStockModal = {};
                populateModal(orgID);
         
                $scope.modalService.stockModal.open();
            };

            var resetStatus = function () {
                $scope.stockGridInstance.columnOption('删除', 'visible', false);
                $scope.stockGridInstance.columnOption('showStockAmount', 'allowEditing', false);
                $scope.stockStatus = $scope.stockOptions.empty;
            };

            var populateModal = function (orgID) {
                resetEditModalData();
                $scope.stockStatus = $scope.stockOptions.empty;
                var param = {
                    currentDate: $scope.entity.stockDate,
                    orgID: orgID

                };
                getService.getStockListByOrgID(param).then(function (data) {
                    if (data) {
                        populateTabData(data, orgID);
                    }
                });
            };

            var populateTabData = function (data,orgID) {
           
                resetStatus();

                //当前记录
                data.parentList.forEach(function (item) {
                    item.id = item.id || PWC.newGuid();
                    item.effectiveDate = ackLib.validation.isEmpty(item.effectiveDate) ? '' : moment(item.effectiveDate).format(constant.date.dateFormatyyyyMMddUppper);
                    item.expiredDate = ackLib.validation.isEmpty(item.expiredDate) ? '' : moment(item.expiredDate).format(constant.date.dateFormatyyyyMMddUppper);
                    item.stockAmount = parseFloat(item.stockAmount).toFixed(constant.toFixedNumber2);
                });

                //历史记录
                data.historyParentList.forEach(function (item) {
                    item.id= item.id || PWC.newGuid();
                    item.effectiveDate = ackLib.validation.isEmpty(item.effectiveDate) ? '' : moment(item.effectiveDate).format(constant.date.dateFormatyyyyMMddUppper);
                    item.expiredDate = ackLib.validation.isEmpty(item.expiredDate) ? '' : moment(item.expiredDate).format(constant.date.dateFormatyyyyMMddUppper);
                    item.alterDate = ackLib.validation.isEmpty(item.alterDate) ? '' : moment(item.alterDate).format(constant.date.dateFormatyyyyMMddUppper);
                    item.stockAmount = parseFloat(item.stockAmount).toFixed(constant.toFixedNumber2);
                });

                var tabList = [];

                var orderIndex = 0;

                var currentNode = data.stockDto;

                var beforeText = "之前";
                var firstEntity = {
                    id: orderIndex,
                    name: currentNode.name,
                    code: currentNode.code,
                    capitalAmount: currentNode.capitalAmount.toFixed(constant.toFixedNumber2),  //注册资本
                    showCapitalAmount: currentNode.capitalAmount <= 0 ? '-' : currentNode.capitalAmount.toFixed(constant.toFixedNumber2),
                    capitalPercent: currentNode.capitalPercent, //股权比例
                    stockDataGridDataSource: data.parentList,
                    index: orderIndex,
                    atlerDate:'最新',
                    text:'最新',
                    stockStatus: $scope.stockOptions.empty,
   
                }

                tabList.push(firstEntity);

                var historyAlterDate = _.unique(_.pluck(data.historyParentList, 'alterDate'), function (item) {
                    return item;
                });
           
                historyAlterDate.forEach(function (alterDate) {
                    
                    //根据某一天来获取当天的所有数据
                    var findAlterDate = _.filter(data.historyParentList, function (item) {
                        return item.alterDate == alterDate;
                    });

                    var first = findAlterDate[0]
                    if (first) {
                        orderIndex = orderIndex + 1;
                        var entity = {
                            id: orderIndex,
                            name: firstEntity.name,
                            code: firstEntity.code,
                            capitalAmount: first.capitalAmount.toFixed(constant.toFixedNumber2),  //注册资本
                            showCapitalAmount: first.capitalAmount <= 0 ? '-' : first.capitalAmount.toFixed(constant.toFixedNumber2),
                            capitalPercent: first.capitalPercent, //股权比例
                            stockDataGridDataSource: findAlterDate,
                            index: orderIndex,
                            atlerDate: first.alterDate,
                            text: first.alterDate + beforeText,
                            stockStatus: $scope.stockOptions.empty,
                        }
                        tabList.push(entity);
                    }
                });

                $scope.tabInstance.selectedItemKeys = [firstEntity.index];
                $scope.stockTabList = tabList;

                $scope.editStockModal = firstEntity;
                populdateStockDataSource(firstEntity.stockDataGridDataSource);

                $scope.selectTab = 0;
                $scope.tabInstance.repaint();
            };

            var populdateStockDataSource = function (dataSource) {
         
                $scope.stockDataSource = dataSource;
                $scope.oldStockData = populateDataObject($scope.stockDataSource);
                $scope.stockGridInstance.refresh();
            };

            //保存股权信息
            $scope.saveStock = function () {
                ////存一个历史记录
                //// Check to make sure the cache doesn't already exist
                //stockCache.put('oldStock', $scope.stockArchitectureCache);

                var oldData = $scope.oldStockData;
                var newData = populateDataObject($scope.stockDataSource);

                if (angular.equals(oldData, newData) && $scope.stockStatus==$scope.stockOptions.empty) {
                    //nothing to do
                    //  alert('same data');
                    $scope.stockModalInstance.close();
                } else {

                    var deleteList = [];
                    var addList = [];
                    var updateList = [];
                    //旧数据在新数据中没有找到,则放到addList
                    newData.forEach(function (row) {

                        updateList.push(row);

                        var findResult = _.find(oldData, function (item) {
                            return item.id == row.id;
                        });
                        //旧数据没有找到,说明是新加的数据
                        if (!findResult) {
                            addList.push(row);

                        }
                        //else {
                        //    //如果旧数据找到了,查看是否相等,,不等的话,放到update list
                        //    if (!angular.equals(row, findResult)) {
                        //        updateList.push(row);
                        //    }
                        //}

                    });
                    //新数据在旧数据中没有找到,则放到deleteList
                    oldData.forEach(function (row) {

                        var findResult = _.find(newData, function (item) {
                            return item.id == row.id;
                        });
                        //新数据没有找到,说明是删除的数据
                        if (!findResult) {
                            deleteList.push(row);
                        }
                    });

                    var addHistory = function () {
                        var deferred = $q.defer();
                        //变更
                        if ($scope.stockStatus == $scope.stockOptions.addHistory) {
                            var stockParam = {
                                currentDate: $scope.entity.currentDate,
                                orgID: $scope.selectedOrgID
                            }
                            stockService.addHistoryStocks(stockParam).success(function (data) {
                                if (data) {
                                    deferred.resolve(data);
                                    ////刷新历史变更记录
                                    //populateModal($scope.selectedOrgID);
                                }
                            });
                        }
                            //修改
                        else if ($scope.stockStatus !== $scope.stockOptions.addHistory) {
                            deferred.resolve(true);
                            $scope.stockModalInstance.close();
                        }
                        
                        return deferred.promise;
                    };


                    //console.log('addList: ' + JSON.stringify(addList));
                    //console.log('updateList: ' + JSON.stringify(updateList));
                    //console.log('deleteList: ' + JSON.stringify(deleteList));

                    //添加历史记录
                    addHistory().then(function (data) {
                         //添加新增的记录
                        updateService.addOrgList(addList, $scope.selectedOrgID).then(function (data) {

                            updateList.forEach(function (item) {
                                item.capitalAmount = $scope.editStockModal.capitalAmount;
                            });
                            //修改记录
                            updateService.updateOrgList(updateList, $scope.selectedOrgID).then(function (data) {
                                //删除记录
                                updateService.deleteOrgList(deleteList, $scope.selectedOrgID).then(function (data) {

                                    if (data) {
                                        ackMessageBox.success(ackLib.Helper.translate("SaveSuccess"));
                                     
                                        //刷新历史变更记录
                                        populateModal($scope.selectedOrgID);
                                        //刷新
                                        orgchartService.populateOrgChart();
                                    }
                                });
                            });
                        })
                    });
                }
            };

            //删除某一个机构(jack delete)
            $scope.removeStock = function (stock) {

                var stockList = [];
                var deleteObj = { id: stock.id, name: stock.name };
                stockList.push(deleteObj);

                var confirmToDelete = $translate.instant('ConfirmToDelete');

                ackMessageBox.confirm(confirmToDelete, '').then(function (data) {
                    if (data) {

                        var tempData = $scope.stockDataSource;
                        for (var i = 0; i < tempData.length; i++) {
                            if (tempData[i].id == stock.id) {
                                tempData.splice(i, 1);
                                break;
                            }
                        }
                        $scope.stockDataSource = tempData;
                    }
                });
            };

            //添加现有机构
            $scope.$watch('addExistOrgIsUpdate', function (newValue, oldValue) {
                if (newValue) {
                    if ($scope.selectedExistOrgList && $scope.selectedExistOrgList.length > 0) {
                        //console.log(JSON.stringify($scope.selectedExistOrgList));
                        addOrgToStockList($scope.selectedExistOrgList);
                    }
                }
            });

            //修改注册资本的时候,比例要重新计算
            $scope.$watch('editStockModal.showCapitalAmount', function (newValue, oldValue) {

                if (!$scope.editStockModal || !$scope.stockDataSource) return;

                if (newValue && newValue > 0) {
                    $scope.editStockModal.capitalAmount = newValue;
                }
                else {
                    // $scope.editStockModal.showCapitalAmount = '-';

                    $scope.editStockModal.capitalAmount = 0;
                }
                
           
                $scope.stockDataSource.forEach(function (row) {

                    if (row.stockAmount > 0) {

                        row.showStockAmount = row.stockAmount;

                        if (newValue && newValue > 0) {

                            row.capitalPercent = parseFloat(row.stockAmount / newValue * 100).toFixed(constant.toFixedNumber2);
                            row.canEditPercent = false;
                        }
                        else {
                            //如果任意一个资本没有填,股权占比就允许手工填入,可以直接修改股权占比
                            row.canEditPercent = true;
                        }
                    }
                    else {
                        row.canEditPercent = true;
                        row.showStockAmount = '-';
                    }
                });


                $scope.stockGridInstance.refresh();

            });

            ////修改注册资本的时候,比例要重新计算
            $scope.$watch('stockDataSource', function (newValue, oldValue) {
                if (newValue && oldValue && newValue !== oldValue) {
   
                    for (var i = 0; i < newValue.length; i++) {
                        
                        var row = newValue[i];
                        if (!row.showStockAmount)
                        {
                            row.showStockAmount = row.stockAmount;
                        }

                        if (row.showStockAmount != '-' && row.showStockAmount > 0) {
                            row.stockAmount = row.showStockAmount;
                        }
                        else {
                            row.stockAmount = 0;
                        }

                        if (row.stockAmount > 0) {
                            if ($scope.editStockModal.capitalAmount > 0) {
                                row.capitalPercent = parseFloat(row.stockAmount / $scope.editStockModal.capitalAmount * 100).toFixed(constant.toFixedNumber4);
                                row.canEditPercent = false;
                            }
                            else {

                            }
                        }
                        else {
                            row.canEditPercent = true;
                            row.showStockAmount = '-';
                        }

                    }
                    $scope.stockGridInstance.refresh();
                }
            },true);

            var populateDataObject = function (data) {
                var arraryList = [];

                if (data) {
                    data.forEach(function (row) {
                        var newObject = {};
                        newObject.id = row.id;
                        newObject.name = row.name;
                        newObject.capitalAmount = row.capitalAmount;
                        newObject.capitalPercent = row.capitalPercent;
                        newObject.parentID = row.parentID;
                        newObject.stockAmount = row.stockAmount;
                        arraryList.push(newObject);
                    });
                }
                return arraryList;

            }

            //添加机构列表 (jack add)
            var addOrgToStockList = function (orgList) {

                var stockList = [];
                var index = 20;
                var childrenAmount = $scope.editStockModal.capitalAmount;

                var hasExist = false;

                for (var i = 0; i < orgList.length; i++) {
                    var row = orgList[i];

                    var findExist = _.find($scope.stockDataSource, function (item) {
                        return item.id == row.id;
                    });

                    if (findExist) {
                        hasExist = true;
                        continue;
                    }

                    if (!findExist) {
                        var randomNum = parseFloat(Math.random() * 10000).toFixed(constant.toFixedNumber2);
                        if (randomNum > childrenAmount) {
                            randomNum = childrenAmount;
                        }
                        var newData = {
                            id: row.id,
                            name: row.name,
                            code: row.code,
                            capitalAmount: randomNum,
                            capitalPercent: index,
                            parentID: $scope.selectedOrgID,
                            stockAmount: parseFloat(childrenAmount * index / 100).toFixed(constant.toFixedNumber2),
                        }
                        stockList.push(newData);
                        $scope.stockDataSource.push(newData);
                    }
                }

                //if (hasExist)
                //{
                //    showWarning("不能添加已经存在的机构");
                //}

                //updateService.addOrgList(stockList, $scope.selectedOrgID).then(function (data) {
                //    if (data) {
                //        populateModal($scope.selectedOrgID);
                //    }
                //});
            };

            //添加现有机
            $scope.addExistOrg = function () {
                $scope.selectedKeyItems = [];

                var selectedKeyItem = [];
                $scope.stockDataSource.forEach(function (row) {
                    selectedKeyItem.push(row.id);
                });
                $scope.selectedKeyItems = selectedKeyItem;
                $scope.addExistOrgOperateType = constant.Operation.Add;
                $scope.addExistOrgIsUpdate = false;
            }


            var initStockDatagrid = function () {

                var commonOptions = {
                    bindingOptions: {
                    },
                    selection: {
                        mode: "single"
                    },
                    columns: [],
                    loadPanel: {
                        enabled: false,
                    },
                    keyExpr: "id",
                    scrolling: {
                        mode: "virtual"
                    },
                    allowColumnResizing: true,
                    noDataText: $translate.instant('NoDataText'),
                    showColumnLines: true,
                    showRowLines: true,
                    rowAlternationEnabled: true,
                    showBorders: true,
                    sorting: {
                        mode: "none"
                    },


                };


                var commonColumns = [
                                {
                                    dataField: "name",
                                    caption: "出资人名称",
                                    alignment: 'center',
                                    allowEditing: false,
                                },
                                {
                                    dataField: "code",
                                    caption: "代码",
                                    alignment: 'center',
                                    allowEditing: false,
                                },
                                {
                                    dataField: "showStockAmount",
                                    caption: "出资额(万元)",
                                    alignment: 'center',
                                    allowEditing: true,
                                    format: { type: 'currency', precision: constant.toFixedNumber2 }
                                },
                                {
                                    dataField: "capitalPercent",
                                    caption: "股权占比(%)",
                                    alignment: 'center',
                                    allowEditing: false,
                                    format: { type: 'currency', precision: constant.toFixedNumber4 }
                                },
                                {
                                    dataField: "id",
                                    caption: $translate.instant('Delete'),
                                    alignment: 'center',
                                    width: 50,
                                    visible: $scope.stockStatus !== $scope.stockOptions.empty,
                                    allowEditing: false,
                                    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.removeStock(options.row.data);
                                            }).appendTo(container);
                                        }
                                        catch (e) {
                                            $log.error(e);
                                        }
                                    }
                                }
                ];

                var options = angular.copy(commonOptions);
                var historyOptions = angular.copy(commonOptions);
                //当前的
                $scope.dataGridStockOptions = angular.extend(options, {
                    bindingOptions: {
                        dataSource: 'stockDataSource'
                    },
                    keyExpr: "id",
                    columns: commonColumns,
                    summary: {
                        totalItems: [
                            {
                                column: "showStockAmount",
                                displayFormat: "{0}",
                                valueFormat: {
                                    type: 'currency',
                                    precision: constant.toFixedNumber2
                                },
                                summaryType: "sum"
                            }, {
                                column: "capitalPercent",
                                displayFormat: "{0}",
                                valueFormat: {
                                    type: 'currency',
                                    precision: constant.toFixedNumber4
                                },
                                summaryType: "sum"
                            }, {
                                showInColumn: "name",
                                displayFormat: "合计"
                            }
                        ]
                    },

                    onInitialized: function (e) {
                        $scope.stockGridInstance = e.component;
                    },
                    editing: {
                        mode: "cell",
                        allowUpdating: true,
                        //texts:{
                        //    editRow: "编辑",
                        //    cancelRowChanges: "取消",
                        //    saveRowChanges: "确定",
                        //},
                    },
                    onCellClick: function (e) {
                        if (e.rowType == "data" && e.column.dataField == "capitalPercent") {
                            if (e.data.canEditPercent) {
                                e.isEditing = true;
                                $scope.stockGridInstance.editCell(e.rowIndex, e.columnIndex);
                                $('.dx-texteditor-input').focus();
                            }
                            else {
                                e.isEditing = false;
                            }
                        }

                    },
                });


                //历史记录
                $scope.historyDataGridStockOptions = angular.extend(historyOptions, {
                    bindingOptions: {
                        dataSource: 'historyStockDataSource'
                    },
                    keyExpr: "id",
                    columns: [
                                {
                                    dataField: "name",
                                    caption: "出资人名称",
                                    alignment: 'center',
                                },
                                {
                                    dataField: "code",
                                    caption: "代码",
                                    alignment: 'center',
                                },
                                {
                                    dataField: "stockAmount",
                                    caption: "出资额(万元)",
                                    alignment: 'center',
                                    format: { type: 'currency', precision: constant.toFixedNumber2 } 
                              
                                },
                                {
                                    dataField: "capitalPercent",
                                    caption: "股权占比(%)",
                                    alignment: 'center',
                                    format: { type: 'currency', precision: constant.toFixedNumber4 }
                                },
                                {
                                    dataField: "effectiveDate",
                                    caption: "有效起始日",
                                    alignment: 'center',
                                },

                                {
                                    dataField: "expiredDate",
                                    caption: "有效截止日",
                                    alignment: 'center',
                                },
                    ],

                    summary: {
                       
                        totalItems: [
                            {
                                column: "stockAmount",
                                displayFormat: "{0}",
                                valueFormat: {
                                    type: 'currency',
                                    precision: constant.toFixedNumber2
                                },
                                summaryType: "sum"
                            }, {
                                column: "capitalPercent",
                                displayFormat: "{0}",
                                valueFormat: {
                                    type: 'currency',
                                    precision: constant.toFixedNumber4
                                },
                                summaryType: "sum"
                            }, {
                                showInColumn: "name",
                                displayFormat: "合计",
                            }
                        ]
                    },
                    onInitialized: function (e) {
                        $scope.historyStockGridInstance = e.component;
                    },
                });
            };

            var initData = function () {
                orgchartService.populateOrgChart();
                initStockDatagrid();
         
                // $scope.modalService.stockModal.open();
            };

            var resetEditModalData = function () {
                $scope.currentNavItem = "page0";
                $scope.stockStatus = $scope.stockOptions.empty;
                $scope.historyStockDataSource = [];
                $scope.stockDataSource = [];
            
            }

            //初始化控件
            var initTextBoxContorls = function () {

                var isShowClearButton = true;
                var boxHeight = '35px';

                $scope.entityOptions = {
                    txtStockeDateOptions: {
                        bindingOptions: {
                            value: 'entity.stockDate',
                        },
                        valueChangeEvent: "change",
                        onValueChanged: function (e) {
                            var stockDate = e.value;
                            if (stockDate != e.previousValue) {
                                if (!stockDate || (stockDate && stockDate != '' && ackLib.validation.isDate(stockDate))) {
                                    //刷新
                                    orgchartService.populateOrgChart();
                                }
                            }
                        },
                        displayFormat: constant.date.dateFormatyyyyMMdd,
                        dateSerializationFormat: constant.date.dateFormatyyyyMMdd,
                        placeholder: $scope.pleaseInput,
                        invalidDateMessage: "请输入正确的日期格式(如1990/01/01)",
                        showClearButton: isShowClearButton,
                        height: boxHeight,

                    },

                    //变更日期
                    txtStockUpdateOptions: {
                        bindingOptions: {
                            value: 'entity.currentDate',
                        },
                        valueChangeEvent: "change",
                        onValueChanged: function (e) {
                            var stockDate = e.value;
           
                        },
                        displayFormat: constant.date.dateFormatyyyyMMdd,
                        dateSerializationFormat: constant.date.dateFormatyyyyMMdd,
                        placeholder: $scope.pleaseInput,
                        invalidDateMessage: "请输入正确的日期格式(如1990/01/01)",
                        showClearButton: isShowClearButton,
                        height: boxHeight,
                    }
                },

                $scope.modalStock = {
                    //修改
                    modifyStock: function () {
                        $scope.stockStatus = $scope.stockOptions.modify;
                        $scope.stockGridInstance.columnOption('删除', 'visible', true);
                        $scope.stockGridInstance.columnOption('showStockAmount', 'allowEditing', true);
                    },
                    //变更
                    addHistoryStock: function () {
                        $scope.stockStatus = $scope.stockOptions.addHistory;
                        $scope.stockGridInstance.columnOption('删除', 'visible', true);
                        $scope.stockGridInstance.columnOption('showStockAmount', 'allowEditing', true);
                    },
                    cancelChange: function () {
                        resetStatus();
                    }
                }

                $scope.stockTab = {
                    bindingOptions: {
                        dataSource: 'stockTabList',
                        selectedIndex :'selectTab'
                    },
                
                    scrollByContent: true,
                    showNavButtons: true,
                    selectedIndex: 0,         //默认选中第一个
                    //width:500,
                    onContentReady:function(e)
                    {
                        e.component.selectedItemKeys=[0];
                    },
                    onInitialized: function (e) {
                        $scope.tabInstance = e.component;
                    },
                    onSelectionChanged:function(e)
                    {
                        if (e.addedItems.length > 0 && e.addedItems[0]) {
                            var itemData = e.addedItems[0];
                            $scope.currentNavItem = 'page' + itemData.index;
                            $scope.editStockModal = itemData;
                            if (itemData.index == 0) {
                                //当前数据
                                $scope.stockDataSource = itemData.stockDataGridDataSource;
                                $scope.stockGridInstance.refresh();

                                $scope.oldStockData = populateDataObject($scope.stockDataSource);
                            }
                            else {
                                //历史数据
                                $scope.historyStockDataSource = itemData.stockDataGridDataSource;
                                $scope.historyStockGridInstance.refresh();
                            }
                        }
                    },
                    //点击行,选中
                    onItemClick: function (e) {
    

                    },
                };

            };


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

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

                $scope.hasAttributeQueryPermission = false;

                $scope.hasAccessSettingQueryPermission = false;
                $scope.hasAccessSettingEditPermission = false;

                //查看机构的权限
                var tempOrg = constant.adminPermission.infrastructure.organizationManage;
                list.push(tempOrg.addCode);
                list.push(tempOrg.queryCode);
                list.push(tempOrg.editCode);

                //自定义显示属性的权限
                var tempAttr = constant.adminPermission.infrastructure.customAttribute;
                list.push(tempAttr.queryCode);

                //权限设置的权限
                var tempAcess = constant.adminPermission.infrastructure.accessSetting;
                list.push(tempAcess.queryCode);
                list.push(tempAcess.editCode);

                $scope.hasDimensionValueEditPermission = false;
                //编辑自定义维度值的时候的权限
                if ($scope.parentDimensionType == constant.dimensionType.BusinessUnit) {
                    var tempDV = constant.adminPermission.basicData.businessUnit;
                    list.push(tempDV.editCode);
                }
                else {
                    //自定义维度的权限
                    var tempDV = constant.adminPermission.basicData.selfDimension;
                    list.push(tempDV.editCode);
                }

                $scope.$root.checkUserPermissionList(list).success(function (data) {
                    // console.log('data: ' + JSON.stringify(data));
                    $scope.hasAddPermission = data[tempOrg.addCode];
                    $scope.hasQueryPermission = data[tempOrg.queryCode];
                    $scope.hasEditPermission = data[tempOrg.editCode];

                    $scope.hasAttributeQueryPermission = data[tempAttr.queryCode];

                    $scope.hasAccessSettingQueryPermission = data[tempAcess.queryCode];
                    $scope.hasAccessSettingEditPermission = data[tempAcess.editCode];

                    $scope.hasDimensionValueEditPermission = data[tempDV.editCode];

                    if ($scope.hasQueryPermission) {
                        initOrgChartData();
                    }
                });
            };


            (function initialize() {
                $log.debug('storeArchitectureViewController.ctor()...');
                $log.debug($state.params.dimensionID);
                var dimensionID = 'c61a5bd6-a996-4952-9869-d053995237e5'; //集团为事业部
                //  $scope.parentDimensionID = $state.params.dimensionID || 'c61a5bd6-a996-4952-9869-d053995237e8';
                var parentDimensionID = $state.params.dimensionID || dimensionID;
                $scope.parentDimensionID = parentDimensionID;
                $scope.showAttributeDimensionID = $scope.parentDimensionID;
                $scope.canEditPercent = false;
                initTextBoxContorls();
                initData();
                //事业部和自定义维度的权限
                setParentDimension().then(function (data) {
                    //checkUserPermission();
                });

               // $scope.editOrgStock("231c835b-169e-4963-b6f5-1601c0795fa6");
            })();
        }
    ]);
infrastructureModule.directive('storeArchitectureView', ['$log', '$compile', '$timeout', '$interval',
   function ($log, $compile, $timeout, $interval) {
       'use strict';
       $log.debug('storeArchitectureView.ctor()...');

       return {
           restrict: 'E',
           templateUrl: '/app/admin/infrastructure/storeArchitectureView/store-architecture-view.html' + '?_=' + Math.random(),
           scope: {},
           replace: true,
           controller: 'storeArchitectureViewController',
           link: function (scope, element) {
                 
               $(".card").draggable({ containment: "parent", cursor: "cursor", handle: ".card-header" });

               var showCardSeleted = '.show-card';

               //$(document).off('click');
               element.off('click');

               var stopPropagation = function (event) {
                   event = event || window.event;
                   if (event.stopPropagation) {
                       event.stopPropagation();
                   } else {
                       event.cancelBubble = true;
                   }
               };

               element.on('mouseenter', '.node', function () {

                   $(this).find('.title-name-edit').css('display', 'block');
                   stopPropagation();
               });
               element.on('mouseleave', '.node', function () {
                   $(this).find('.title-name-edit').css('display', 'none');
                   stopPropagation();
               });


               //编辑机构的股权结构
               element.on('click', '.edit-stock-value', function () {
                   //事业部ID
                   var orgID = $(this).attr("data-organization-id");
                   if (orgID) {
                       console.log("orgID: " + orgID);

                       scope.editOrgStock(orgID);
                   }
                   stopPropagation();
                   return false;
                   //  stopPropagation();
               });

               scope.showFullScreen = function () {

                   $('.store-architecture-view').parent().toggleClass('fullScreen');
                   if ($('.store-architecture-view').parent().hasClass('fullScreen')) {
                       scope.fullScreenText = '退出全屏';
                       scope.isShowFullScreen = true;
                   } else {
                       scope.fullScreenText = '全屏展示';
                       scope.isShowFullScreen = false;
                   }
               }
           }
       };
   }
]);


infrastructureModule
    .controller('UserDetailViewController', ['$window', '$location', 'userService', '$stateParams', '$location', '$scope',
        '$log', 'SweetAlert', 'permissionService', '$translate', 'areaRegionService', 'uiGridTreeViewConstants', '$timeout',
        'areaService', 'uiGridConstants', '$interval', 'orgService', '$q', 'roleService', '$rootScope', '$state', 'userService',
        function ($window, $location, userService, $stateParams, $location, $scope,
            $log, SweetAlert, permissionService, $translate, areaRegionService, uiGridTreeViewConstants, $timeout,
            areaService, uiGridConstants, $interval, orgService, $q, roleService, $rootScope, $state, userService) {

            $scope.serviceType = constant.serviceType.VAT;
            var roleCardSelector = '#assign-user-box';

            $scope.back = function () {
                if ($rootScope.previousLocation.indexOf('user') > 0) {
                    //重新刷新数据
                    $state.go('user');
                } else {
                    $window.history.back();
                }
            };

            $scope.showOperateLogPop = function () {
                $scope.isShowLog = true;
            };

            // 添加或者编辑机构层级成功之后,刷新当前页面的数据
            $scope.$watch('userRolesIsUpdate', function (newValue, oldValue) {
                if (newValue) {
                    $scope.getOrgRoleListView();
                }
            });

            //设置角色,可添加或取消原始角色,可添加和取消额外角色。可设置访问不可访问
            $scope.setRoleToOrganization = function () {
                var selectedArr = [];
                var hasOneItem = false;
                $scope.roleList.forEach(function (item) {

                    if (item.isChecked) {
                        hasOneItem = true;
                    }

                    var selectedObject = {
                        id: PWC.newGuid(),
                        dimensionValueID: $scope.dimensionValueId,
                        dimensionID: $scope.dimensionId,
                        userID: $scope.userId,
                        organizationID: $scope.organizationId,
                        roleID: item.id,
                        isAdd: item.isChecked,
                        IsAccessible: $scope.roleEntity.isAccessible,
                        hasOriginalRole: $scope.roleEntity.hasOriginalRole
                    };

                    selectedArr.push(selectedObject);
                });

                if (!hasOneItem && $scope.roleEntity.isAccessible && !$scope.roleEntity.hasOriginalRole) {
                    showWarning("SelectAtLeastOneRole");
                    return false;
                };

                userService.updateUserRoleOrganization(selectedArr).success(function (data) {
                    if (data) {
                        showSuccessMsg("SaveSuccess");
                        //刷新用户角色列表
                        loadUserRole();
                    }
                });

            };

            //用户角色框隐藏
            $scope.closeSetRoleCard = function () {
                hideRoleInfoCard();
            };

            var hideRoleInfoCard = function () {
                $(roleCardSelector).hide();
            };

            //添加现有机构到当前用户权限控制
            $scope.addExistOrg = function () {
                var selectedKeyItem = [];
                $scope.orgSettingList.data.forEach(function (row) {
                    selectedKeyItem.push(row.orgID);
                });
                $scope.selectedKeyItems = selectedKeyItem;
                $scope.addExistOrgOperateType = constant.Operation.Add;
                $scope.addExistOrgIsUpdate = false;
            };

            //添加现有权限
            $scope.popupRoleAddWin = function () {

                if (!$scope.hasEditPermission) {
                    return;
                }
                var selectedKeyItem = [];
                $scope.roleInfoList.forEach(function (row) {
                    selectedKeyItem.push(row.roleID);
                });
                $scope.addExistRoleOperateType = constant.Operation.Add;
                $scope.addExistRoleIsUpdated = false;
                $scope.selectedRoleList = selectedKeyItem;
            };

            $scope.$watch('addExistRoleIsUpdated', function (newValue, oldValue) {
                if (newValue) {
                    if ($scope.selectedRoleList && $scope.selectedRoleList.length > 0) {

                        var removedRoles = [];
                        var addedRoles = [];
                        var roleIdList = _.map($scope.roleInfoList, function (item) {
                            return item.roleID;
                        });
                        var userRoleUpdateModel = {};

                        roleIdList.forEach(function (item) {
                            if ($scope.selectedRoleList.indexOf(item) < 0) {
                                removedRoles.push(item);
                            }
                        });

                        $scope.selectedRoleList.forEach(function (item) {
                            if (roleIdList.indexOf(item) < 0) {
                                addedRoles.push(item);
                            }
                        });

                        var userID = $scope.selectedUser.id;
                        userRoleUpdateModel.userID = userID;
                        userRoleUpdateModel.removedRoles = []; //如果取消掉,根据现在的需求不需要删除
                        userRoleUpdateModel.addedRoles = addedRoles;

                        if (addedRoles.length > 0) {
                            roleService.updateUserRole(userRoleUpdateModel).success(function (data) {
                                $scope.getUserRoleData();
                                $scope.getDimensionRoleListView();
                                $scope.getOrgRoleListView();

                                SweetAlert.success($translate.instant('addUserRoleTitle'), $translate.instant('addUserRoleSuccess'));
                            });
                        } else {
                            SweetAlert.success($translate.instant('operationSuccess'), $translate.instant('noAdditionalRoleAdded'));
                        }
                    }
                }
            });

            // 添加范围确认之后触发数据库更新操作
            $scope.$watch('addExistDimensionIsUpdated', function (newValue, oldValue) {
                if (newValue) {
                    if ($scope.selectedDimensionValueList && $scope.selectedDimensionValueList.length > 0) {

                        var addedDimensions = [];
                        var dimensionValueUpdateModel = {};

                        $scope.selectedDimensionValueList.forEach(function (item) {
                            if ($scope.originalDVlist == undefined || $scope.originalDVlist.indexOf(item) < 0) {
                                addedDimensions.push(item);
                            }
                        });

                        var userID = $scope.selectedUser.id;
                        dimensionValueUpdateModel.userID = userID;
                        dimensionValueUpdateModel.addedDimensions = addedDimensions;

                        var invalidItems = _.filter(addedDimensions, function (item) {
                            return item.parentID == null;
                        });

                        if (invalidItems.length == addedDimensions.length) {
                            SweetAlert.warning($translate.instant('addDimensionValueFirstWarn'));
                            return;
                        } else {

                            roleService.updateDimensionValues(dimensionValueUpdateModel).success(function (data) {
                                $scope.getDimensionRoleListView();

                                SweetAlert.success($translate.instant('addDimensionTitle'), $translate.instant('addDimensionSuccess'));
                            });
                        }
                    } else {
                        SweetAlert.warning($translate.instant('addDimensionValueFirstWarn'));
                        return;
                    }
                }
            });

            $scope.$watch('isUpdateUser', function (newValue, oldValue) {
                if (newValue) {
                    $scope.getUserRoleData();
                    $scope.getDimensionRoleListView();
                    $scope.getOrgRoleListView();
                }
            });

            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 getOrignalUserRole = function (userID) {
                //getUserRoleListByUserID
                userService.getUserRoleListByUserID(userID).success(function (data) {
                    if (data) {

                        var subRoleList = data && data.roleInfoList || [];
                        $scope.originalUserRoleList = subRoleList;
                        //console.log(JSON.stringify("rolelist:" + JSON.stringify(data.RoleInfoList)));
                    }

                });
            };

            //显示角色卡片的时候,获取所有当前用户的角色列表,如果在所有角色列表中有存在,则选中
            var getRoleByService = function (row, enumSettingType) {
                roleService.getRoleListByRoleTypeId(constant.serviceType.VAT).success(function (roleData) {
                    if (roleData) {
                        //$scope.roleList = roleData;

                        var selectedUserRole;
                        if (enumSettingType == 1) {
                            //当前维度行
                            selectedUserRole = _.find($scope.dimensionRoleList, function (item) {
                                return item.dimensionID == row.dimensionID && item.dimensionValueID == row.dimensionValueID;
                            });
                        } else {
                            selectedUserRole = _.find($scope.orgRoleList, function (item) {
                                return item.orgID == row.orgID;
                            });
                        }

                        //当前用户行的角色列表
                        var roleInfoList = selectedUserRole && selectedUserRole.extraRoleList;
                        var hasAllCheck = true;
                        if (roleInfoList && roleInfoList.length > 0) {
                            roleData.forEach(function (roleItem) {

                                var selectedRole = _.find(roleInfoList, function (item) {
                                    return item.roleID == roleItem.id;
                                });

                                if (selectedRole) {
                                    roleItem.isChecked = true;
                                } else {
                                    roleItem.isChecked = false;
                                    hasAllCheck = false;
                                }
                            });
                        } else {
                            hasAllCheck = false;
                        }
                        $scope.roleEntity.isAllRoleChecked = hasAllCheck;
                        $scope.roleEntity.isHeritable = row.hasOriginalRole;
                        $scope.roleEntity.isAccessible = row.isAccessible;
                        $scope.roleList = roleData;
                        // console.log(JSON.stringify(roleData));
                    }
                });
            };

            //点击显示当前用户的角色卡片
            $scope.showRoleInfoCard = function (row, enumSettingType) {

                $scope.enumSettingType = enumSettingType;
                $scope.roleEntity = {};
                $scope.dimensionValueID = row.entity.dimensionValueID;
                $scope.orgID = row.entity.orgID;
                $scope.dimensionID = row.entity.dimensionID;

                var roleCard = $(roleCardSelector);
                var rowId = $('#' + (row.entity.dimensionValueID || row.entity.orgID));

                getOrignalUserRole($scope.userID);
                getRoleByService(row.entity, enumSettingType);

                showOrgCard(roleCard, rowId, 40, 0);

            };

            //全部选中
            $scope.AllRoleChecked = function () {
                angular.forEach($scope.roleList, function (item) {
                    item.isChecked = $scope.roleEntity.isAllRoleChecked;
                });
            };

            var showWarning = function (resultMsg) {

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

            //为事业部的值(其他维度的值)添加用户角色
            $scope.setRoleToDimensionValue = function () {

                if ($scope.enumSettingType == 1) {
                    saveUpdateRoleDimensionValue();
                } else {
                    saveUpateRoleOrg();
                }
                $scope.closeSetRoleCard();
            };

            var saveUpateRoleOrg = function () {
                var selectedArr = [];
                var hasOneItem = false;
                $scope.roleList.forEach(function (item) {

                    if (item.isChecked) {
                        hasOneItem = true;
                    }

                    var selectedObject = {
                        id: PWC.newGuid(),
                        userID: $scope.userID,
                        organizationID: $scope.orgID,
                        roleID: item.id,
                        isAdd: item.isChecked,
                        IsAccessible: $scope.roleEntity.isAccessible,
                        hasOriginalRole: $scope.roleEntity.isHeritable || false
                    };

                    selectedArr.push(selectedObject);
                });

                if (!hasOneItem && $scope.roleEntity.isAccessible && !$scope.roleEntity.hasOriginalRole) {
                    showWarning("SelectAtLeastOneRole");
                    return false;
                };

                userService.updateUserRoleOrganization(selectedArr).success(function (data) {
                    if (data) {
                        showSuccessMsg("SaveSuccess");
                        //刷新用户角色列表
                        $scope.getOrgRoleListView();
                    }
                });
            };

            var saveUpdateRoleDimensionValue = function () {
                var selectedArr = [];
                var hasOneItem = false;
                $scope.roleList.forEach(function (item) {

                    if (item.isChecked) {
                        hasOneItem = true;
                    }

                    var selectedObject = {
                        id: PWC.newGuid(),
                        dimensionValueID: $scope.dimensionValueID,
                        dimensionID: $scope.dimensionID,
                        userID: $scope.userID,
                        roleID: item.id,
                        isAdd: item.isChecked,
                        IsAccessible: $scope.roleEntity.isAccessible,
                        hasOriginalRole: $scope.roleEntity.isHeritable || false
                    };

                    selectedArr.push(selectedObject);
                });

                if (!hasOneItem && $scope.roleEntity.isAccessible && !$scope.roleEntity.isHeritable) {
                    showWarning("SelectAtLeastOneRole");
                    return false;
                };

                userService.updateUserRoleDimension(selectedArr).success(function (data) {
                    if (data) {
                        $scope.getDimensionRoleListView();
                        showSuccessMsg("SaveSuccess");
                    }
                });
            };

            var showSuccessMsg = function (resultMsg) {

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

            //用户角色框隐藏
            $scope.closeSetRoleCard = function () {
                hideRoleInfoCard();
            };

            var hideRoleInfoCard = function () {
                $(roleCardSelector).hide();
            };

            // 显示机构角色卡片  
            var showOrgCard = function (popCard, row, topOffset, leftOffset) {

                popCard.css("display", "block");

                var top = row.offset().top + topOffset;
                if (top + popCard.height() > window.innerHeight) {
                    top = window.innerHeight - popCard.height() - 20;
                }

                popCard.css('top', top + 'px');

                var left = row.offset().left + leftOffset;
                if (left + popCard.width() > window.innerWidth) {
                    left = row.offset().left - popCard.width() - 30;
                }

                popCard.css('left', left + 'px');

                popCard.show();
                event.stopPropagation();
            };

            $scope.loadPermissions = function (roleID, $event) {

                //如果点击的是x,就不需要加载其他数据了
                var element = $event.target;
                var closeEle = $(element).hasClass('fa');

                if (closeEle) {
                    return;
                }

                //获取全部的权限
                //前端选中该节点
                $scope.selectedRoleID = roleID;
                if (roleID == '0') {
                    getAllPermissionsByRoleIDList();
                } else {
                    $scope.getDevTreePermissionsByRoleID($scope.selectedRoleID, $scope.serviceType);
                }
            };

            var getAllPermissionsByRoleIDList = function () {
                var roleIDList = _.map($scope.roleInfoList, function (item) {
                    return item.roleID;
                });
                $scope.getDevTreePermissionsByRoleIDList(roleIDList, $scope.serviceType);
            };

            //获取指定角色ID的权限
            $scope.getDevTreePermissionsByRoleID = function (roleID, serviceID) {
                permissionService.getDevTreePermissionsByRoleID(roleID, serviceID).success(function (data) {
                    $scope.permissionTreeViewData = data.permissionDevTreeList;;

                });
            };

            //获取指定角色列表的权限合集
            $scope.getDevTreePermissionsByRoleIDList = function (roleIDList, serviceID) {
                permissionService.getDevTreePermissionsByRoleIDList(roleIDList, serviceID).success(function (data) {
                    $scope.permissionTreeViewData = data;
                });
            };

            // 修改用户
            $scope.updateUser = function (user) {
                if (!$scope.hasEditPermission) {
                    return;
                }

                if ($scope.userOperateType === constant.Operation.Edit) {
                    $scope.userOperateType = null;
                }

                $scope.userOperateType = constant.Operation.Edit;
                $scope.isUpdateUser = false;
                $scope.selectedUser = {
                    id: user.id
                };
            };

            // 禁用用户
            $scope.disableUser = function (user) {
                if (!$scope.hasEditPermission) {
                    return;
                }
                if ($scope.userOperateType === constant.Operation.Disable) {
                    $scope.userOperateType = null;
                }

                $scope.userOperateType = constant.Operation.Disable;
                $scope.isUpdateUser = false;
                $scope.selectedUser = {
                    id: user.id,
                    userName: user.userName,
                    currentStatus: user.status
                };
            };

            // 启用用户
            $scope.enable = function (user) {
                if (!$scope.hasEditPermission) {
                    return;
                }
                if ($scope.userOperateType === constant.Operation.Enable) {
                    $scope.userOperateType = null;
                }

                $scope.userOperateType = constant.Operation.Enable;
                $scope.isUpdateUser = false;
                $scope.selectedUser = {
                    id: user.id,
                    userName: user.userName,
                    currentStatus: user.status
                };
            };

            //删除用户角色
            $scope.removeRole = function (role) {
                if (!$scope.hasEditPermission) {
                    return;
                }

                var roleDeleteText;
                if (role.roleID !== '0') {
                    roleDeleteText = $translate.instant('roleDeleteConfirm') + ' - ' + role.roleName + '?';
                } else {
                    roleDeleteText = $translate.instant('allRoleDeleteConfirm') + '?';
                }

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

                        if (role.roleID == '0') {
                            var roleIDList = _.map($scope.roleInfoList, function (item) {
                                return item.roleID;
                            });

                            roleService.removeUserRole($scope.userID, roleIDList, $scope.serviceType).success(function (data) {
                                if (data) {
                                    //同时刷新上层维度设置和各机构设置    
                                    $scope.getUserRoleData();
                                    $scope.getDimensionRoleListView();
                                    $scope.getOrgRoleListView();
                                }
                            });
                            $scope.roleInfoList = [];
                        } else {
                            var roleList = [];
                            roleList.push(role.roleID);
                            roleService.removeUserRole($scope.userID, roleList, $scope.serviceType).success(function (data) {
                                if (data) {
                                    //同时刷新上层维度设置和各机构设置  
                                    $scope.getDimensionRoleListView();
                                    $scope.getOrgRoleListView();
                                }
                            });
                            $scope.roleInfoList = _.without($scope.roleInfoList, _.find($scope.roleInfoList, function (item) {
                                return item.roleID === role.roleID
                            }));

                            if ($scope.roleInfoList.length === 1) {
                                var singleRole = $scope.roleInfoList[0];
                                if (singleRole.roleID === '0') {
                                    getAllPermissionsByRoleIDList();
                                }
                            }
                        }

                        SweetAlert.success($translate.instant('deleteUserRoleTitle'), $translate.instant('deleteUserRoleSuccess'));
                    }
                });
            };

            $scope.getGridHeight = function () {
                return {};
            };

            $scope.getUserRoleData = function () {

                var userId = $stateParams.id;
                $scope.userID = userId;

                userService.GetUserById(userId).success(function (data) {
                    $scope.user = data;

                    var filterOperationObjectList = [];
                    filterOperationObjectList.push(data.userName);

                    $scope.filterOperationObjectList = filterOperationObjectList;

                    console.log(data);
                });

                $scope.selectedUser = {
                    id: userId
                };

                roleService.getAllRoleListByUserID(userId, $scope.serviceType).success(function (data) {

                    //默认添加全部角色 
                    data.unshift({
                        roleName: '全部角色',
                        roleID: '0'
                    });
                    $scope.roleInfoList = data;

                    $scope.selectedRoleID = data !== undefined && data.length > 0 ? data[0].roleID : '';
                    //$scope.getDevTreePermissionsByRoleID($scope.selectedRoleID, $scope.serviceType);
                    getAllPermissionsByRoleIDList();
                });
            };

            $scope.toggleCallback = function (ivhNode, isExpand, ivhTree) {
                console.log(ivhNode);
            };

            $scope.tickCheckbox = function (ivhNode, isExpand, ivhTree) {
                console.log(ivhNode);
            };

            $scope.filter = function () {
                var searchValue = $scope.searchText;
                if (searchValue !== '') {

                    var xx = $.extend(true, {}, $scope.data);

                    var tempData = _.filter(xx, function (item) {
                        return (item.orgName !== undefined && item.orgName.indexOf(searchValue) >= 0) ||
                            (item.businessUnit !== undefined && item.businessUnit.indexOf(searchValue) >= 0) ||
                            (item.areaName !== undefined && item.areaName.indexOf(searchValue) >= 0) ||
                            (item.industryName !== undefined && item.industryName.indexOf(searchValue) >= 0) ||
                            (item.userInfo !== undefined && item.userInfo.indexOf(searchValue) >= 0);
                    });

                    tempData.forEach(function (item) { item.$$treeLevel = 0; });
                    $scope.areaORGGridList.data = tempData;
                } else {
                    $scope.areaORGGridList.data = $scope.data;
                }
            };

            $scope.AddOrg = function (buID) {
                $scope.orgOperateType = constant.Operation.Add;
                $scope.selectedOrg = null;
                $scope.isOrgUpdate = false;
                $scope.organization = {
                    businessUnitID: buID
                };
            };

            //添加现有维度
            $scope.popupDimensionAddWin = function () {

                $scope.addExisDimensionOperateType = constant.Operation.Add;
                $scope.addExistDimensionIsUpdated = false;
                $scope.selectedDimensionValueList = [];

                $scope.generalSettingList.data.forEach(function (item) {
                    $scope.selectedDimensionValueList.push(item.dimensionValueID);
                    $scope.originalDVlist = angular.copy($scope.selectedDimensionValueList);
                });
            };

            //获取机构上层维度设置
            $scope.getDimensionRoleListView = function () {

                var userId = $stateParams.id;
                orgService.getOrgBuAreaIndustryUser(userId).success(function (data) {

                    data.forEach(function (row) {
                        var uniqueRoleList = _.uniq(row.roleList, function (item) {
                            return item.roleID;
                        });

                        if (row.isAccessible) {
                            var roleNameList = _.map(uniqueRoleList, function (x) {
                                return x.roleName;
                            }).join(',');
                            row.roleName = roleNameList;
                        } else {
                            row.roleName = $translate.instant('NonAccessible'); //不可访问
                        }

                        row.extraRoleList = _.filter(row.roleList, function (item) {
                            return item.roleSource == constant.roleSource.DimensionLevel;
                        });

                    });

                    $scope.dimensionRoleList = data;
                    $scope.generalSettingList.data = data;
                    $scope.getOrgRoleListView();
                });
            };

            //获取机构设置
            $scope.getOrgRoleListView = function () {

                var userId = $stateParams.id;
                userService.getUserRoleByUserID(userId).success(function (data) {
                    if (data && data.orgDtoList)
                        data.orgDtoList.forEach(function (row) {

                            //var uniqueRoleList = _.uniq(row.roleList, function (item) {
                            //    return item.id;
                            //});

                            //var roleNameList = _.map(uniqueRoleList, function (x) { return x.name; }).join(',');
                            //row.roleName = roleNameList;
                            //row.extraRoleList = _.filter(row.roleList, function (item) {
                            //    return item.roleSource == constant.roleSource.OrganizationLevel;
                            //});
                            var uniqRoleList = _.uniq(row.roleList, function (item) { return item.id });

                            if (row.isAccessible) {
                                if (uniqRoleList && uniqRoleList.length > 0) {
                                    row.roleName = _.map(uniqRoleList, function (x) { return x.name; }).join(constant.comma);
                                }
                                else {
                                    row.roleName = $translate.instant('NoRole');
                                }
                            }
                            else {
                                row.roleName = $translate.instant('NonAccessible'); //不可访问
                            }
                        });

                    $scope.orgRoleList = data.orgDtoList;
                    $scope.orgSettingList.data = data.orgDtoList;
                    $scope.allOrgInfo = data.orgRoleInfoList;
                });
            };

            //添加现有机构
            $scope.$watch('addExistOrgIsUpdate', function (newValue, oldValue) {
                if (newValue) {
                    if ($scope.selectedExistOrgList && $scope.selectedExistOrgList.length > 0) {
                        var orgList = [];
                        var newAddedItems = [];

                        $scope.orgSettingList.data.forEach(function (row) {
                            orgList.push(row.orgID);
                        });
                        var selectedOrgIdList = _.map($scope.selectedExistOrgList, function (item) {
                            return item.id;
                        });
                        selectedOrgIdList.forEach(function (orgId) {
                            if (orgList.indexOf(orgId) < 0) {
                                newAddedItems.push(orgId);
                            }
                        });

                        var userID = $stateParams.id;
                        roleService.updateUserOrg(newAddedItems, userID).success(function (data) {
                            $scope.getOrgRoleListView();
                            SweetAlert.success($translate.instant('addExistOrgTitle'), $translate.instant('addOrgListSuccess'));
                        });
                    }
                }
            });


            var areaORGGridInit = function () {
                $scope.areaORGGridList = {
                    enableRowSelection: true,
                    enableSelectAll: false,
                    rowHeight: 40,
                    enableRowHeaderSelection: false,
                    modifierKeysToMultiSelect: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    enableVerticalScrollbar: uiGridConstants.scrollbars.enableVerticalScrollbar,

                    enableSorting: true,
                    enableColumnMenus: false,
                    enableFiltering: false,
                    showTreeExpandNoChildren: false,
                    enableFullRowSelection: true, //是否点击行任意位置后选中,默认为false
                    multiSelect: false, // 是否可以选择多个,默认为true; 
                    columnDefs: [{
                        field: 'orgName',
                        name: $translate.instant('OrganizationName'),
                        headerCellClass: '',

                        cellTemplate: '<div ng-class="{true: \'text-align-left\', false: \'text-align-left-padding\'}[!row.entity.isOrganization]"><span title="{{row.entity.orgName}}">{{row.entity.orgName}}</span></div>'
                    }, {
                        field: 'businessUnit',
                        name: $translate.instant('BusinessUnitTitleName'),
                        headerCellClass: '',

                        cellTemplate: '<div class="text-align-left"><span title="{{row.entity.businessUnit}}">{{row.entity.businessUnit}}</span></div>'
                    }, {
                        field: 'area',
                        name: $translate.instant('AreaTitleName'),
                        headerCellClass: '',

                        cellTemplate: '<div class="text-align-left"><span>{{row.entity.areaName}}</span></div>'
                    }, {
                        field: 'industry',
                        name: $translate.instant('IndustryTitleName'),
                        headerCellClass: '',

                        cellTemplate: '<div class="text-align-left"><span>{{row.entity.industryName}}</span></div>'
                    }, {
                        field: 'user',
                        name: $translate.instant('UserTitleName'),
                        headerCellClass: '',

                        cellTemplate: '<div class="text-align-left"><span>{{row.entity.userInfo}}</span></div>'
                    }],
                    onRegisterApi: function (gridApi) {

                        $scope.gridApi = gridApi;

                        $scope.gridSelectCount = $scope.gridApi.selection.getSelectedRows().length;
                        var onRowsRenderedOff = gridApi.core.on.rowsRendered(null, function () {
                            onRowsRenderedOff(); // run once
                            PWC.triggerRowSelectOnClick('#etsGrid'); // requires '.ui-grid-canvas'
                        });
                        // call resize every 500 ms for 5 s after modal finishes opening - usually only necessary on a bootstrap modal
                        $interval(function () {
                            $scope.gridApi.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);

                    }
                };

                $scope.getRoleListWithComma = function (roleList) {
                    var nameList = _.map(roleList, function (item) {
                        return item.roleName
                    });
                    return nameList.join(',');
                };

                var str = '';
                if ($scope.hasEditPermission) {
                    str = '<div class="text-align-left"><span>&nbsp;<i class="fa fa-trash" style="color:#ee7749" aria-hidden="true" ng-click="grid.appScope.deleteDimensionRole(row)"></i></span></div>';
                } else {
                    str = '<div class="text-align-left"><span class="no-permission">&nbsp;<i class="fa fa-trash" style="color:#ee7749" aria-hidden="true"></i></span></div>';
                }

                //机构上层维度设置 grid初始化
                $scope.generalSettingList = {
                    enableRowSelection: true,
                    enableSelectAll: false,
                    rowHeight: 40,
                    enableRowHeaderSelection: false,
                    modifierKeysToMultiSelect: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    enableVerticalScrollbar: uiGridConstants.scrollbars.enableVerticalScrollbar,

                    enableSorting: true,
                    enableColumnMenus: false,
                    enableFiltering: false,
                    showTreeExpandNoChildren: false,
                    enableFullRowSelection: true, //是否点击行任意位置后选中,默认为false
                    multiSelect: false, // 是否可以选择多个,默认为true; 
                    columnDefs: [{
                        field: 'roleObject',
                        width: '20%',
                        name: $translate.instant('RoleDimensionTitle'),
                        headerCellClass: '',

                        cellTemplate: '<div><span title="{{row.entity.dimensionName}}" style="padding-left:10px;">{{row.entity.dimensionName}}</span></div>'
                    }, {
                        field: 'accessControl',
                        name: $translate.instant('DimensionName'),
                        headerCellClass: '',
                        width: '20%',
                        cellTemplate: '<div><span title="{{row.entity.dimensionValueName}}" style="padding-left:10px;">{{row.entity.dimensionValueName}}</span></div>'
                    }, {
                        field: 'role',
                        name: $translate.instant('RoleTitle'),
                        headerCellClass: '',
                        width: '39%',
                        cellTemplate: '<div class="text-align-left"  id="{{row.entity.dimensionValueID}}"  aria-hidden="true" ng-click="grid.appScope.showRoleInfoCard(row,1)"><span title="{{row.entity.roleName}}">{{row.entity.roleName |limitString:32 }}</span></div>'
                    }, {
                        field: 'array',
                        name: '',
                        headerCellClass: '',
                        width: '1%',
                        cellTemplate: '<div class="text-align-left"  id="{{row.entity.dimensionValueID}}"  aria-hidden="true" ng-click="grid.appScope.showRoleInfoCard(row,1)"><i class="fa fa-caret-down icon-right" style="padding-left: 0px;"></i></div>'
                    }, {
                        field: 'role',
                        name: $translate.instant('OrgUserAction'),
                        headerCellClass: '',
                        width: '20%',
                        cellTemplate: str
                    }],
                    onRegisterApi: function (gridApi) {

                        $scope.gridApi = gridApi;

                        $scope.gridSelectCount = $scope.gridApi.selection.getSelectedRows().length;
                        var onRowsRenderedOff = gridApi.core.on.rowsRendered(null, function () {
                            onRowsRenderedOff(); // run once
                            //PWC.triggerRowSelectOnClick('#etsGrid'); // requires '.ui-grid-canvas'
                        });
                        // call resize every 500 ms for 5 s after modal finishes opening - usually only necessary on a bootstrap modal
                        $interval(function () {
                            $scope.gridApi.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);

                    }
                };

                $scope.isChecked = true;

                $scope.switchCheck = function () {
                    $scope.isChecked = !$scope.isChecked;
                };


                var orgStr = '';
                if ($scope.hasEditPermission) {
                    orgStr = '<div class="text-align-left"><span><i style="color: #404041;" class="material-icons" ng-click="grid.appScope.modifyOrgRole(row)">create</i>&nbsp;<i class="fa fa-trash" style="color:#ee7749" aria-hidden="true" ng-click="grid.appScope.deleteOrgRole(row)"></i></span></div>';
                } else {
                    orgStr = '<div class="text-align-left"><span class="no-permission"><i class="material-icons">create</i>&nbsp;<i class="fa fa-trash" style="color:#ee7749" aria-hidden="true"></i></span></div>';
                }
                //机构设置 grid初始化
                $scope.orgSettingList = {
                    enableRowSelection: true,
                    enableSelectAll: false,
                    rowHeight: 40,
                    enableRowHeaderSelection: false,
                    modifierKeysToMultiSelect: false,
                    enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                    enableVerticalScrollbar: uiGridConstants.scrollbars.enableVerticalScrollbar,

                    enableSorting: true,
                    enableColumnMenus: false,
                    //enableColumnResizing: true,
                    enableFiltering: false,
                    showTreeExpandNoChildren: false,
                    enableFullRowSelection: true, //是否点击行任意位置后选中,默认为false
                    multiSelect: false, // 是否可以选择多个,默认为true; 
                    columnDefs: [{
                        field: 'orgNameTitle',
                        name: $translate.instant('OrgNameTitle'),
                        headerCellClass: '',
                        width: '35%',
                        cellTemplate: '<div ng-class="{true: \'text-align-left\', false: \'text-align-left-padding\'}[!row.entity.isOrganization]"><span title="{{row.entity.orgName}}">{{row.entity.orgName | limitString:30}}</span></div>'
                    }, {
                        field: 'roleTitle',
                        name: $translate.instant('RoleTitle'),
                        headerCellClass: '',
                        width: '40%',
                        cellTemplate: '<div class="text-align-left"  id="{{row.entity.orgID}}"  aria-hidden="true"><span title="{{row.entity.roleName}}">{{row.entity.roleName |limitString:32 }}</span></div>'
                    }, {
                        field: 'roleAction',
                        name: $translate.instant('OrgUserAction'),
                        headerCellClass: '',
                        width: '25%',
                        cellTemplate: orgStr
                    }],
                    onRegisterApi: function (gridApi) {

                        $scope.gridApi = gridApi;

                        $scope.gridSelectCount = $scope.gridApi.selection.getSelectedRows().length;
                        var onRowsRenderedOff = gridApi.core.on.rowsRendered(null, function () {
                            onRowsRenderedOff(); // run once
                            //PWC.triggerRowSelectOnClick('#etsGrid'); // requires '.ui-grid-canvas'
                        });
                        // call resize every 500 ms for 5 s after modal finishes opening - usually only necessary on a bootstrap modal
                        $interval(function () {
                            $scope.gridApi.core.handleWindowResize();
                        }, 500, 60 * 60 * 8);

                    }
                };

            };

            $scope.modifyDimensionRole = function (data) {
                console.log('modifyDimensionRole:', data);
            };

            $scope.deleteDimensionRole = function (data) {

                var userId = $stateParams.id;

                SweetAlert.swal({
                    title: $translate.instant('ConfirmDelete') + '?',
                    text: $translate.instant('userDimensionDeleteConfirm') + '?',
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: $translate.instant('Confirm'),
                    cancelButtonText: $translate.instant('Cancel'),
                    closeOnConfirm: false,
                    closeOnCancel: true
                }, function (isConfirm) {
                    if (isConfirm) {
                        orgService.deleteUserDimensionValue(data.entity, userId).success(function (data) {
                            $scope.getDimensionRoleListView();
                            SweetAlert.success($translate.instant('deleteRoleUserDetailTitle'), $translate.instant('deleteUserDimensionSuccess'));
                        });
                    }
                });
            };

            $scope.modifyOrgRole = function (row) {

                console.log(row);
                $scope.userRoleOperateType = constant.Operation.Edit;
                $scope.selectedOrgID = row.entity.orgID;
                $scope.selectedUserID = $scope.userID;
                $scope.userRolesIsUpdate = false;
            };

            $scope.deleteOrgRole = function (data) {

                var userId = $stateParams.id;

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

                        var selectedArr = [];
                        var allOrgInfo = _.filter($scope.allOrgInfo, function (item) {
                            return item.organizationID == data.entity.orgID;
                        });

                        if (allOrgInfo && allOrgInfo.length > 0) {
                            allOrgInfo.forEach(function (row) {
                                var selectedObject = {
                                    dimensionValueID: row.dimensionValueID,
                                    dimensionID: row.dimensionID,
                                    userID: userId,
                                    organizationID: row.organizationID,
                                    isHeritable: false //设置维度在机构上,是否可继承
                                };
                                selectedArr.push(selectedObject);
                            });
                        }


                        userService.deleteUserRoleOrg(selectedArr).success(function (data) {
                            if (data) {
                                SweetAlert.success($translate.instant('deleteRoleUserDetailTitle'), $translate.instant('deleteUserOrgSuccess'));
                                $scope.getOrgRoleListView();
                            }
                        });
                        //orgService.deleteUserOrg(data.entity, userId).success(function (data) {
                        //    $scope.getOrgRoleListView();
                        //    SweetAlert.success($translate.instant('deleteRoleUserDetailTitle'), $translate.instant('deleteUserOrgSuccess'));
                        //});
                    }
                });
            };


            var getUserPermission = function () {

                var list = [];

                var userManageTemp = constant.adminPermission.infrastructure.userManage;
                list.push(userManageTemp.addCode);
                list.push(userManageTemp.editCode);

                $scope.$root.checkUserPermissionList(list).success(function (data) {
                    $scope.hasAddPermission = data[userManageTemp.addCode];
                    $scope.hasEditPermission = data[userManageTemp.editCode];
                    areaORGGridInit();
                });
            };

            (function initialize() {
                $log.debug('UserDetailViewController.ctor()...');

                $scope.roleEntity = {};

                $scope.hasAddPermission = false;

                $scope.hasEditPermission = false;

                getUserPermission();

                loadPermissionTree();

                $scope.getDimensionRoleListView();
                $scope.getOrgRoleListView();

                $scope.getUserRoleData();

            })();
        }
    ]);

infrastructureModule.directive('userDetailView', ['$log', '$compile', '$timeout', '$interval',
    function ($log, $compile, $timeout, $interval) {
        'use strict';
        $log.debug('userDetailView.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/userDetail/user-detail-view.html' + '?_=' + Math.random(),
            scope: {},
            replace: true,
            controller: 'UserDetailViewController',
            link: function (scope, element) {

                $(document).on({
                    mouseenter: function () {
                        $(this).find('.remove-role-name').css('display', 'inline');
                    },
                    mouseleave: function () {
                        $(this).find('.remove-role-name').css('display', 'none');
                    }
                }, ".role-name"); //pass the element as an argument to .on

                $(document).on('click', function (e) {

                    var container = $(".assign-user-box");
                    // if the target of the click isn't the container nor a descendant of the container
                    if (!container.is(e.target) && container.has(e.target).length === 0) {
                        container.hide();
                    }
                });

                var stopPropagation = function (event) {
                    event = event || window.event;
                    if (event.stopPropagation) {
                        event.stopPropagation();
                    } else {
                        event.cancelBubble = true;
                    }
                }
            }//# end of link
        }
    }
]);
infrastructureModule
    .controller('userListController', ['$scope', '$log', 'userService', 'uiGridConstants', 'SweetAlert', 'projectService', 'roleService', '$translate', 'enums',
        function($scope, $log, userService, uiGridConstants, SweetAlert, projectService, roleService, $translate, enums) {
            'use strict';

            /***********************************************************new code start*********************************************************/
            $scope.totalCount = 0;

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

            // 修改用户
            $scope.createUser = function() {

                $scope.userOperateType = constant.Operation.Add
                $scope.isUpdateUser = false;
                $scope.selectedUser = {};
            };


            //如果添加了用户,则刷新
            $scope.$watch('isUpdateUser', function(newValue, oldValue) {
                if (newValue) {
                    getUserList();
                }
            });


            var getUserList = function() {
                userService.getAllUserRoleList(constant.serviceType.VAT).success(function(data) {
                    if (data) {

                        data.forEach(function(row) {
                            var uniqRoleList = _.uniq(row.roleInfoList, function(item) {
                                return item.id });
                            row.roleNameList = _.map(uniqRoleList, function(x) {
                                return x.name; }).join(constant.comma);
                            row.statusDesc = row.status == constant.activeStatus.active ? $translate.instant('Enable') : $translate.instant('Disabled');
                        });

                        $scope.treeListSource = data;
                        //console.log("JSON: " + JSON.stringify(data));
                        $scope.setGridHeight();
                    }
                });
            };

            var loadTreeList = function() {
                $scope.userTreeOptions = {
                    bindingOptions: {
                        dataSource: 'treeListSource'
                    },
                    columns: [{
                        dataField: "userName",
                        caption: $translate.instant('PUserName'),
                        cellTemplate: function (container, options) {
                            try {
                                $('<a class="hyper-link">' + options.value + '</a>')
                                    .attr('href', '#/userDetail/' + options.row.data.id)
                                    .appendTo(container);
                            }
                            catch (e) {
                                $log.error(e);
                            }
                        }
                    }, {
                        dataField: "email",
                        caption: $translate.instant('PE-mail')
                    }, {
                        dataField: "organizationName",
                        caption: $translate.instant('OrganizationID')

                    }, {
                        dataField: "roleNameList",
                        caption: $translate.instant('Role'),
                        width: 350

                    }, {
                        dataField: "statusDesc",
                        caption: $translate.instant('PStatus')

                    }],

                    loadPanel: {
                        enabled: false
                    },
                    scrolling: {
                        mode: "virtual"
                    },

                    keyExpr: "id",
                    parentIdExpr: "parentID",
                    selection: {
                        mode: "single"
                    },
                    allowColumnResizing: true,
                    columnAutoWidth: true,
                    showRowLines: true,
                    showColumnLines: true,
                    rowAlternationEnabled: true, //单双行颜色
                    noDataText: $translate.instant('NoDataText'),
                    showBorders: true,
                    //sorting: {
                    //    mode: "none"
                    //},
                    searchPanel: {
                        placeholder: $translate.instant('Search'),
                        width: 518,
                        visible: true
                    },
                    onContentReady: function (e) {
                        var totalCount = e.component.totalCount();
                        if (totalCount > 0) {
                            $scope.totalCount = totalCount;
                        }
                    },
                };

            };

            // 关于日志部分
            $scope.showOperateLogPop = function() {
                $scope.isShowLog = true;
            };

            var checkUserPermission = function () {

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

                var temp = constant.adminPermission.infrastructure.userManage;
                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.hasAddPermission = data[temp.addCode];
                    $scope.hasEditPermission = data[temp.editCode];
                    if ($scope.hasQueryPermission)
                    {
                        getUserList();
                    }
                });
            };

            //init page
            (function initialize() {
                $log.debug('UserList.ctor()...');
                loadTreeList();
                checkUserPermission();
            })();
        }
    ]);

infrastructureModule.directive('userList', ['$log',
    function ($log) {
        'use strict';
        $log.debug('userList.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/userList/user-list.html' + '?_=' + Math.random(),
            replace: true,
            scope: {},
            controller: 'userListController',
            link: function (scope, element) {

                scope.setGridHeight = function () {
                    var pageWrapSelector = ".user-list-wrap";
                    var menuSelector = ".menu-header";
                    var contentHeader = '.content-container .header';
                    var dxGridSelctor = "#userGridContainer";

                    var contentHeaderHeight = parseInt($(contentHeader).css('height').replace('px', ''));
                    var pageHeight = parseInt($(pageWrapSelector).css('height').replace('px', ''));
                    var menuHeight = parseInt($(menuSelector).css('height').replace('px', ''));
                    var height = pageHeight - menuHeight - contentHeaderHeight - 40 + 'px';

                    $(dxGridSelctor).css('max-height', height);
                };


                $(window).resize(function () {
                    scope.setGridHeight();
                });

                //var lazyLayout = _.debounce(setGridHeight, 50);
                //$(window).resize(lazyLayout);
            }
        };
    }
]);
infrastructureModule
.controller('UserManageController', ['$scope', '$log', 'userService', 'orgService', 'uiGridConstants', 'SweetAlert', 'projectService', 'roleService', '$translate', 'enums',
    function ($scope, $log, userService, orgService, uiGridConstants, SweetAlert, projectService, roleService, $translate, enums) {
        'use strict';

        /***********************************************************new code start*********************************************************/

        //Clear user model
        var newUser = function () {
            $scope.isAdd = true;
            $scope.editUserModel = {};
            resetErrorStatus();
            $('#addUserPop').modal('show');
        };


        //Initial user list
        var initUser = function () {
            userService.getUserTreeList().success(function (userData) {
                $scope.userList = userData;
                selectedUser($scope.userList[0].subUsers[0]);
                getProjectByUserId($scope.userList[0].subUsers[0].id);
            });
        };


        //select tree node event
        var selectedUser = function (user) {

            if (user.id === constant.guid.empty) {
                return;
            }

            $scope.selectUser = user;

            $scope.selectUser.statusName = $scope.selectUser.status === enums.userStatus.disabled ? $translate.instant('UserStateDisable') :
                ($scope.selectUser.status === enums.userStatus.active ? $translate.instant('UserStateEnable') :
                ($scope.selectUser.status === enums.userStatus.inActive ? $translate.instant('UserStateUnActive') :
                ($scope.selectUser.status === enums.userStatus.locked ? $translate.instant('UserStateLocked') : $translate.instant('UserStateUnknow'))));

            if ($scope.selectUser.organizationID) {
                orgService.getSingleOrg($scope.selectUser.organizationID).success(function (orgData) {
                    $scope.selectUser.OrgName = orgData.name;
                });
            }
            else {
                $scope.selectUser.OrgName = '';
            }

            getProjectByUserId($scope.selectUser.id);
        };

        //Load user info by userId
        var loadUser = function (userId) {
            $scope.isAdd = false;
            resetErrorStatus();
            userService.getSingleUser(userId).success(function (userData) {
                $scope.editUserModel.IsAdmin = userData.isAdmin;
                $scope.editUserModel.ID = userData.id;
                $scope.editUserModel.UserName = userData.userName;
                $scope.editUserModel.Status = userData.status;
                $scope.editUserModel.OrganizationID = userData.organizationID;
                $scope.editUserModel.Email = userData.email;
                $scope.editUserModel.OrgName = userData.orgName;
                $scope.editUserModel.RoleIDs = userData.roleIDs;
                $scope.editUserModel.RoleNames = userData.roleNames;
                $scope.editUserModel.CreateTime = userData.createTime;
                $scope.editUserModel.Password = userData.password;
            });
            $('#addUserPop').modal('show');
        };


        //Save role info
        var saveUser = function () {
            if (!($('#userForm').valid())) {
                return;
            }

            if ($scope.isAdd) {

                userService.addUser($scope.editUserModel).success(function (or) {
                    if (or) {
                        if (or.result === true) {
                            SweetAlert.success($translate.instant('AddUserSuccess'));
                            $scope.editUserModel = {};
                            initUser();
                        }
                        else {
                            SweetAlert.warning($translate.instant(or.resultMsg));
                        }
                    }
                });
            } else {

                userService.updateUser($scope.editUserModel).success(function (or) {
                    if (or) {
                        if (or.result === true) {
                            SweetAlert.success($translate.instant('UpdateUserSuccess'));
                            $scope.editUserModel = {};
                            initUser();
                        }
                        else {
                            SweetAlert.warning($translate.instant(or.resultMsg));
                        }
                    }
                });
            }
            $('#addUserPop').modal('hide');

        };

        //disable user account
        var disableUser = function (user) {
            SweetAlert.swal({
                title: $translate.instant('Confirm') + $translate.instant('StopUse') + '?',
                text: $translate.instant('Confirm') + $translate.instant('StopUse') + user.userName,
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55", confirmButtonText: $translate.instant('Confirm'),
                cancelButtonText: $translate.instant('Cancel'),
                closeOnConfirm: false,
                closeOnCancel: true
            },
          function (isConfirm) {
              if (isConfirm) {
                  // 选中
                  userService.enableOrDisableUser(user.id, 0).success(function (or) {
                      if (or) {
                          if (or.result === true) {
                              $scope.selectUser.status = enums.userStatus.disabled;
                              $scope.selectUser.statusName = $translate.instant('StopUse');
                              SweetAlert.success($translate.instant('DisableUserSuccess'));
                          }
                          else {
                              SweetAlert.warning($translate.instant(or.resultMsg));
                          }
                      }
                  });
              }
          });

        };

        //enable user account
        var enableUser = function (userId) {
            userService.enableOrDisableUser(userId, enums.userStatus.active).success(function (or) {
                if (or) {
                    if (or.result === true) {
                        $scope.selectUser.status = enums.userStatus.active;
                        $scope.selectUser.statusName = $translate.instant('Enable');
                        SweetAlert.success($translate.instant('EnableUserSuccess'));
                    }
                    else {
                        SweetAlert.warning($translate.instant(or.resultMsg));
                    }
                }
            })
        };

        //get project list by userid
        var getProjectByUserId = function (userId) {
            userService.getProjectListByUserId(userId).success(function (projectData) {
                var curProject = null;
                projectData.forEach(function (p) {
                    if (!curProject) {
                        curProject = p;
                        p.nameDisplay = p.name;
                        p.organizationNameDisplay = p.organizationName;
                        p.yearDisplay = p.year;
                    }
                    else {
                        if (p.id == curProject.id) {
                            p.nameDisplay = '';
                            p.organizationNameDisplay = '';
                            p.yearDisplay = '';
                        }
                        else {
                            curProject = p;
                            p.nameDisplay = p.name;
                            p.organizationNameDisplay = p.organizationName;
                            p.yearDisplay = p.year;
                        }
                    }
                });
                $scope.gridOptionsProjectList.data = projectData;
            });
        };


        //add project pop up 
        var addProjectPopUp = function () {
            if (!$scope.selectUser) {
                SweetAlert.warning($translate.instant('SelectUserFirst'));
                return;
            }

            if ($scope.selectUser.status === 0) {
                SweetAlert.warning($translate.instant('DisabledUser'));
                return;
            }

            projectService.getProjectExceptSelected($scope.selectUser.id).success(function (allProjectData) {
                //set index number, ui-grid have no $$index
                var projectIndex = 1;
                var curProject = null;
                allProjectData.forEach(function (p) {
                    if (!curProject) {
                        curProject = p;
                        p.index = projectIndex++;
                        p.nameDisplay = p.name;
                        p.organizationNameDisplay = p.organizationName;
                        p.yearDisplay = p.year;
                        p.industryNameDisplay = p.industryName;
                    }
                    else {
                        if (p.id == curProject.id) {
                            p.nameDisplay = '';
                            p.organizationNameDisplay = '';
                            p.yearDisplay = '';
                            p.industryNameDisplay = '';
                        }
                        else {
                            curProject = p;
                            p.index = projectIndex++;
                            p.nameDisplay = p.name;
                            p.organizationNameDisplay = p.organizationName;
                            p.yearDisplay = p.year;
                            p.industryNameDisplay = p.industryName;
                        }
                    }
                });
                $scope.gridOptionsAllProjectList.data = allProjectData;
            });

            $scope.gridApiAllProject.selection.clearSelectedRows();
            $('#addProjectPop').modal('show');
        };

        //add project to user
        var addProject = function () {
            var selectedProject = $scope.gridApiAllProject.selection.getSelectedRows();
            if (selectedProject && selectedProject.length === 0) {
                showInfo($translate.instant('AssignProject'), $translate.instant('SelectOneProjectToAdd'), 'addProjectPop');
                return;
            }
            var selectedProjectIds = [];
            if (selectedProject) {
                selectedProject.forEach(function (s) {
                    selectedProjectIds.push({ 'projectID': s.id, 'serviceTypeID': s.serviceTypeID });
                });
            }
            var userProject = {};
            userProject.UserId = $scope.selectUser.id;
            userProject.ProjectIds = selectedProjectIds;

            userService.addProjectToUser(userProject).success(function (or) {
                if (or) {
                    if (or.result === true) {
                        SweetAlert.success($translate.instant('AddProjectToUserSuccess'));
                        getProjectByUserId($scope.selectUser.id);
                        $('#addProjectPop').modal('hide');
                    }
                    else {
                        SweetAlert.warning($translate.instant(or.resultMsg));
                    }
                }

            });
        };

        //remove project from user
        var removeProject = function () {
            var selectedProject = $scope.gridApiProject.selection.getSelectedRows();
            if (selectedProject && selectedProject.length === 0) {
                SweetAlert.warning($translate.instant('SelectOneProjectToDelete'));
                return;
            }
            var selectedProjectIds = [];
            if (selectedProject) {
                selectedProject.forEach(function (s) {
                    selectedProjectIds.push({ 'projectID': s.id, 'serviceTypeID': s.serviceTypeID });
                });
            }
            var userProject = {};
            userProject.UserId = $scope.selectUser.id;
            userProject.ProjectIds = selectedProjectIds;

            userService.removeProjectFromUser(userProject).success(function (or) {
                if (or) {
                    if (or.result === true) {
                        SweetAlert.success($translate.instant('RemoveProjectFromUserSuccess'));
                        getProjectByUserId($scope.selectUser.id);
                        $scope.gridApiProject.selection.clearSelectedRows();
                    }
                    else {
                        SweetAlert.warning($translate.instant(or.resultMsg));
                    }
                }
            });
        };


        //assign role to project
        var assignRole = function (event, project) {
            if ($('.assign-user-box').is(":hidden")) {
                $('.assign-user-box').css('top', event.clientY + document.body.scrollTop);
                $('.assign-user-box').css('left', event.clientX - 110);
                $(".assign-user-box").show();
            } else {
                $(".assign-user-box").hide();
            }

            $(document).one("click", function () {
                $(".assign-user-box").hide();
            });
            event.stopPropagation();
            $scope.roleList = [];
            getRoleByService(project);

            //set currentProject 
            $scope.curProject = project;

        };

        //get role by serviceType
        var getRoleByService = function (project) {

            var selectedProjectIds = [];
            selectedProjectIds.push({ 'projectID': project.id, 'serviceTypeID': project.serviceTypeID });

            var userProject = {};
            userProject.UserId = $scope.selectUser.id;
            userProject.ProjectIds = selectedProjectIds;

            roleService.getRoleListByRoleTypeId(project.serviceTypeID).success(function (roleData) {

                //get project's own roles
                userService.getProjectRoles(userProject).success(function (checkedRole) {
                    $scope.roleChecked = checkedRole;

                    //checked own roles
                    roleData.forEach(function (r) {
                        if ($.inArray(r.id, $scope.roleChecked) > -1) {
                            r.isChecked = true;
                        }
                    });
                    $scope.roleList = roleData;
                });

            });
        };

        //add or remove role to project
        var setRoleToProject = function (role) {
            $log.debug(role.isChecked);
            $log.debug(role.id);

            var selectedProjectIds = [];
            selectedProjectIds.push({ 'projectID': $scope.curProject.id, 'serviceTypeID': $scope.curProject.serviceTypeID });

            var userProject = {};
            userProject.UserId = $scope.selectUser.id;
            userProject.ProjectIds = selectedProjectIds;
            userProject.RoleID = role.id;

            if (role.isChecked) {
                userProject.IsAdd = true;
                userService.operateProjectRole(userProject).success(function (or) {
                });
            }
            else {
                userProject.IsAdd = false;
                userService.operateProjectRole(userProject).success(function (or) {
                });
            }
        };

        var resources = {
            userNameRequired: $translate.instant('RequireUserName'),
            userEmailRequired: $translate.instant('RequireEmail'),
            userEmailCheck: $translate.instant('RequireCorrectEmail'),
            userOrgRequired: $translate.instant('RequireOrganization')
        };

        var validator = $('#userForm').validate({
            errorClass: "has-error",
            rules: {
                inputUserName: {
                    required: true
                },
                inputUserEmail: {
                    required: true,
                    email: true
                },
                orgName: {
                    required: true
                }
            },
            messages: {
                inputUserName: {
                    required: resources.userNameRequired
                },
                inputUserEmail: {
                    required: resources.userEmailRequired,
                    email: resources.userEmailCheck
                },
                orgName: {
                    required: resources.userOrgRequired
                }
            },
            errorPlacement: function (error, element) {
                setErrorStyle(error, element);
            }
        });

        var setErrorStyle = function (error, element) {
            if (element.hasClass('has-error')) {
                element.parent().addClass('has-error');
                error.insertAfter(element);
                error.addClass('label');
            }
            if (element[0].name === 'orgName') {
                element.parent().addClass('col-xs-9');
                element.parent().addClass('padding-left-zero');
            }
        };

        var resetErrorStatus = function () {
            validator.resetForm();
            var currentForm = $('#userForm');
            $(currentForm).find('.has-error').removeClass('has-error');
        };

        var showOperateLogPop = function () {
            $scope.isShowLog = true;
            // $('#showOperatePop').modal('show');
        };
        
        $scope.getGridHeight = function () {
            return { height: ($(".user-manage .project-list-container").height() - $(".user-manage .project-list-container .buttons").height()) + "px" };
        };

        //init page
        (function initialize() {
            $log.debug('UserManageController.ctor()...');
            $scope.userList = [];
            $scope.isAdd = false;
            //To save new role model or edit role model
            $scope.editUserModel = {};

            /*************************new variables****************************/
            $scope.selectUser = {};
            $scope.searchText = '';
            $scope.roleList = [];
            $scope.roleChecked = [];


            $(".assign-user-box").on("click", function (e) {
                e.stopPropagation();
            });

            $scope.gridOptionsProjectList = {
                rowHeight: 55,
                selectionRowHeaderWidth: 55,
                enableSorting: false,
                enableColumnMenus: false,
                enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                enableRowSelection: true,
                enableSelectAll: true,
                columnDefs: [
                  {
                      field: 'name', name: $translate.instant('ProjectNameCol'), width: '29.5%', headerCellClass: 'cell-text-align-left',
                      cellTemplate: '<div><span>{{row.entity.nameDisplay}}<span></div>'
                  },
                  {
                      field: 'organizationName', name: $translate.instant('ProjectCompanyCol'), width: '23.5%', headerCellClass: 'cell-text-align-left',
                      cellTemplate: '<div><span>{{row.entity.organizationNameDisplay}}</span></div>'
                  },
                  {
                      field: 'year', name: $translate.instant('ProjectYearCol'), width: '11.8%', headerCellClass: 'cell-text-align-center',
                      cellTemplate: '<div class="cell-text-align-center"><span>{{row.entity.yearDisplay}}</span></div>'
                  },
                  {
                      field: 'serviceTypeName', name: $translate.instant('ProjectServiceCol'), width: '17.6%', headerCellClass: 'cell-text-align-left',
                      cellTemplate: '<div><span>{{row.entity.serviceTypeName}}</span></div>'
                  },
                  {
                      name: $translate.instant('AssignRoleCol'), width: '17.6%', headerCellClass: 'cell-text-align-center', enableFiltering: false,
                      cellTemplate: '<div class="cell-text-align-center">' +
                          '<a class="assignA" href="javascript:void(0)" ng-click="grid.appScope.assignRole($event,row.entity)"> <i class="material-icons">rate_review</i></a>' +
                          '</div>'
                  }
                ],
                onRegisterApi: function (gridApi) {
                    $scope.gridApiProject = gridApi;
                }
            };

            $scope.gridOptionsAllProjectList = {
                rowHeight: 55,
                selectionRowHeaderWidth: 55,
                enableSorting: false,
                enableColumnMenus: false,
                enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
                enableRowSelection: true,
                enableSelectAll: true,
                columnDefs: [
                   {
                       field: 'index', name: $translate.instant('SequenceNoCol'), width: 90, headerCellClass: 'cell-text-align-center', enableFiltering: false,
                       cellTemplate: '<div class="cell-text-align-center"><span>{{row.entity.index}}<span></div>'
                   },
                  {
                      field: 'name', name: $translate.instant('ProjectNameCol'), width: 250, headerCellClass: 'cell-text-align-left',
                      cellTemplate: '<div><span>{{row.entity.nameDisplay}}<span></div>'
                  },
                  {
                      field: 'organizationName', name: $translate.instant('ProjectCompanyCol'), width: 200, headerCellClass: 'cell-text-align-left',
                      cellTemplate: '<div><span>{{row.entity.organizationNameDisplay}}</span></div>'
                  },
                  {
                      field: 'year', name: $translate.instant('ProjectYearCol'), width: 100, headerCellClass: 'cell-text-align-center',
                      cellTemplate: '<div class="cell-text-align-center"><span>{{row.entity.yearDisplay}}</span></div>'
                  },
                  {
                      field: 'serviceTypeName', name: $translate.instant('ProjectServiceCol'), width: 220, headerCellClass: 'cell-text-align-left',
                      cellTemplate: '<div><span>{{row.entity.serviceTypeName}}</span></div>'
                  }
                ],
                onRegisterApi: function (gridApi) {
                    $scope.gridApiAllProject = gridApi;
                }
            };


            initUser();

            //Save user info
            $scope.saveUser = saveUser;

            //Load user info by userId
            $scope.loadUser = loadUser;

            //Clear user model
            $scope.newUser = newUser;

            //Enable user 
            $scope.enableUser = enableUser;

            //Disable user
            $scope.disableUser = disableUser;

            //Select user
            $scope.selectedUser = selectedUser;

            //Assign role
            $scope.assignRole = assignRole;

            //Add project pop up
            $scope.addProjectPopUp = addProjectPopUp;

            //Add project
            $scope.addProject = addProject;

            //Remove project
            $scope.removeProject = removeProject;

            //Set role to project
            $scope.setRoleToProject = setRoleToProject;

            $scope.resetErrorStatus = resetErrorStatus;

            $scope.showOperateLogPop = showOperateLogPop;

        })();
    }
]);
infrastructureModule.directive('userManage', ['$log',
    function ($log) {
        'use strict';
        $log.debug('userManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/userManage/user-manage.html' + '?_=' + Math.random(),
            replace: true,
            scope: {},
            controller: 'UserManageController',
        };
    }
]);
infrastructureModule
    .controller('UserManageListController', ['$state', '$scope', '$log', 'userService', 'orgService', 'SweetAlert', 'projectService', 'roleService', '$translate', 'enums', 'businessUnitService', 'areaService', '$timeout', 'loginContext',
        function ($state, $scope, $log, userService, orgService, SweetAlert, projectService, roleService, $translate, enums, businessUnitService, areaService, $timeout, loginContext) {
            'use strict';

            /***********************************************************new code start*********************************************************/
            var orgTree, roleTree;
            $scope.orgTree = orgTree = {};
            $scope.roleTree = roleTree = {};

            // 机构列表树
            $scope.getOrgListToJson = function () {
                $scope.doing_async = true;

                orgService.getOrgListToJson(0).success(function (data) {


                    var filterData = [];
                    if (loginContext.userName && loginContext.userName.toLowerCase() === "simon") {
                        data.forEach(function (row) {
                            if (row && row.data.industryID === '10') {
                                filterData.push(row);
                            }
                        });
                    } else {
                        filterData = data;
                    }

                    $scope.orgTreeData = filterData;
                    $scope.doing_async = false;
                }).error(function (data) {
                    $log.debug(JSON.stringify(data));
                });
            };

            // 单击机构
            $scope.singleClickOrg = function (org) {
                if (org.selected) {
                    org.selected = false;
                    $scope.selectOrgList.splice(jQuery.inArray(org, $scope.selectOrgList), 1);
                } else {
                    org.selected = true;
                    $scope.selectOrgList.push(org);
                }

                queryOnPage();
            };

            // 事业部单选
            $scope.singleClickBusinessUnit = function (businessUnitModel) {
                if (businessUnitModel.selected) {
                    businessUnitModel.selected = false;
                    $scope.selectBusinessUnitList.splice(jQuery.inArray(businessUnitModel, $scope.selectBusinessUnitList), 1);
                } else {
                    businessUnitModel.selected = true;
                    $scope.selectBusinessUnitList.push(businessUnitModel);
                }

                queryOnPage();
            };

            // 区域单选
            $scope.singleClickArea = function (model) {
                if (model.selected) {
                    model.selected = false;
                    $scope.selectAreaList.splice(jQuery.inArray(model, $scope.selectAreaList), 1);
                } else {
                    model.selected = true;
                    $scope.selectAreaList.push(model);
                }

                queryOnPage();
            };

            // 角色单选
            $scope.singleClickRole = function (model) {
                if (!model.data.roleCategoryID) {
                    // 是角色分类,不是角色
                    return;
                }
                if (model.selected) {
                    model.selected = false;
                    $scope.selectRoleList.splice(jQuery.inArray(model, $scope.selectRoleList), 1);
                } else {
                    model.selected = true;
                    $scope.selectRoleList.push(model);
                }

                queryOnPage();
            };

            // 添加用户
            $scope.addUser = function () {
                if ($scope.userOperateType === constant.Operation.Add) {
                    $scope.userOperateType = null;
                }

                $scope.userOperateType = constant.Operation.Add;
                $scope.isUpdateUser = false;
                $scope.selectedUser = null;
            };

            // 修改用户
            $scope.updateUser = function (user, $event) {
                if ($scope.userOperateType === constant.Operation.Edit) {
                    $scope.userOperateType = null;
                }

                $scope.userOperateType = constant.Operation.Edit;
                $scope.isUpdateUser = false;
                $scope.selectedUser = { id: user.id };
                $event.stopPropagation();
            };

            // 禁用用户
            $scope.disableUser = function (user, $event) {
                if ($scope.userOperateType === constant.Operation.Disable) {
                    $scope.userOperateType = null;
                }

                $scope.userOperateType = constant.Operation.Disable;
                $scope.isUpdateUser = false;
                $scope.selectedUser = { id: user.id, userName: user.userName };
                $event.stopPropagation();
            };

            // 启用用户
            $scope.enableUsers = function (user, $event) {
                if ($scope.userOperateType === constant.Operation.Enable) {
                    $scope.userOperateType = null;
                }

                $scope.userOperateType = constant.Operation.Enable;
                $scope.isUpdateUser = false;
                $scope.selectedUser = { id: user.id, userName: user.userName };
                $event.stopPropagation();
            };

            // 角色树列表
            var getRoleTreeList = function () {
                $scope.doing_async_role = true;
                $scope.roleTreeData = [];
                roleService.getRoleTreeList().success(function (data) {
                    $scope.roleTreeData = data;
                    $scope.doing_async_role = false;
                    setRoleColor();
                    getAllUserRoleList();
                });
            };

            // 颜色模板
            var colorPanel = {

                // 颜色列表
                // yellow,orange,gold
                colorList: ['admin-color', 'role-color1', 'role-color2', 'manager-color', 'normal-color'],

                createNew: function () {
                    var colorPanelInstance = {};
                    colorPanelInstance.index = -1;
                    colorPanelInstance.getNextColor = function () {
                        if (colorPanelInstance.index >= colorPanel.colorList.length - 1) {
                            colorPanelInstance.index = 0;
                        } else {
                            colorPanelInstance.index++;
                        }

                        return colorPanel.colorList[colorPanelInstance.index];
                    }

                    return colorPanelInstance;
                }
            };

            // 颜色实例
            var colorPanelInstance = colorPanel.createNew();

            // 颜色板
            var roleColorPanel = {};
            // 设置颜色
            var setRoleColor = function () {

                if ($scope.roleTreeData && $scope.roleTreeData.length > 0) {
                    $scope.roleTreeData.forEach(function (roleType) {
                        if (roleType.children && roleType.children.length > 0) {
                            roleType.children.forEach(function (role) {
                                roleColorPanel[role.data.id] = colorPanelInstance.getNextColor();
                            });
                        }
                    });
                };
            };


            // 获取区域列表
            var getAreaList = function () {
                // body...
                areaService.getAreaList(0).success(function (data) {
                    $scope.areaList = data;
                });
            };

            // 事业部-机构树列表
            $scope.getBusinessUnitOrganizationStaticsTreeList = function () {
                $scope.selectAreaType = false;
                $scope.doing_async = true;
                $scope.areaTreeData = [];
                orgService.getBusinessUnitOrganizationStaticsTreeList().success(function (data) {
                    if (data && data.length > 0) {
                        data.forEach(function (row) {
                            row.count = row.data.organizationCount;
                            row.isShowCount = true;
                        });
                    }

                    $scope.areaTreeData = data;
                    $scope.doing_async = false;
                    return areaTree.expand_level_function();
                });
            };

            // 选中角色节点
            $scope.selectRoleNode = function (branch) {

            };

            // 选择区域节点
            $scope.selectOrgTreeNode = function (branch) {

                // branch.data
                $scope.selectOrgBranch = branch;
                queryOnPage();
            };

            $scope.goToUserDetail = function (userID) {
                $state.go('userDetail', { id: userID });
            };

            $scope.toggleUserStatus = function () {
                if ($scope.showActiveUser) {
                    $scope.showActiveUser = false;
                } else {
                    $scope.showActiveUser = true;
                }

                queryOnPage();
            };


            $scope.selectTab = function (index) {
                if (index === $scope.selectTabIndex) {
                    return;
                }

                $scope.selectTabIndex = index;
                clearStaticsAndQueryInfo();
                getAllUserRoleList();
            };

            var clearStaticsAndQueryInfo = function () {
                clearOrgTree($scope.orgTreeData);
                clearArea();
                clearBusinessUnit();
                clearRole();
                initParams();
            };

            // 获取事业部列表
            var getBusinessUnitList = function () {
                businessUnitService.getBusinessUnitList().success(function (data) {
                    data = _.filter(data, function (row) {

                        return row.isActive;
                    });
                    $scope.businessUnitList = data;
                });
            };

            var dataType = {
                isPrefixNumber: function (value) {
                    var reg = /^\d+/;
                    if (reg.test(value)) {
                        return true;
                    } else {
                        return false;
                    }
                },
                isPrefixChar: function (value) {
                    var reg = /^[a-zA-Z]+/;
                    if (reg.test(value)) {
                        return true;
                    } else {
                        return false;
                    }
                },
                isPrefixNumberOrChar: function (value) {
                    if (dataType.isPrefixNumber(value)) {
                        return true;
                    }

                    if (dataType.isPrefixChar(value)) {
                        return true;
                    }

                    return false;
                }
            }

            var sortByUserName = function (data) {
                if (data && data.length > 0) {

                    var charList = [];
                    var nocharList = [];

                    data.forEach(function (row) {
                        if (dataType.isPrefixNumberOrChar(row.userName)) {
                            row.userNameSort = row.userName;

                            if (row.userNameSort) {
                                row.userNameSort = row.userNameSort.toLowerCase();
                            }

                            charList.push(row);

                        } else {
                            nocharList.push(row);
                        }

                    });

                    charList = _.sortBy(charList, 'userNameSort');

                    nocharList = nocharList.sort(function compareFunction(param1, param2) {
                        return param1.userName.localeCompare(param2.userName, 'zh');
                    });

                    var all = _.union(charList, nocharList);
                    return all;
                }

                return data;
            };


            var getAllUserRoleList = function () {

                if ($scope.selectTabIndex === 1) {
                    roleService.getAllUserRoleList().success(function (data) {

                        data = _.filter(data, function (row) {

                            return row.userName && row.userName.toLowerCase() !== "admin";
                        });

                        if (loginContext.userName.toLowerCase() === "simon") {
                            data = _.filter(data, function (row) {
                                return row.userName !== "aaa" && row.userName !== "bbb";
                            });
                        }

                        // 先排序
                        data = sortByUserName(data);
                        $scope.originalUserRoleList = data;
                        var copy = angular.copy($scope.originalUserRoleList);
                        // $scope.userRoleList = _.filter(copy, function(row) {
                        //     return copy.status !== enums.userStatus.disabled;
                        // });
                        $scope.userRoleList = copy;

                        queryOnPage();
                    });

                } else {

                    roleService.getAllOwnUserRoleList().success(function (data) {
                        data = _.filter(data, function (row) {

                            return row.userName && row.userName.toLowerCase() !== "admin";
                        });

                        if (loginContext.userName.toLowerCase() === "simon") {
                            data = _.filter(data, function (row) {
                                return row.userName !== "aaa" && row.userName !== "bbb";
                            });
                        }

                        // 先排序
                        data = sortByUserName(data);
                        $scope.originalUserRoleList = data;
                        var copy = angular.copy($scope.originalUserRoleList);

                        // $scope.userRoleList = _.filter(copy, function(row) {
                        //     return copy.status !== enums.userStatus.disabled;
                        // });

                        $scope.userRoleList = copy;
                        queryOnPage();
                    });
                }
            };

            var renderStatics = function () {
                setOrgTreeCount($scope.orgTreeData);
                setBusinessUnitCount();
                setAreaCount();
                setRoleCount();
            };

            // 设置机构树的用户个数
            var setOrgTreeCount = function (orgTreeList) {
                // isShowCount, count
                if (orgTreeList && orgTreeList.length > 0) {
                    orgTreeList.forEach(function (row) {
                        var userList = _.filter($scope.userRoleList, function (data) {
                            return data.organizationID === row.data.id;
                        });

                        if (userList && userList.length > 0) {
                            var userNameList = _.uniq(_.pluck(userList, 'userName'));
                            row.count = userNameList.length;
                            row.isShowCount = true;
                        } else {
                            row.isShowCount = false;
                            row.count = 0;
                        }

                        setOrgTreeCount(row.children);
                    });
                }
            };

            // 清除机构树设置信息
            var clearOrgTree = function (orgTreeList) {
                if (orgTreeList && orgTreeList.length > 0) {
                    orgTreeList.forEach(function (row) {
                        row.isShowCount = false;
                        row.count = 0;
                        row.selected = false;
                        clearOrgTree(row.children);
                    });
                }
            };

            // 事业部的count
            var setBusinessUnitCount = function () {
                if ($scope.businessUnitList && $scope.businessUnitList.length > 0) {
                    for (var i = 0; i < $scope.businessUnitList.length; i++) {
                        var row = $scope.businessUnitList[i];
                        var query = _.filter($scope.userRoleList, function (user) {
                            return user.businessUnitID === row.id;
                        });

                        if (query && query.length > 0) {
                            var userNameList = _.uniq(_.pluck(query, 'userName'));
                            row.count = userNameList.length;
                            row.isShowCount = true;
                            row.count = query.length;
                        } else {
                            row.isShowCount = false;
                            row.count = 0;
                        }
                    }
                }
            };

            // 清除事业部设置信息
            var clearBusinessUnit = function () {
                if ($scope.businessUnitList && $scope.businessUnitList.length > 0) {
                    for (var i = 0; i < $scope.businessUnitList.length; i++) {
                        var row = $scope.businessUnitList[i];
                        row.isShowCount = false;
                        row.count = 0;
                        row.selected = false;
                    }
                }
            };

            // 设置区域统计
            var setAreaCount = function () {
                if ($scope.areaList && $scope.areaList.length > 0) {
                    for (var i = 0; i < $scope.areaList.length; i++) {
                        var row = $scope.areaList[i];
                        var query = _.filter($scope.userRoleList, function (user) {
                            return user.areaID === row.id;
                        });

                        if (query && query.length > 0) {
                            var userNameList = _.uniq(_.pluck(query, 'userName'));
                            row.count = userNameList.length;
                            row.isShowCount = true;
                            row.count = query.length;
                        } else {
                            row.isShowCount = false;
                            row.count = 0;
                        }
                    }
                }
            };

            // 清除区域设置信息
            var clearArea = function () {
                if ($scope.areaList && $scope.areaList.length > 0) {
                    for (var i = 0; i < $scope.areaList.length; i++) {
                        var row = $scope.areaList[i];


                        row.isShowCount = false;
                        row.count = 0;
                        row.selected = false;

                    }
                }
            };

            // 设置角色个数
            var setRoleCount = function () {
                if ($scope.roleTreeData && $scope.roleTreeData.length > 0) {
                    $scope.roleTreeData.forEach(function (roleType) {

                        // 角色分类
                        if (roleType.children && roleType.children.length > 0) {
                            roleType.children.forEach(function (role) {
                                // 角色
                                var query = _.filter($scope.userRoleList, function (data) {
                                    var roleQuery = _.filter(data.roleInfoList, function (roleInfo) {
                                        return roleInfo.id === role.data.id;
                                    });

                                    if (roleQuery && roleQuery.length > 0) {
                                        return true;
                                    } else {
                                        return false;
                                    }
                                });

                                if (query && query.length > 0) {
                                    var userNameList = _.uniq(_.pluck(query, 'userName'));
                                    role.count = userNameList.length;
                                    role.isShowCount = true;
                                    role.count = query.length;
                                } else {
                                    role.isShowCount = false;
                                    role.count = 0;
                                }
                            });
                        }
                    });
                }
            };

            // 清除角色
            var clearRole = function () {
                if ($scope.roleTreeData && $scope.roleTreeData.length > 0) {
                    $scope.roleTreeData.forEach(function (roleType) {

                        // 角色分类
                        if (roleType.children && roleType.children.length > 0) {
                            roleType.children.forEach(function (role) {
                                // 角色
                                role.isShowCount = false;
                                role.count = 0;
                                role.selected = false;
                            });
                        }
                    });
                }
            };

            // 页面级别筛选
            var queryOnPage = function () {
                $scope.disabledUsersCount = 0;
                if (!$scope.originalUserRoleList || $scope.originalUserRoleList.length === 0) {
                    return;
                }

                var result = [];

                for (var i = 0; i < $scope.originalUserRoleList.length; i++) {
                    var user = $scope.originalUserRoleList[i];

                    // 根据用户名或者邮箱做筛选
                    if ($scope.queryUser) {

                        // 转换大小写
                        var userName = user.userName ? user.userName.toLowerCase() : '';
                        var email = user.email ? user.email.toLowerCase() : '';

                        if (userName.indexOf($scope.queryUser.toLowerCase()) === -1 && email.indexOf($scope.queryUser.toLowerCase()) === -1) {
                            continue;
                        }

                        // 只显示禁用的用户
                        if (!$scope.showActiveUser && user.status != enums.userStatus.disabled) {
                            continue;
                        }
                    } else {
                        // 用户状态筛选
                        // 只显示启用的
                        if ($scope.showActiveUser && user.status === enums.userStatus.disabled) {
                            continue;
                        }

                        // 只显示禁用的用户
                        if (!$scope.showActiveUser && user.status != enums.userStatus.disabled) {
                            continue;
                        }
                    }

                    // 根据机构做筛选
                    if ($scope.selectOrgBranch && user.organizationID != $scope.selectOrgBranch.data.id) {
                        continue;
                    }

                    // 机构筛选
                    if ($scope.selectOrgList && $scope.selectOrgList.length > 0) {
                        var query = _.filter($scope.selectOrgList, function (row) {
                            return row.data.id === user.organizationID;
                        });

                        if (!query || query.length == 0) {
                            continue;
                        }
                    }

                    // 事业部筛选
                    if ($scope.selectBusinessUnitList && $scope.selectBusinessUnitList.length > 0) {
                        var query = _.filter($scope.selectBusinessUnitList, function (row) {
                            return row.id === user.businessUnitID;
                        });

                        if (!query || query.length == 0) {
                            continue;
                        }
                    }

                    // 区域
                    if ($scope.selectAreaList && $scope.selectAreaList.length > 0) {
                        var query = _.filter($scope.selectAreaList, function (row) {
                            return row.id === user.areaID;
                        });

                        if (!query || query.length == 0) {
                            continue;
                        }
                    }

                    // 角色筛选
                    if ($scope.selectRoleList && $scope.selectRoleList.length > 0) {
                        var roleIdList = _.pluck(user.roleInfoList, 'id');

                        var query = _.filter($scope.selectRoleList, function (row) {
                            return roleIdList.indexOf(row.data.id) > -1;
                        });

                        if (!query || query.length == 0) {
                            continue;
                        }
                    }

                    user.roleInfoList.forEach(function (role) {
                        role.theme = roleColorPanel[role.id];
                    });


                    result.push(user);
                }

                $scope.userRoleList = result;

                if ($scope.showActiveUser && !$scope.queryUser) {
                    var disabledUser = _.filter($scope.originalUserRoleList, function (data) {
                        return data.status === enums.userStatus.disabled;
                    });

                    if (disabledUser) {
                        $scope.disabledUsersCount = disabledUser.length;
                    }

                } else {
                    var disabledUser = _.filter($scope.userRoleList, function (data) {
                        return data.status === enums.userStatus.disabled;
                    });

                    if (disabledUser) {
                        $scope.disabledUsersCount = disabledUser.length;
                    }
                }


                // 先排序
                //sort();
                $scope.curPage = 1;

                computePager($scope.curPage);
                //creatPager($scope.userRoleList.length, $scope.curPage);
                renderStatics();
            };


            //var creatPager = function (totalPage, curPage) {
            //    $scope.creatPage = $("#userManagePager").createPage({
            //        pageCount: totalPage,
            //        current: curPage,
            //        backFn: function (p) {
            //            //单击回调方法,p是当前页码
            //            computePager(p);
            //        }
            //    });

            //    $('#userManagePager').css('display', 'inline-block');
            //};

            var computePager = function (pageIndex) {
                $scope.curPage = pageIndex;
                if ($scope.userRoleList && $scope.userRoleList.length > 0) {
                    $scope.queryResult.pageInfo.totalCount = $scope.userRoleList.length;
                    var totalPage = parseInt($scope.queryResult.pageInfo.totalCount / $scope.queryResult.pageInfo.pageSize);
                    totalPage = $scope.queryResult.pageInfo.totalCount % $scope.queryResult.pageInfo.pageSize == 0 ? totalPage : totalPage + 1;
                    $scope.queryResult.pageInfo.totalPage = totalPage;

                    $scope.creatPage = $("#userManagePager").createPage({
                        pageCount: totalPage,
                        current: $scope.curPage,
                        backFn: function (p) {
                            //单击回调方法,p是当前页码
                            computePager(p);
                        }
                    });

                    $('#userManagePager').css('display', 'inline-block');
                    getList();

                } else {
                    $scope.curPage = 1;
                    $scope.creatPage = $("#userManagePager").createPage({
                        pageCount: 0,
                        current: $scope.curPage,
                        backFn: function (p) {
                            //单击回调方法,p是当前页码
                            computePager(p);
                        }
                    });

                    $scope.queryResult.list = [];
                    $('#userManagePager').css('display', 'inline-block');
                }
            };

            // 前台分页
            var getList = function () {
                var startIndex = ($scope.curPage - 1) * $scope.queryResult.pageInfo.pageSize;
                var endIndex = $scope.curPage * $scope.queryResult.pageInfo.pageSize;


                var resultList = [];

                var userNameList = '';
                if (endIndex < $scope.userRoleList.length) {
                    resultList = $scope.userRoleList.slice(startIndex, endIndex);

                    userNameList = _.pluck(resultList, 'userName').join(',');
                } else {
                    resultList = $scope.userRoleList.slice(startIndex);
                }

                for (var i = 0; i < resultList.length; i++) {
                    var row = resultList[i];
                    if (i >= 9) {
                        row.popoverPlace = "top-right";
                    } else {
                        row.popoverPlace = 'bottom-right';
                    }
                }

                return $timeout(function () {
                    $scope.queryResult.list = resultList;
                }, 100);
            };

            var sort = function () {
                $scope.userRoleList = _.sortBy($scope.userRoleList, 'userName');
                if (!$scope.sortAsc) {
                    $scope.userRoleList = $scope.userRoleList.reverse();
                }
            };

            $scope.modifySort = function () {
                if ($scope.sortAsc) {
                    $scope.sortAsc = false;
                } else {
                    $scope.sortAsc = true;
                }

                queryOnPage();
            };


            // 查询用户事件
            $scope.queryUserEvent = function () {
                if ($scope.queryUser) {
                    clearOrgTree($scope.orgTreeData);
                    clearArea();
                    clearBusinessUnit();
                    clearRole();

                    $scope.selectOrgList = [];

                    // 选择事业部
                    $scope.selectBusinessUnitList = [];

                    $scope.selectAreaList = [];

                    // 查询角色
                    $scope.selectRoleList = [];
                }

                queryOnPage();
            };

            // 清除输入的查询用户条件
            $scope.clearQueryUser = function () {
                $scope.queryUser = '';
                queryOnPage();
            };

            $scope.showMoreOrgClick = function () {
                if ($scope.showMoreOrg) {
                    $scope.showMoreOrg = false;
                    $scope.showMoreOrgStr = $translate.instant('ShowMore');

                } else {
                    $scope.showMoreOrg = true;
                    $scope.showMoreOrgStr = $translate.instant('Packup');
                }
            };

            $scope.showMoreBusinessUnitClick = function () {
                if ($scope.showMoreBusinessUnit) {
                    $scope.showMoreBusinessUnit = false;
                    $scope.showMoreBusinessUnitStr = $translate.instant('ShowMore');

                } else {
                    $scope.showMoreBusinessUnit = true;
                    $scope.showMoreBusinessUnitStr = $translate.instant('Packup');
                }
            };

            $scope.showMoreAreaToggle = function () {
                if ($scope.showMoreArea) {
                    $scope.showMoreArea = false;
                    $scope.showMoreAreaStr = $translate.instant('ShowMore');
                } else {
                    $scope.showMoreArea = true;
                    $scope.showMoreAreaStr = $translate.instant('Packup');
                }
            };

            $scope.showMoreRoleToggle = function () {
                if ($scope.showMoreRole) {
                    $scope.showMoreRole = false;
                } else {
                    $scope.showMoreRole = true;
                }
            }

            // 添加或者编辑机构成功之后,刷新当前页面的数据
            $scope.$watch('isUpdateUser', function (newValue, oldValue) {
                if (newValue) {
                    getAllUserRoleList();
                }
            });

            $scope.selectUserRole = function (x, $event) {
                x.isOpen = true;
                $event.stopPropagation();
            }

            // 关于日志部分
            $scope.showOperateLogPop = function () {
                $scope.isShowLog = true;
            };
            var initParams = function () {
                // 机构默认显示
                $scope.showMoreOrg = true;
                $scope.showMoreOrgStr = $translate.instant('ShowMore');

                // 区域默认简化显示
                $scope.showMoreArea = false;
                $scope.showMoreAreaStr = $translate.instant('ShowMore');

                // 事业部默认简化显示
                $scope.showMoreBusinessUnit = false;
                $scope.showMoreBusinessUnitStr = $translate.instant('ShowMore');
                // 角色默认简化显示
                $scope.showMoreRole = false;
                // 选择机构
                $scope.selectOrgList = [];

                // 选择事业部
                $scope.selectBusinessUnitList = [];

                // 查询用户
                $scope.queryUser = '';

                // 查询区域
                $scope.selectAreaList = [];

                // 查询角色
                $scope.selectRoleList = [];

                // 取第几页数据
                $scope.curPage = 1;

                $scope.sortAsc = true;

                $scope.isShowBoard = true;

                $scope.showActiveUser = true;

                $scope.templateUrl = 'userRolePopoverTemplate.html';
            };

            $scope.getUserBodyHeight = function () {
                var right_container = $('.right-container').height();
                var tool_bar = $('.tool-bar').height();
                var height = right_container - tool_bar - 53;

                return {
                    height: height + 'px'
                }
            };



            var getUserPermission = function () {

                var list = [];

                var userManageTemp = constant.adminPermission.infrastructure.userManage;
                list.push(userManageTemp.addCode);
                list.push(userManageTemp.editCode);

                $scope.$root.checkUserPermissionList(list).success(function (data) {
                    $scope.hasAddPermission = data[userManageTemp.addCode];
                    $scope.hasEditPermission = data[userManageTemp.editCode];
                });
            };

            $scope.stopPropagation = function ($event) {
                $event.stopPropagation();
            };

            //init page
            (function initialize() {
                $log.debug('UserManageController.ctor()...');

                $scope.hasAddPermission = false;

                $scope.hasEditPermission = false;

                // 默认选择可访问tab
                $scope.selectTabIndex = 0;
                initParams();
                getUserPermission();
                // 用户编辑框ID
                $scope.getOrgListToJson();
                getRoleTreeList();
                getBusinessUnitList();
                getAreaList();


                $scope.queryResult = {
                    pageInfo: {
                        totalCount: 0,
                        pageSize: 12,
                        list: []
                    }
                };
            })();
        }
    ]);

infrastructureModule.directive('userManageList', ['$log',
    function ($log) {
        'use strict';
        $log.debug('userManage.ctor()...');

        return {
            restrict: 'E',
            templateUrl: '/app/admin/infrastructure/userManageList/user-manage-list.html' + '?_=' + Math.random(),
            replace: true,
            scope: {},
            controller: 'UserManageListController',
        };
    }
]);