commonModule.
controller('addExistUserModalController', ['$scope', '$log', '$translate', 'uiGridConstants', 'ackUibModal', '$timeout', '$interval', '$filter', 'SweetAlert', 'dimensionService', 'userService',
    function ($scope, $log, $translate, uiGridConstants, ackUibModal, $timeout, $interval, $filter, SweetAlert, dimensionService, userService) {

        $scope.gridInstance = null;
        var modalSelector = '#addUserModal';
        $scope.allowUncheck = false;

        //弹框服务
        $scope.modalService = {
            userModal: {
                open: function () {
                    $scope.userModalInstance = ackUibModal($scope, 'addExistUserModal.html', 'add-exist-user-modal-wrap', '.add-exist-user-modal-wrap', 'static',
                        function () {
                        $scope.operateType = null;
                    });
                    $scope.userModalInstance.open();
                },
                close: function () {
                    $scope.isUpdate = true;
                    $scope.userModalInstance.close();
                },
                cancel: function () {
                    $scope.userModalInstance.cancel();
                },
            }
        }

        var showModal = function () {
            //$scope.selectedKeyItems = ['90154bc8-be4a-46f2-ac08-84c1cdf8b381', 'f525f1f1-749b-4dc8-9d86-72d9014156a3', 'b5050352-e095-4d5a-bd74-dced354d063e', '8be3ce87-1193-4b35-8fda-2d5a191ce341']
            $scope.selectedUserList = [];
            $scope.originalList = angular.copy($scope.selectedKeyItems);
            getUserList();
            $scope.modalService.userModal.open();
        };

        $scope.$watch('operateType', function (newValue, oldValue) {
            if (newValue) {
              
                if (newValue == constant.Operation.Add) {
                    showModal();
                } else if (newValue == constant.Operation.Edit) {

                }
            }
        });

        $scope.closeModal = function () {
            $scope.modalService.userModal.cancel();
        };

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

        //将角色列表换成逗号分隔
        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 setUserCheckStatus = function (selectedKeyItems)
        {
            if (selectedKeyItems && selectedKeyItems.length > 0) {
                var selectItems = [];

                selectedKeyItems.forEach(function (key) {
                    var temp = _.find($scope.userDataGridSource, function (item) {
                        return item.userID === key;
                    });
                    if (temp && temp != null) {
                        selectItems.push(temp);
                    }
                });

                $timeout(function () {
                    $scope.gridInstance.clearSelection();
                    var key = $scope.gridInstance.keyOf(selectItems);
                    $scope.gridInstance.selectRows(key, true);
                }, 100);
            }
            else {
                $timeout(function () {
                    $scope.gridInstance.clearSelection();
                }, 100);
            }
        };
        var getUserList = function () {

            userService.getAllUserRoleList(constant.serviceType.VAT).success(function (data) {
                if (data) {
                     
                    data.forEach(function (row) {
                        var roleNames = _.pluck(row.roleInfoList, 'name');
                        row.roleInfoStr = roleNames.join(constant.comma);
                    });

                    $scope.userDataGridSource = data;

                    //console.log('$scope.selectedKeyItems : ' + $scope.selectedKeyItems);
                    setUserCheckStatus($scope.selectedKeyItems);
                }
            });
        };


        var loadUserDatagrid = function () {
            $scope.userDataGridOptions = {
                bindingOptions: {
                    dataSource: 'userDataGridSource',
                },
                selection: {
                    mode: "multiple",
                     showCheckBoxesMode: 'always'
                },
                allowColumnResizing: true,
                columnAutoWidth: true,
                columns: [
                        {
                            dataField: "userName",
                            caption: $translate.instant('PUserName'),
                            width:100
                        },
                        {
                            dataField: "roleInfoStr",
                            caption: $translate.instant('Role'),
                            width: 250
                        },
                        {
                            dataField: "organizationName",
                            caption: $translate.instant('PCompany'),
                            width: 200
                        }
                ],

                loadPanel: {
                    enabled: true
                },
                scrolling: {
                    mode: "virtual"
                },
                //showCheckBoxesMode: 'always',
                //keyExpr: "userID",
                showRowLines: true,
                showColumnLines: true,
                rowAlternationEnabled: true,
               
                showBorders: true,
                sorting: {
                    mode: "none"
                },
                noDataText: $translate.instant('NoDataText'),
                searchPanel: {
                    placeholder: $translate.instant('Search'),
                    width: 567,
                    visible: true
                },
                onInitialized: function (e) {
                    $scope.gridInstance = e.component;
                },
                onSelectionChanged: function (selectedItems,a,b,c) {

                    //整个集合 List
                    var rowList = selectedItems.selectedRowsData;
                    $scope.selectedUserList = rowList;
                    //只有orgID List
                    var keyList = $.map(rowList, function (value) { return value.userID });
                    $scope.selectedKeyItems = keyList;

                    ////追加原始的
                    //if ($scope.selectedKeyItems.length == 0) {
                    //    setUserCheckStatus($scope.originalList);
                    //}

                },
                onContentReady: function (e, container)
                {
                    if (!$scope.allowUncheck) {
                        var $checkBox = $('.dx-header-row .dx-checkbox').first();
                        $checkBox.on('dxclick', function (e) {
                            var isChecked = $checkBox.dxCheckBox('instance').option('value');
                            if (!isChecked) {    //追加原始角色选中
                                if ($scope.originalList && $scope.originalList.length > 0) {
                                    setUserCheckStatus($scope.originalList);
                                }
                            }
                        });
                    }
                },
                onRowPrepared: function (e) {
                    //只有不允许取消的时候才disabled
                    if (!$scope.allowUncheck) {
                        if (e && e.data) {
                            if ($scope.originalList.indexOf(e.data.userID) > -1) {
                                e.rowElement.addClass("dx-state-disabled");
                            }
                        }
                    }
                }
            };

        };

        (function initialize() {
            $log.debug('addExistUserModalController.ctor()...');
        
            loadUserDatagrid();
            //showModal();
        })();
    }
]);