commonModule.
controller('addExistRoleModalController', ['$scope', '$log', '$translate', 'uiGridConstants', '$location', '$timeout', '$interval', '$filter', 'SweetAlert', 'roleService', 'userService', 'permissionService',
    function ($scope, $log, $translate, uiGridConstants, $location, $timeout, $interval, $filter, SweetAlert, roleService, userService, permissionService) {

        $scope.searchValue = "";

        var modalSelector = '#addRoleModal';
        $scope.allowUncheck = false;

        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 showModal = function () {
            // $scope.selectedRoleList = [];
            // $scope.selectedRoleList = ['1a22c719-9751-4a7c-a3b5-6bf333567970', '468AAF7D-268B-4ADF-A331-FF762C950EC6'];

            $scope.originalRoleList = angular.copy($scope.selectedRoleList);

            getDataList();
            initPermissionByRoleIDList($scope.selectedRoleList);
            $(modalSelector).modal("show");
        };
        $scope.$watch('operateType', function (newValue, oldValue) {
            if (newValue) {
                reset();
                if (newValue == constant.Operation.Add) {
                    showModal();
                } else if (newValue == constant.Operation.Edit) {

                }
            }
        });

        var reset = function () {
            $scope.searchValue = '';
        };

        $(".addRoleModal").on("hidden.bs.modal", function () {
            $scope.operateType = null;
        });

        $scope.closeModal = function () {
            $scope.operateType = null;
        };

        $scope.Save = function () {
            //返回用户ID列表
            //console.log(JSON.stringify($scope.selectedRoleList));
            $scope.operateType = null;
            $scope.isUpdate = true;
            $(modalSelector).modal("hide");
        };


        var setSelectItems = function (roleData) {

            if ($scope.selectedRoleList && $scope.selectedRoleList.length > 0) {
                for (var i = 0; i < roleData.length; i++) {

                    if ($scope.selectedRoleList.indexOf(roleData[i].id) > -1) {
                        roleData[i].selected = true;
                        roleData[i].expanded = true;
                    }

                    if (roleData[i].subRoles && roleData[i].subRoles.length > 0) {
                        setSelectItems(roleData[i].subRoles);
                    }
                }
            }

            return roleData;
        };

        var getDataList = function () {

            roleService.getRoleListByServiceGroup().success(function (roleData) {
                if (roleData) {
                    var data = setSelectItems(roleData);
                    $scope.roleTreeViewData = data;
                }
            });
        };

        var initPermissionByRoleIDList = function (roleIDList)
        {
            permissionService.getDevTreePermissionsByRoleIDList(roleIDList, constant.serviceType.VAT).success(function (data) {
                if (data) {
                    $scope.permissionTreeViewData = data;
                }
            });

        };

        var loadPermissionByRoleID = function (roleID) {
            permissionService.getDevTreePermissionsByRoleID(roleID, constant.serviceType.VAT).success(function (data) {
                if (data) {
                    $scope.permissionTreeViewData = data.permissionDevTreeList;
                }
            });
        };

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

        var loadPermissionTree = function () {
            $scope.permissionTreeViewOptions = {
                bindingOptions: {
                    dataSource: 'permissionTreeViewData',
                    searchValue: 'searchValue'
                },
                dataStructure: "plain",
                selection: {
                    mode: "single"
                },
                loadPanel: {
                    enabled: true
                },
                scrolling: {
                    mode: "virtual"
                },
                keyExpr: "id",
                // parentIdExpr: "pLevel",

                showRowLines: true,
                showColumnLines: true,
                rowAlternationEnabled: true,
                showBorders: true,
                noDataText: $translate.instant('NoDataText'),
                selectAllText: $translate.instant('SelectAll')
            };
        };

        var loadRoleTree = function () {
            $scope.roleTreeViewOptions = {
                bindingOptions: {
                    dataSource: 'roleTreeViewData',
                    searchValue: 'searchValue'
                },
                selection: {
                    mode: "multiple"
                },

                loadPanel: {
                    enabled: true
                },
                scrolling: {
                    mode: "virtual"
                },
                keyExpr: "id",
                parentIdExpr: "parentID",
                showRowLines: true,
                showColumnLines: true,
                expandAllEnabled: true,
                rowAlternationEnabled: true,
                expandedRowKeys: [1],
                showBorders: true,
                noDataText: $translate.instant('NoDataText'),
                selectAllText: $translate.instant('SelectAll'),
                displayExpr: 'name',  //显示的属性名称,默认为text
                itemsExpr: 'subRoles',  //子层的数组名称,默认为items
                //scrollDirection:'vertical',  //Accepted Values: 'vertical' | 'horizontal' | 'both'
                selectNodesRecursive: true,  //级联选择
                showCheckBoxesMode: 'normal', //Accepted Values: 'none' | 'normal' | 'selectAll'
                onItemSelectionChanged: function (obj, element, model, node) {

                    populateSelectedRole(obj.itemData);
                },
                onInitialized: function (e) {
                    $scope.widgetInstance = e.component;
                },
                //点击行,选中
                onItemClick: function (e) {

                    loadPermissionByRoleID(e.itemData.id);
                },
                onItemRendered: function (e) {

                    if ($scope.allowUncheck) { return;}

                    var originalRoleList = $scope.originalRoleList;

                    if (e && e.itemData && originalRoleList && originalRoleList.length>0) {
                    
                        if (originalRoleList.indexOf(e.itemData.id) > -1) {
                            e.itemElement.closest('li.dx-treeview-node').find('.dx-checkbox-checked').addClass("dx-state-disabled");
                        }
                        if (e.itemData.isRoleCategory && e.itemData.subRoles.length > 0)
                        {
                            var subRoles = e.itemData.subRoles;
                            var subRoleId = _.pluck(subRoles, 'id');
                            var hasCheckedAll = true;
                            for (var i = 0; i < originalRoleList.length; i++) {
                                var hasFind = _.find(subRoleId, function (item) {
                                    return item.id == originalRoleList[i].id;
                                });
                                if (!hasFind) {
                                    hasCheckedAll = false;
                                    break;
                                }
                            }
                            if (hasCheckedAll)
                            {
                                e.itemElement.closest('li.dx-treeview-node').find('.dx-checkbox-checked').addClass("dx-state-disabled");
                            }
                        } 
                    }
                }
            };

        };
        //构造选中的角色list
        var populateSelectedRole = function (itemData) {

            var itemIndex = -1;

            $.each($scope.selectedRoleList, function (index, item) {
                if (item.id === itemData.id) {
                    itemIndex = index;
                    return false;
                }
            });

            if (itemData.selected && itemIndex === -1) {
                if (itemData.isRoleCategory) {
                    //选择父级角色分类
                    itemData.subRoles.forEach(function (item) {
                        if ($scope.selectedRoleList.indexOf(item.id) < 0) {
                            $scope.selectedRoleList.push(item.id);
                        }
                    });
                } else {
                    //选择叶子节点角色
                    $scope.selectedRoleList.push(itemData.id);
                }

            } else if (!itemData.selected) {
                //$scope.selectedRoleList.splice(itemIndex, 1);
                //$scope.selectedRoleList.forEach(function (item) {
                //    $scope.widgetInstance.selectItem(item);
                //});
                if (!itemData.isRoleCategory) {
                    //叶子节点取消选中情况
                    $.each($scope.selectedRoleList, function (index, item) {
                        if (item === itemData.id) {
                            $scope.selectedRoleList.splice(index, 1);
                            return false;
                        }
                    });
                } else {

                    var cloneSelectedRoleList = angular.copy($scope.selectedRoleList);
                    var removeIndexList = [];

                    $.each(cloneSelectedRoleList, function (index, item) {
                        itemData.subRoles.forEach(function (x) {
                            if (item === x.id) {
                                removeIndexList.push(index);
                            }
                        });
                    });

                    //从后往前删除
                    for (var i = removeIndexList.length - 1; i >= 0; i--) {
                        $scope.selectedRoleList.splice(removeIndexList[i], 1);
                    }

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

                    if (!$scope.allowUncheck) {
                        $scope.originalRoleList.forEach(function (item) {
                            $scope.widgetInstance.selectItem(item);
                        });
                    }

                }
            }

            $scope.selectedItemList = [];
            $scope.roleTreeViewData.forEach(function (item) {
                var subRoles = _.filter(item.subRoles, function (item) {
                    return $scope.selectedRoleList.indexOf(item.id) > -1;
                });

                subRoles.forEach(function (row) {
                    $scope.selectedItemList.push(row);
                });
            });


        };

        (function initialize() {
            $log.debug('addExistUserModalController.ctor()...');

            loadRoleTree();
            loadPermissionTree();
        
            //  showModal();
        }) ();

}
]);