crmApp.controller("RolesController", RolesController);

crmApp.controller("UserRoleMatrixController", UserRoleMatrixController);

crmApp.controller("UserRoleDetailController", UserRoleDetailController);

function RolesController($scope, $window, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $filter, $compile, UserSI) {
    var vm = this;

    vm.isActiveOptions = [{ Text: 'Yes', Value: true },
                         { Text: 'No', Value: false }];
    vm.dtInstance = {};
    vm.listing = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
  

    vm.init = function () {
        //var model = { LookupCode: "JenisPelanggan" };
        //AdminSI.getLookupParam(model).then(function (r) {
        //    if (r.status === 200) {
        //        vm.list = r.data;
        //    }
        //});
        UserSI.getUserRoleListing().then(function (r) {
            if (r.status === 200) {
                vm.listing = r.data;
                console.log(vm.listing);
            }
        });
    };
    vm.dtColumnDefs = [
        DTColumnDefBuilder.newColumnDef(0),
        DTColumnDefBuilder.newColumnDef(1),
        DTColumnDefBuilder.newColumnDef(2)
                                  .withTitle('Created Date Time').withOption('type', 'date'),
        DTColumnDefBuilder.newColumnDef(3),
        DTColumnDefBuilder.newColumnDef(4)
                                  .withTitle('Last Updated Date Time').withOption('type', 'date'),
        DTColumnDefBuilder.newColumnDef(5)
    ];
    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers');
        //.withDisplayLength(10);
       // .withOption('order', [0, 'desc']);

    vm.addNewRoles = function () {
        vm.openNewTab('/User/Roles/Detail/');
    };

    vm.openNewTab = function (url) {
        window.open(url, '_blank');
    }

    vm.openCurrentWindow = function (url) {
        window.open(url, '_target');
    }

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.openCurrentWindow('/User/Roles/Detail/' + id);
    };

    vm.save = function (myForm) {
    }
}

function UserRoleMatrixController($scope, $window, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $filter, $compile, UserSI) {
    var vm = this;

    vm.init = function () {

        UserSI.getUserRoleMatrix().then(function (r) {
            if (r.status === 200) {
                vm.Matrix = r.data;
                for (var key in vm.Matrix.TaskCategory) {
                    vm.Matrix.TaskCategory[key].IsCollapse = true;
                }
                console.log(vm.Matrix);
            }
        });
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");
        window.open('/User/Roles/Detail/' + id, '_target');
    };

    vm.bindMatrixValue = function (functionalRoleID, functionalTaskID) {
        m = $filter('filter')(vm.Matrix.UserRoleTasks, { FunctionalTaskID: functionalTaskID, FunctionalRoleID: functionalRoleID }, true);
        return m.length == 0 ? false : true;
    }
    vm.addNewRoles = function () {
        vm.openNewTab('/User/Roles/Detail/');
    };
    vm.openNewTab = function (url) {
        window.open(url, '_blank');
    }

    vm.openCurrentWindow = function (url) {
        window.open(url, '_target');
    }
}

function UserRoleDetailController($scope, $window, $filter, $q, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $filter, $compile, UserSI, GeneralService, AntiForgeryService) {
    var vm = this;
    vm.FunctionalRoleID = $window.functionalRoleID == '' ? '0' : $window.functionalRoleID;
    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;

    var constHierarchySeksyen = 34;
    var constHierarchyJabatan = 35;
    var constHierarchyCawangan = 36;
    var constHierarchyUnit = 37;

    vm.init = function () {
        tabAction("01");
        vm.showdetail = false;
        vm.showValidationMsg = false;
        vm.showTasksValidationMsg = false;
        vm.DuplicateNameMsg = "* Current Role name has been used. Please try another.";
        vm.showDuplicateNameMsg = false;
        vm.showUnitRequiredMsg = false;
        vm.showUserRequiredMsg = false;
        vm.showdetail = false;
        vm.showUserdetail = false;
        vm.ResetHierarchy();
        vm.ResetUserHierarchy();
        // TODO : Temporarily hardcoded for testing
        //vm.Unit = {
        //    UnitID: ,
        //    UnitName: 'UBB',
        //    BranchName: 'ALOR SETAR'
        //};
        vm.Unit = {
            UnitID: 402,
            UnitName: 'CKHT Pungutan',
            BranchName: 'PETALING JAYA'
        };

        vm.SelectedTimbalan = "";
        vm.SelectedJabatan = "";
        vm.SelectedCawangan = "";
        vm.SelectedUnits = "";
        vm.SelectedTimbalanUser = "";
        vm.SelectedJabatanUser = "";
        vm.SelectedCawanganUser = "";
        vm.SelectedUnitsUser = "";

        vm.SeksyenEnabled = true;
        vm.JabatanEnabled = true;
        vm.SeksyenUserEnabled = true;
        vm.JabatanUserEnabled = true;

        GetUserGroupHierarcyOptions();

        var functionalRoleID = vm.FunctionalRoleID;
        UserSI.getUserRoleDetails(functionalRoleID).then(function (r) {
            if (r.status === 200) {
                vm.Roles = r.data;
                for (var key in vm.Roles.TaskCategory) {
                    vm.Roles.TaskCategory[key].IsCollapse = true;
                }
                console.log(vm.Roles);
                // Set default value for new page
                if (vm.FunctionalRoleID == 0) { vm.Roles.IsActive = true; }
            }
        });

    };

    vm.MainHeaderCheckBoxOnChecked = function (isChecked) {
        // Loop to check task header for the children
        angular.forEach(vm.Roles.TaskCategory, function (obj) {
            obj.SelectAll = isChecked;
            vm.TaskCheckBoxOnChecked(obj.LookupParamID, true, isChecked);
        });
    };

    vm.TaskCheckBoxOnChecked = function (id, isHeader, isChecked) {
        if (isChecked == null) isChecked = false;
        // Get task category by id
        var selectedTask = $.grep(vm.Roles.TaskCategory, function (obj) {
            return obj.LookupParamID == id;
        })[0];

        if (selectedTask) {
            if (isHeader) {
                // To select/ deselect all childs checkbox
                angular.forEach(selectedTask.FunctionalTasks, function (obj) {
                    obj.Selected = isChecked;
                });
            } else {
                // to uncheck Select all if one ofthe childs checkbox is uncheck
                var intCount = 0;
                angular.forEach(selectedTask.FunctionalTasks, function (obj) {
                    intCount += obj.Selected ? 1 : 0;
                });
                if (intCount == selectedTask.FunctionalTasks.length) {
                    selectedTask.SelectAll = true;
                }
                else {
                    selectedTask.SelectAll = false;
                }
            }
        }
    }

    vm.addMember = function () {
        if (validateAddMember()) {
            console.log(vm.AssignTo);
            console.log(vm.AssignToUser);
            var member = {
                DisplayName: vm.AssignToUser.DisplayName,
                UnitID: vm.AssignTo.ID,
                UserProfileID: vm.AssignToUser.UserProfileID
            };
            var userUnit = $filter('filter')(vm.Roles.RoleUnits, { UnitID: member.UnitID });
            if (userUnit && userUnit != null && userUnit.length > 0) {

                // search for existing user
                var userExisted = $filter('filter')(userUnit[0].RoleMembers, { UserProfileID: member.UserProfileID }, true);
                if (userExisted.length > 0) {
                    swal("Failed", "This user has been added into the role unit", "error");
                } else {
                    // add into existing unit
                    userUnit[0].RoleMembers.push(member);
                }
            }
            else {
                var newUnit = {
                    DisplayBranchName: (vm.AssignTo.AdditionalInfo!=null)?'('+vm.AssignTo.AdditionalInfo+')':'',
                    IsHide: false,
                    UnitID: vm.AssignTo.ID,
                    UnitName: vm.AssignTo.DisplayName,
                    RoleMembers: [member],
                    AdditionalInfo: vm.AssignTo.AdditionalInfo
                };
                vm.Roles.RoleUnits.push(newUnit);
            }
            console.log(vm.Roles.RoleUnits);
            // clear fields
            vm.reset();
        }
    };

    vm.reset = function () {
        vm.AssignTo = null;
        vm.AssignToUser = null;
        vm.ResetHierarchy();
        vm.showdetail = false;
        vm.ResetUserHierarchy();
        vm.showUserdetail = false;
    }

    //Unit and filter
    vm.seksyenChange = function (selectedTimbalan) {
        vm.filteredWorkflowAssignToJabatanOption = [];
        if (selectedTimbalan != null) {
            var m = $filter('filter')(vm.WorkflowAssignToJabatanOption, { ParentUnitID: parseInt(selectedTimbalan) }, true);
            vm.filteredWorkflowAssignToJabatanOption = [];
            if (m != undefined && m.length != 0) {
                vm.filteredWorkflowAssignToJabatanOption = m;
            }
        }
    };
    vm.seksyenUserChange = function (selectedTimbalanUser) {
        vm.filteredWorkflowAssignToJabatanUserOption = [];
        if (selectedTimbalanUser != null) {
            var m = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, { ParentUnitID: parseInt(selectedTimbalanUser) }, true);
            vm.filteredWorkflowAssignToJabatanUserOption = [];
            if (m != undefined && m.length != 0) {
                vm.filteredWorkflowAssignToJabatanUserOption = m;
            }

            SearchUserByUnitID(selectedTimbalanUser);
        }
        else { vm.AssignToUser = "";}
    };

    vm.jabatanChange = function (SelectedJabatan) {
        //enable upper hierarchy
        vm.SeksyenEnabled = true;

        vm.filteredWorkflowAssignToCawanganOption = [];

        if (SelectedJabatan != null) {
            //disable upper hierarchy
            vm.SeksyenEnabled = false;
            var m = $filter('filter')(vm.WorkflowAssignToCawanganOption, { ParentUnitID: parseInt(SelectedJabatan) }, true);

            if (m != undefined && m.length != 0) {

                vm.filteredWorkflowAssignToCawanganOption = m;
            }
            //SearchUserByUnitID(SelectedJabatan);

        }
    };

    vm.jabatanUserChange = function (SelectedJabatanUser) {
        //enable upper hierarchy
        vm.SeksyenUserEnabled = true;

        vm.filteredWorkflowAssignToCawanganUserOption = [];

        if (SelectedJabatanUser != null) {
            //disable upper hierarchy
            vm.SeksyenEnabled = false;
            var m = $filter('filter')(vm.WorkflowAssignToCawanganUserOption, { ParentUnitID: parseInt(SelectedJabatanUser) }, true);

            if (m != undefined && m.length != 0) {

                vm.filteredWorkflowAssignToCawanganUserOption = m;
            }
            SearchUserByUnitID(SelectedJabatanUser);

        } else { vm.AssignToUser = ""; }
    };

    vm.cawanganChange = function (SelectedCawangan) {
        //enable upper hierarchy
        vm.SeksyenEnabled = true;
        vm.JabatanEnabled = true;

        vm.filteredWorkflowAssignToUnitOption = [];

        if (SelectedCawangan != null) {
            //disable upper hierarchy
            vm.SeksyenEnabled = false;
            vm.JabatanEnabled = false;

            var m = $filter('filter')(vm.WorkflowAssignToUnitOption, { ParentUnitID: parseInt(SelectedCawangan) }, true);

            if (m != undefined && m.length != 0) {
                vm.filteredWorkflowAssignToUnitOption = m;
            }
            //SearchUserByUnitID(SelectedCawangan);
        }
    };

    vm.cawanganUserChange = function (SelectedCawanganUser) {
        //enable upper hierarchy
        vm.SeksyenUserEnabled = true;
        vm.JabatanUserEnabled = true;

        vm.filteredWorkflowAssignToUnitUserOption = [];

        if (SelectedCawanganUser != null) {
            //disable upper hierarchy
            vm.SeksyenUserEnabled = false;
            vm.JabatanUserEnabled = false;

            var m = $filter('filter')(vm.WorkflowAssignToUnitUserOption, { ParentUnitID: parseInt(SelectedCawanganUser) }, true);

            if (m != undefined && m.length != 0) {
                vm.filteredWorkflowAssignToUnitUserOption = m;
            }
            SearchUserByUnitID(SelectedCawanganUser);
        } else { vm.AssignToUser = ""; }
    };

    vm.unitChange = function (SelectedUnits) {
        //SearchUserByUnitID(SelectedUnits);
    };

    vm.unitUserChange = function (SelectedUnitsUser) {
        SearchUserByUnitID(SelectedUnitsUser);
    };

    vm.SearchJabatan = function (query) {
        vm.JabatanOption = [];
        if (query.length > 1) {
            vm.JabatanOption = vm.WorkflowAssignToJabatanOption;
        }
    }

    vm.SearchJabatanUser = function (query) {
        vm.JabatanUserOption = [];
        if (query.length > 1) {
            vm.JabatanUserOption = vm.WorkflowAssignToJabatanUserOption;
        }
    }

    vm.SearchCawanganUser = function (query) {
        vm.CawanganUserOption = [];
        if (query.length > 1) {
            vm.CawanganUserOption = vm.WorkflowAssignToCawanganUserOption;
        }
    }

    vm.SearchCawangan = function (query) {
        vm.CawanganOption = [];
        if (query.length > 1) {
            vm.CawanganOption = vm.WorkflowAssignToCawanganOption;
        }
    }

    vm.SearchUserByName = function (query) {
        vm.UserResultOption = [];
        vm.loading = true;

        if (query.length > 2) {
            UserSI.searchUserByName(query).then(function (r) {
                if (r.data != null) {
                    var m = r.data;
                    if (m.length != 0) {
                        vm.UserResultOption = m;
                    }
                } vm.loading = false;
            });
        }

    }


    vm.SearchUnitByName = function (query) {
        vm.UnitResultOption = [];
        vm.loading = true;

        if (query.length > 2) {
            UserSI.searchUnitByName(query).then(function (r) {
                if (r.data != null) {
                    var m = r.data;
                    if (m.length != 0) {
                        vm.UnitResultOption = m;
                    }
                } vm.loading = false;
            });
        }
    }
    function SearchUserByUnitID(selectedUnitID) {
        if (selectedUnitID) {
            vm.NoUserMessage = false;
            vm.UserResultOption = [];
            vm.AssignToUser = "";
            UserSI.searchUserByUnitID(selectedUnitID).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        vm.UserResultOption = r.data;

                        if (vm.UserResultOption.length == 0) {
                            vm.NoUserMessage = true;
                        }
                    }
                }
            });
        }
    }

    // Drop Down List for Other Option(Group,User OR All)
    vm.chooseOtherGroupOrUser = function () {
        vm.ResetHierarchy();
    }
    // Drop Down List for Other Option (Group,User OR All)

    //Open and Hide More Option for Other
    vm.ShowFilterOption = function () {
        if (!vm.showdetail) {
            vm.showdetail = true;
        }
        else {
            //vm.ResetHierarchy();
            vm.showdetail = false;
        }
    }

    vm.ShowFilterUserOption = function () {
        if (!vm.showUserdetail) {
            vm.showUserdetail = true;
        }
        else {
            //vm.ResetUserHierarchy();
            vm.showUserdetail = false;
        }
    }

    vm.ResetHierarchy = function () {
        vm.SeksyenEnabled = true;
        vm.JabatanEnabled = true;
        vm.NoUserMessage = false;

        vm.SelectedTimbalan = "";
        vm.SelectedJabatan = "";
        vm.SelectedCawangan = "";
        vm.SelectedUnits = "";
        vm.AssignTo = "";

        vm.filteredWorkflowAssignToJabatanOption = [];
        vm.filteredWorkflowAssignToCawanganOption = [];
        vm.filteredWorkflowAssignToUnitOption = [];
        vm.UnitResultOption = [];

        vm.JabatanOption = [];
        vm.CawanganOption = [];
        vm.UnitOption = [];
    }

    vm.ResetUserHierarchy = function () {
        vm.SeksyenUserEnabled = true;
        vm.JabatanUserEnabled = true;
        vm.NoUserMessage = false;

        vm.SelectedTimbalanUser = "";
        vm.SelectedJabatanUser = "";
        vm.SelectedCawanganUser = "";
        vm.SelectedUnitsUser = "";
        vm.AssignToUser = "";

        vm.filteredWorkflowAssignToJabatanUserOption = [];
        vm.filteredWorkflowAssignToCawanganUserOption = [];
        vm.filteredWorkflowAssignToUnitUserOption = [];
        vm.UserResultOption = [];

        vm.JabatanUserOption = [];
        vm.CawanganUserOption = [];
        vm.UnitOption = [];
    }

    function GetUserGroupHierarcyOptions() {
        UserSI.getUserGroupHierarcyOptions().then(function (r) {
            if (r.status === 200) {
                if (r.data) {
                    vm.WorkflowAssignToSeksyenOption = r.data["WorkflowAssignToSeksyenOption"];
                    vm.WorkflowAssignToJabatanOption = r.data["WorkflowAssignToJabatanOption"];
                    vm.WorkflowAssignToCawanganOption = r.data["WorkflowAssignToCawanganOption"];
                    vm.WorkflowAssignToUnitOption = r.data["WorkflowAssignToUnitOption"];

                    vm.WorkflowAssignToSeksyenUserOption = r.data["WorkflowAssignToSeksyenOption"];
                    vm.WorkflowAssignToJabatanUserOption = r.data["WorkflowAssignToJabatanOption"];
                    vm.WorkflowAssignToCawanganUserOption = r.data["WorkflowAssignToCawanganOption"];
                    vm.WorkflowAssignToUnitUserOption = r.data["WorkflowAssignToUnitOption"];
                }
            }
        });
    }

    vm.SelectHierarchy = function () {
        vm.UnitResultOption = [];
        m = [];

        if (vm.SelectedUnits != "" && vm.SelectedUnits != null) {
            m = $filter('filter')(vm.WorkflowAssignToUnitOption, { ID: vm.SelectedUnits }, true);
        }
        else if (vm.SelectedCawangan != "" && vm.SelectedCawangan != null) {
            m = $filter('filter')(vm.WorkflowAssignToCawanganOption, { ID: vm.SelectedCawangan }, true);
        }
        else if (vm.SelectedJabatan != "" && vm.SelectedJabatan != null) {
            m = $filter('filter')(vm.WorkflowAssignToJabatanOption, { ID: vm.SelectedJabatan }, true);
        }

        else if (vm.SelectedTimbalan != "" && vm.SelectedTimbalan != null) {
            m = $filter('filter')(vm.WorkflowAssignToSeksyenOption, { ID: vm.SelectedTimbalan }, true);
        }

        if (m && (m.length != 0)) {

            vm.UnitResultOption = m;
            vm.AssignTo = m[0];
            console.log('Assign To ',vm.AssignTo);
        }

    }

    function validateAddMember() {
        if (!vm.AssignTo || vm.AssignTo == null) {
            vm.showUnitRequiredMsg = true;
        }
        else { vm.showUnitRequiredMsg = false; }
        if (!vm.AssignToUser || vm.AssignToUser == null) {
            vm.showUserRequiredMsg = true;
        }
        else { vm.showUserRequiredMsg = false; }

        if (vm.showUnitRequiredMsg || vm.showUserRequiredMsg) {
            return false;
        }
        else {
            return true;
        }
    }

    vm.editUnit = function (selectedUnit) {
        vm.Unit.UnitID = selectedUnit.UnitID;
        vm.Unit.UnitName = selectedUnit.UnitName;
        vm.Unit.BranchName = selectedUnit.BranchName;

     
        if (selectedUnit.HierarchyType == constHierarchySeksyen) {
            vm.ResetHierarchy();
            vm.SelectedTimbalan = selectedUnit.UnitID;
            vm.seksyenChange(selectedUnit.UnitID);
        } else if (selectedUnit.HierarchyType == constHierarchyJabatan) {
            vm.ResetHierarchy();
            vm.SelectedTimbalan = selectedUnit.UnitID;
            vm.seksyenChange(selectedUnit.UnitID);
        }
        vm.AssignTo = {
            ID: selectedUnit.UnitID,
            ParentUnitID: selectedUnit.BranchID,
            AssignToType: 20,
            DisplayName: selectedUnit.UnitName,
            HierarchyType: selectedUnit.HierarchyType,
            AdditionalInfo: selectedUnit.AdditionalInfo
        };
      
    };

    vm.deleteUser = function (selectedUser) {
        swal({
            title: "Are you sure you want to delete this member (" + selectedUser.DisplayName + ")?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: true,
            closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                var userUnit = $filter('filter')(vm.Roles.RoleUnits, { UnitID: selectedUser.UnitID }, true)[0];

                //Remove unit if only one member exits
                if (userUnit.RoleMembers.length == 1) {
                    angular.forEach(vm.Roles.RoleUnits, function (obj, i) {
                        if (obj.UnitID == userUnit.UnitID) {
                            vm.Roles.RoleUnits.splice(i, 1);
                        }
                    });
                } else {
                    angular.forEach(userUnit.RoleMembers, function (obj, i) {
                        if (obj.UserProfileID == selectedUser.UserProfileID) {
                            userUnit.RoleMembers.splice(i, 1);
                        }
                    });
                }
                $scope.$apply();
            }
        });

    };

    vm.deleteUnit = function (selectedUnit) {

        swal({
            title: "Are you sure you want to delete this unit? This will delete all members for the selected unit (" + selectedUnit .UnitName+ ").",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: true,
            closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                angular.forEach(vm.Roles.RoleUnits, function (obj, i) {
                    if (obj.UnitID == selectedUnit.UnitID) {
                        vm.Roles.RoleUnits.splice(i, 1);
                    }
                });
                $scope.$apply();
            }
        });


    }

    function validateForm(roleForm) {
        var isDirty = roleForm.$dirty;
        var validRegarding = true;
        //if (roleForm.$valid) {
        if (!vm.Roles.RoleName) {
            vm.showValidationMsg = true;
        } else { vm.showValidationMsg = false; }
        //} else {
        //    vm.showValidationMsg = true;
        //}

        return !vm.showValidationMsg;
    }

    function showValidationAlert() {
        swal("Failed", "Please fill in all the required fields!", "error");
    }

    function validateTasks() {
        var taskSelected = 0;
        angular.forEach(vm.Roles.TaskCategory, function (obj) {
            var intCount = 0;
            intCount = $filter('filter')(obj.FunctionalTasks, { Selected: true }).length;
            taskSelected += intCount;
        });

        if (taskSelected == 0 && vm.Roles.IsActive == true)
        { vm.showTasksValidationMsg = true; }
        else { vm.showTasksValidationMsg = false; }

        return !vm.showTasksValidationMsg;
    }

    function getChangeHistorybyForm(form) {
        vm.ChangesHistory = [];
        angular.forEach(form, function (value, key) {

            if (key[0] == '$') return;

            var displayName = $(document.getElementById(key)).data('displayfield');
            // var takeLabelText = $(document.getElementById(key)).data('takelabeltext');

            if ($(document.getElementById(key))[0].tagName == 'INPUT' && $(document.getElementById(key))[0].type == 'radio') {
                newvalue = $(document.getElementById(key))[0].parentElement.innerText.trim();
            }
            var i = key.toString().indexOf(':');
            vm.ChangesHistory.push({
                ID: vm.Roles.FunctionalRoleID,
                FieldName: key,
                DisplayName: displayName
            });
        });
        console.log(vm.ChangesHistory);
    }

    vm.FindDuplicateRoleName = function () {
        var model = {
            RoleName: vm.Roles.RoleName.trim(),
            FunctionalRoleID: vm.FunctionalRoleID
        }
        UserSI.findDuplicateRoleName(model).then(function (r) {
            if (r.status === 200) {
                if (r.data == true) {
                    vm.showDuplicateNameMsg = true;
                }
                else {
                    vm.showDuplicateNameMsg = false;
                }
            }
        });
    };

    function returnResultPromise() {
        var result = null;
        var deferred = $q.defer();
        deferred.reject('');
        result = deferred.promise;
        return result;
    }

    vm.SaveRoleDetails = function (roleForm) {
        var result = null;
        // getChangeHistorybyForm(roleForm);
        var isDirty = true;// roleForm.$dirty;
        if (isDirty) {
            if (validateForm(roleForm) && validateTasks()) {
                vm.Roles.RoleName = vm.Roles.RoleName.trim();

                // Check for duplicate role name
                vm.FindDuplicateRoleName()
                if (vm.showDuplicateNameMsg) {
                    swal("Failed", vm.DuplicateNameMsg, "error");
                    result = returnResultPromise();
                }
                if (result== null) {
                    var data = UserSI.saveRoleDetails(vm.Roles);
                    result = data;
                    data.then(function (r) {
                        if (r.status === 200) {
                            swal({
                                title: GeneralService.SaveMessage.Title,
                                text: GeneralService.SaveMessage.Text,
                                type: "success",
                                timer: 2500,
                                showConfirmButton: true
                            }, function () {
                                vm.redirectTo('/user/roles/detail/' + r.data);
                            });
                        }
                        else {
                            swal("Failed", r.data, "error");
                        }
                    });
                }
            } else {
                showValidationAlert();
                result = returnResultPromise();
            }
        } else {
            swal("Failed", "No Changes has been made!", "error");
            result = returnResultPromise();
        }

        return result;
    };

    vm.SearchUser = function (query) {

        var keyword = query.trim();

        if (keyword.length < 3) {
            vm.UsersOption = [];
            return;
        }

        vm.loading = true;
        var data = {
            Keyword: query
        }

        UserSI.searchUsersByKeyword(data).then(function (r) {
            if (r.data != null) {
                var m = r.data;
                vm.UsersOption = m;
            } vm.loading = false;
        });

    };

    vm.SelectUser = function (selectedItem) {
        vm.SelectedUser = selectedItem;
    };

    vm.redirectTo = function (url) {

        $window.beforeUnloadCanceled = true;
        $window.location.href = url;
    }


    vm.tabAction = tabAction;
    function tabAction(cls) {
        reset();

        switch (cls) {
            case '01':
                tabProfile01Click();
                break;
            case '02':
                tabProfile02Click();
                break;
        }
    }
    //Profile Tab 01
    vm.tabProfile01Click = tabProfile01Click;
    function tabProfile01Click() {
        vm.tabProfile01Active = true;

    }

    //Profile Tab 02
    vm.tabProfile02Click = tabProfile02Click;
    function tabProfile02Click() {
        vm.tabProfile02Active = true;

    }

    vm.expanding_property = {
        field: "name",
        displayName: "Functional Tasks"
    };

    vm.gridConfig = {
        iconCollapse: "fa fa-angle-down",
        iconExpand: "fa fa-angle-right",
        highlightSelected: true
    };

    vm.gridConfig1 = angular.extend({}, {
        checkboxTree: true
    }, vm.gridConfig);

    vm.dummyTree = [{
        "id": 1,
        "name": "Tax Payer Profile",
        "expanded": true,
        "children": [{
            "id": 11,
            "name": "View Tax Payer- VIP Own Branch",
            "children": [],
            "selected": true
        }, {
            "id": 13,
            "name": "View Tax Payer- VIP All Branch",
            "children": [],
            "selected": true
        }, {
            "id": 14,
            "name": "View Tax Payer- Biasa Own Branch",
            "children": [],
            "selected": true
        }, {
            "id": 15,
            "name": "View Tax Payer-Biasa All Branch",
            "children": [],
            "selected": true
        }],
        "selected": true
    }];

    var data = [{
        "id": 1,
        "name": "Tax Payer Profile",
        "children": [{
            "id": 11,
            "name": "View Tax Payer- VIP Own Branch",
            "selected": true
        }, {
            "id": 13,
            "name": "View Tax Payer- VIP All Branch",
            "selected": true
        }, {
            "id": 14,
            "name": "View Tax Payer- Biasa Own Branch"
        }, {
            "id": 15,
            "name": "View Tax Payer-Biasa All Branch"
        }]
    }, {
        "id": 20,
        "name": "Activity Profile",
        "children": [{
            "id": 165,
            "name": "View Activity Profile"
        }, {
            "id": 1665,
            "name": "View Activity Profile - Social Media Section"
        }]
    }];
    vm.data = [];
    vm.dummyTreeData = angular.copy(data);
    vm.dummyTreeData1 = angular.copy(data);

    function reset() {
        vm.tabProfile01Active = false;
        vm.tabProfile02Active = false;
    }
}