crmApp.controller("UserRequestController", UserRequestController);

function UserRequestController($scope, $window, $q, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $filter, $compile, UserSI, AntiForgeryService, GeneralService) {
    var vm = this;
    var DefaultUnitID = "";
    var AdditionalUnitID = "";
    var ManagerID = "";
    vm.SeksyenEnabledDocUnit = true;
    vm.JabatanEnabledDocUnit = true;
    vm.SeksyenEnabledAdditionalUnit = true;
    vm.JabatanEnabledAdditionalUnit = true;
    vm.showNoManagerValidationMsg = false;

    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;

    vm.Validation = {
    };
    vm.Validation.Email = GeneralService.Validation.Email;
    vm.Validation.EmailMsg = GeneralService.Validation.EmailMsg;

    vm.showUserdetail = false;
    vm.showPengurusAdditionUnitDetail = false;
    vm.changesHistory = [];
    vm.userList = {};
    vm.DefaultrolesID = [];
    vm.AdditionalrolesID = [];
    vm.showRoleNoRecord = false;
    vm.showAdditionalRoleNoRecord = false;
    vm.DefaultrolesIDRemove = [];
    vm.DefaultrolesName = [];
    vm.AdditionalRolesName = [];
    vm.additionalUnitandRoles = [];
    vm.RemoveUnitAndRoles = [];
    vm.AddNewDefaultRoleID = [];
    vm.actWorkflowAssignToCawanganOption = [];
    vm.UserResultOption = [];
    vm.UserManagerResultOption = [];
    vm.ChangeAdditionUserManager = [];
    vm.RemoveAdditionUserManager = [];

    vm.SelectedAdditionalUnitID = "";
    vm.SelectedAdditionalUnitAndRoles = [];
    vm.AddAdditionalRolesID = [];
    vm.AdditionalRolesIDRemove = [];
    vm.AdditionalForUnitID = "";
    vm.AdditionalUnitID = [];
    vm.SeksyenUserEnabled = false;
    vm.SeksyenUserAdditionEnabled = false;
    vm.JabatanUserEnabled = false;
    vm.JabatanUserAdditionEnabled = false;
    vm.CawanganUserEnabled = false;
    vm.CawanganUserAdditionEnabled = false;
    vm.UserRequestshow = true;
    vm.duplicateLoginData = [];
    vm.lstAdditionUserManager = [];
    vm.lstRemoveAdditionUserManager = [];
    var newStatus =  53;
    var PendingReviewStatus = 54;
    var PendingApprovalStatus = 55;
    var ApprovedStatus = 56;
    var RejectedStatus = 57;
    var ClosedStatus = 58;
    var Active = 63;
    var InActive = 64;
    var Dormant = 65;
    var Expiry = 66;
    var CancelRequest = 68;
    vm.showExpiryDate = false;
    vm.showDormanDate = false;
    var constChangePengurusUnit = 'Sila kemaskini pengurus unit yang baharu.';
    var AssignToSystem = 'Sistem';

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();
    var IsSentForApproval = null;

    today = mm + '/' + dd + '/' + yyyy;
    
    vm.UserProfileID = $window.userProfileID;

    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                         { Text: 'Tidak', Value: false }];

    vm.init = function () {

        // datepicker
        vm.dateFromMinDate = null;
        vm.dateFromMaxDate = null;
        vm.buttonBarObj = $scope.ButtonBar;
        console.log(vm.buttonBarObj);
        vm.dateFromOptions = {
            minDate: (new Date()).setHours(0, 0, 0, 0), // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            dateDisabled: false,
            startingDay: 1
        };

        vm.dateToMinDate = null;
        vm.dateToMaxDate = null;
        vm.dateToOptions = {
            minDate: (new Date()).setHours(0, 0, 0, 0), // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            dateDisabled: false,
            startingDay: 1,
            closed: function (args) {
                vm.closedArgs = args;
                alert('datepicker closed');
            }
        };

        // Expiry date        
        vm.expiryDateOptions = {
            minDate: (new Date()).setHours(0, 0, 0, 0), // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            startingDay: 1
        };

        getDDLOptions().then(function (data) {

            for (var key in data) {
                vm[key] = data[key];
            }

            vm.WorkflowAssignToSeksyenOptionDocUnit = data["WorkflowAssignToSeksyenOption"];
            vm.WorkflowAssignToJabatanOptionDocUnit = data["WorkflowAssignToJabatanOption"];
            vm.WorkflowAssignToCawanganOptionDocUnit = data["WorkflowAssignToCawanganOption"];
            vm.WorkflowAssignToUnitOptionDocUnit = data["WorkflowAssignToUnitOption"];

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

            vm.WorkflowAssignToSeksyenOptionAdditionalUnit = data["WorkflowAssignToSeksyenOption"];
            vm.WorkflowAssignToJabatanOptionAdditionalUnit = data["WorkflowAssignToJabatanOption"];
            vm.WorkflowAssignToCawanganOptionAdditionalUnit = data["WorkflowAssignToCawanganOption"];
            vm.WorkflowAssignToUnitOptionAdditionalUnit = data["WorkflowAssignToUnitOption"];

            vm.Jawatan = data["UserJawatan"];


            if (vm.UserProfileID > 0) {
                vm.showdetailRoles = true;
                vm.showdetailAdditionalRoles = true;
                UserSI.getUserRequestProfileDetailByID(vm.UserProfileID).then(function (r) {
                    if (r.status == 200) {
                        vm.userList = r.data;
                        if (vm.userList != null) {
                            vm.userList.CreatedDateTime = $filter('date')(vm.userList.CreatedDateTime, $scope.DateTimeFormat);
                        }

                        if (vm.userList.WorkFlowCatatanHistory) {
                            for (i = 0; i < vm.userList.WorkFlowCatatanHistory.length; i++)
                                vm.userList.WorkFlowCatatanHistory[i].Catatan = vm.userList.WorkFlowCatatanHistory[i].Catatan.replace(/\n/g, '<br/>');
                        }

                        if (vm.userList.WFStatusID == ApprovedStatus) {
                            //if (vm.userList.IsSendApproval == false && (vm.userList.UserProfileID > 0 || vm.userList.UserProfileID !=null))
                            if (vm.userList.UserProfileID > 0 || vm.userList.UserProfileID != null) {
                                vm.userList.DiagihkanDateTime = new Date(vm.userList.LastUpdatedDateTime);
                            }
                            vm.userList.AssignToName = AssignToSystem;
                        }

                        if (vm.userList.UserWFActiveCondition != null)
                        {
                            if (vm.userList.UserWFActiveCondition.DormantDateFrom != null && vm.userList.UserWFActiveCondition.DormantDateTo != null)
                            {
                                vm.DateFrom = new Date(vm.userList.UserWFActiveCondition.DormantDateFrom);
                                vm.DateTo = new Date($filter('date')(vm.userList.UserWFActiveCondition.DormantDateTo, 'MM/dd/yyyy'));//new Date(vm.userList.UserWFActiveCondition.DormantDateTo);
                            }
                            else if(vm.userList.UserWFActiveCondition.DormantDateFrom != null && vm.userList.UserWFActiveCondition.DormantDateTo == null)
                            {
                                vm.DateFrom = new Date(vm.userList.UserWFActiveCondition.DormantDateFrom);
                            }

                            if (vm.userList.UserWFActiveCondition.ExpiryDate != null)
                            {
                                vm.TarikhLuput = new Date(vm.userList.UserWFActiveCondition.ExpiryDate);
                            }
                            vm.userList.ActiveCondition = vm.userList.UserWFActiveCondition.ActiveCondition
                             
                            if(vm.userList.UserWFActiveCondition.ActiveCondition == Dormant)
                            {
                                vm.showDormanDate = true;
                                vm.showExpiryDate = false;
                            }
                            else if (vm.userList.UserWFActiveCondition.ActiveCondition == Expiry)
                            {
                                vm.showExpiryDate = true;
                                vm.showDormanDate = false;
                            }
                            else
                            {
                                vm.showExpiryDate = false;
                                vm.showDormanDate = false;
                            }
                        }

                        if (vm.userList.UserWorkFlow != null)
                        {
                            if(vm.userList.IsCurrentUserLogin)
                            {
                                if (vm.userList.WFStatusID == newStatus)
                                {
                                    vm.isRequestlogin = true;
                                    vm.isReviewLogin = false;
                                    vm.isApprovedLogin = false;
                                }
                                else if (vm.userList.WFStatusID == PendingReviewStatus)
                                {
                                    vm.isRequestlogin = false;
                                    vm.isReviewLogin = true;
                                    vm.isApprovedLogin = false;
                                    vm.isCancelRequest = false;
                                }
                                else if (vm.userList.WFStatusID == PendingApprovalStatus) {
                                    vm.isRequestlogin = false;
                                    vm.isReviewLogin = false;
                                    vm.isApprovedLogin = true;
                                }
                                else if (vm.userList.WFStatusID == RejectedStatus)
                                {
                                    vm.isRequestlogin = true;
                                    vm.isReviewLogin = false;
                                    vm.isApprovedLogin = false;
                                    vm.isCancelRequest = true;
                                }

                                vm.IsCurrentLogin = 1;
                                
                            }
                            else {
                                if (vm.userList.IsOtherUserLogin) {

                                }
                                else {
                                 if (vm.userList.WFStatusID == PendingReviewStatus)
                                    {
                                        vm.isRequestlogin = false;
                                        vm.isReviewLogin = false;
                                        vm.isApprovedLogin = false;
                                        vm.isCancelRequest = false;
                                    }
                                    //vm.isRequestlogin = false;
                                 
                                }
                                vm.IsCurrentLogin = 0;
                            }

                        }
                        else
                        {
                            if(vm.userList.WFStatusID == null)
                            {
                                vm.isRequestlogin = true;
                                vm.isReviewLogin = false;
                                vm.isApprovedLogin = false;
                                vm.isCancelRequest = false;
                            }
                            else if (vm.userList.WFStatusID == ClosedStatus)
                            {
                                vm.isRequestlogin = true;
                                vm.isReviewLogin = false;
                                vm.isApprovedLogin = false;
                                vm.isCancelRequest = false;
                            }
                            else if (vm.userList.WFStatusID != ApprovedStatus)
                            {
                                vm.isRequestlogin = true;
                                vm.isReviewLogin = false;
                                vm.isApprovedLogin = false;
                                vm.isCancelRequest = true;
                            }

                        }

                        //vm.UserByName = vm.userList.UserByName;
                        vm.UserManagerResultOption = r.data.UserProfileManager;
                        vm.UserResultOption = r.data.UserProfileManager;
                        vm.AdditionalUnitIDMultiple = vm.userList.AdditionalUnitIDMultiple;
                        vm.editTitle = "Kemaskini Pengguna Baru"

                        if (vm.userList.UnitID != null && vm.userList.UnitID > 0) {
                            DefaultUnitID = vm.userList.UnitID.toString();
                        }
                        else {
                            DefaultUnitID = "";
                        }

                        if (DefaultUnitID != "") {
                            m = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, { ID: DefaultUnitID }, true);
                            if (m.length > 0) {
                                //vm.editing.DefaultUnitID = m[0].Value;
                                vm.DefaultUnitID = m[0];
                            }
                            else {
                                m = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, { ID: DefaultUnitID }, true);
                                if (m.length > 0) {
                                    vm.DefaultUnitID = m[0];
                                }
                                else {
                                    m = $filter('filter')(vm.WorkflowAssignToJabatanOptionDocUnit, { ID: DefaultUnitID }, true);
                                    if (m.length > 0) {
                                        vm.DefaultUnitID = m[0];
                                    }
                                    else {
                                        m = $filter('filter')(vm.WorkflowAssignToSeksyenOptionDocUnit, { ID: DefaultUnitID }, true);
                                        if (m.length > 0) {
                                            vm.DefaultUnitID = m[0];
                                        }
                                        else {
                                            vm.userList.UnitID = "";
                                        }

                                    }

                                }

                            }
                        }
                        else {
                            vm.userList.UnitID = "";
                        }

                        if (vm.userList.ManagerUserProfileID != null && vm.userList.ManagerUserProfileID > 0) {
                            ManagerID = vm.userList.ManagerUserProfileID;
                        }
                        else {
                            vm.NoUserMessage = true;
                            vm.ManagerProfileID = "No user found in this group";
                            //vm.UserResultOption.length = 0;
                            vm.ManagerProfileID = "";

                        }

                        if (ManagerID != "") {
                            vm.ManagerProfileID = vm.UserResultOption[0];
                        }
                        //else {
                        //    vm.NoUserMessage = true;
                        //    if (vm.UserResultOption == null)
                        //    {
                        //        vm.UserResultOption.length == 0
                        //    }
                            
                        //    vm.ManagerProfileID = "No user found in this group";
                        //}

                        if (vm.userList.UserFunctionRoles.length > 0) {
                            vm.DefaultrolesName = [];
                            angular.forEach(vm.userList.UserFunctionRoles, function (value, key) {

                                m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: value.FunctionalRoleID }, true);
                                if (m.length > 0) {
                                    vm.DefaultrolesName.push(m[0]);
                                    vm.DefaultrolesID.push(m[0].FunctionalRoleID);
                                }
                                else {
                                    vm.DefaultrolesName = "";

                                }
                            })
                        }
                        //else {
                        //    vm.showRoleNoRecord = true;
                        //    vm.ManagerProfileID = "";
                        //}

                        //For Addition Role ID
                        if (vm.userList.UserAdditionalFunctionRoles.length > 0) {
                            vm.AdditionalUnitIDMultiple = vm.AdditionalUnitIDMultiple.split(',');

                            angular.forEach(vm.AdditionalUnitIDMultiple, function (value, key) {

                                m = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, { ID: value }, true);
                                if (m.length > 0) {
                                    //vm.editing.DefaultUnitID = m[0].Value;
                                    vm.AdditionalUnitID = m[0];
                                }
                                else {
                                    m = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, { ID: value }, true);
                                    if (m.length > 0) {
                                        vm.AdditionalUnitID = m[0];
                                    }
                                    else {
                                        m = $filter('filter')(vm.WorkflowAssignToJabatanOptionDocUnit, { ID: value }, true);
                                        if (m.length > 0) {
                                            vm.AdditionalUnitID = m[0];
                                        }
                                        else {
                                            m = $filter('filter')(vm.WorkflowAssignToSeksyenOptionDocUnit, { ID: value }, true);
                                            if (m.length > 0) {
                                                vm.AdditionalUnitID = m[0];
                                            }
                                            else {
                                                vm.userList.AdditionalUnitID = "";
                                            }

                                        }

                                    }

                                }

                                vm.additionalUnitandRoles.push(vm.AdditionalUnitID);

                                b = $filter('filter')(vm.userList.UserAdditionalFunctionRoles, { UnitID: parseInt(value) }, true);
                                if (b.length > 0) {
                                    vm.additionalUnitandRoles[key].UnitRoleFunctionalID = b;

                                }
                                else {

                                }


                                //For Each Unit Additional Role Manager
                                if (vm.userList.AdditionalUnitUserProfileManager.length > 0) {
                                    c = $filter('filter')(vm.userList.AdditionalUnitUserProfileManager, { UnitID: parseInt(value) }, true);
                                    if (c.length > 0) {
                                        vm.additionalUnitandRoles[key].ManagerID = c[0].UserProfileID;
                                        vm.additionalUnitandRoles[key].ManagerName = c[0].DisplayName;
                                    }
                                    else
                                    {
                                        vm.additionalUnitandRoles[key].ManagerName = '-';
                                    }

                                }
                                else {

                                    vm.additionalUnitandRoles[key].ManagerName = '-';
                                    vm.AdditionalUnitID = ""
                                }

                            })


                            vm.AdditionalUnitID = ""
                        }
                        else {
                            vm.AdditionalUnitID = ""
                        }

           
                    }
                });
            }
            else {
                vm.userList = {};
                vm.editTitle = "Permohonan Pengguna Baru"
                vm.userList.ActiveCondition = Active;
                vm.userList.WFUserProfileID = 0;
                vm.showdetailRoles = false;
                vm.showdetailAdditionalRoles = false;
                vm.AdditionalUnitID = "";
                vm.isRequestlogin = true;
                vm.isReviewLogin = false;
                vm.userList.WFStatusDesc = "-";
               
                //For Default Unit(predefined for unit name based on the requestor)
                var b = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                if (b.length > 0 && b != undefined)
                {
                        var a = $filter('filter')(vm.WorkflowAssignToSeksyenOptionDocUnit, { ID: b[0].SeksyenID.toString() }, true);
                        if (a != undefined && a.length != 0) {
                            vm.WorkflowAssignToSeksyenOptionDocUnit = a;
                            // vm.actWorkflowAssignToJabatanOptionDocUnit = m;
                            vm.SelectedTimbalanDocUnit = a[0].ID;
                            vm.SeksyenEnabledDocUnit = false;
                        }
                        
                        var c = $filter('filter')(vm.WorkflowAssignToJabatanOption, { ID: b[0].JabatanID.toString() }, true);
                        if (c != undefined && c.length != 0) {
                            vm.actWorkflowAssignToJabatanOptionDocUnit = c;
                            vm.SelectedJabatanDocUnit = c[0].ID;
                            vm.JabatanEnabledDocUnit = false;
                        }

                        var d = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, { ID: b[0].CawanganID.toString() }, true);
                        {
                            if(d.length > 0 && d !=undefined)
                            {
                                vm.actWorkflowAssignToCawanganOptionDocUnit = d;
                                vm.SelectedCawanganDocUnit = d[0].ID;
                                vm.CawanganEnabledDocUnit = false;

                                var e = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, { ParentUnitID: parseInt(vm.SelectedCawanganDocUnit) }, true);

                                if (e != undefined && e.length != 0) {
                                    vm.actWorkflowAssignToUnitOptionDocUnit = e;
                                    vm.SelectedUnitsDocUnit = b[0].ID;
                                }
                            }
                        }
                        
                    //var m = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, { ID: $window.objUser.Unit.Branch.UnitID.toString() }, true);
                    //{
                    //    if(m.length > 0 && m !=undefined)
                    //    {
                    //        vm.actWorkflowAssignToCawanganOptionDocUnit = m;
                    //        vm.SelectedCawanganDocUnit = m[0].ID;
                    //        vm.CawanganEnabledDocUnit = false;
                    //    }
                    //}

                    //var m = $filter('filter')(vm.WorkflowAssignToJabatanOption, { ID: $window.objUser.Unit.Branch.UnitID.toString() }, true);

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

                    //    var a = $filter('filter')(vm.WorkflowAssignToSeksyenOptionDocUnit, { ID: m[0].ParentUnitID.toString() }, true);
                    //    if (a != undefined && a.length != 0) {
                    //        vm.WorkflowAssignToSeksyenOptionDocUnit = a;
                    //        // vm.actWorkflowAssignToJabatanOptionDocUnit = m;
                    //        vm.SelectedTimbalanDocUnit = a[0].ID;
                    //        vm.SeksyenEnabledDocUnit = false;

                    //    }

                    //    vm.actWorkflowAssignToJabatanOptionDocUnit = m;
                    //    vm.SelectedJabatanDocUnit = m[0].ID;
                    //    vm.JabatanEnabledDocUnit = false;

                    //    var b = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                    //    if (b != undefined && b.length != 0) {
                    //        vm.actWorkflowAssignToCawanganOptionDocUnit = b;
                    //        vm.SelectedCawanganDocUnit = b[0].ID;
                    //        vm.CawanganEnabledDocUnit = false;

                    //        var m = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, { ParentUnitID: parseInt(vm.SelectedCawanganDocUnit) }, true);

                    //        if (m != undefined && m.length != 0) {
                    //            vm.actWorkflowAssignToUnitOptionDocUnit = m;
                    //        }
                    //    }
                    //}
                }
                else 
                {
                    var a = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                    if(a.length > 0 && a !=undefined)
                    {
                        var b = $filter('filter')(vm.WorkflowAssignToSeksyenOptionDocUnit, { ID: a[0].SeksyenID.toString() }, true);
                            if (b != undefined && b.length != 0) {
                                vm.WorkflowAssignToSeksyenOptionDocUnit = b;
                                vm.SelectedTimbalanDocUnit = b[0].ID;
                                vm.SeksyenEnabledDocUnit = false;
                            }

                            var c = $filter('filter')(vm.WorkflowAssignToJabatanOption, { ID: a[0].JabatanID.toString() }, true);
                            if(c !=undefined && c.length > 0)
                            {
                                vm.actWorkflowAssignToJabatanOptionDocUnit = c;
                                vm.SelectedJabatanDocUnit = c[0].ID;
                                vm.JabatanEnabledDocUnit = false;
                            }

                            var d = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, { ParentUnitID: parseInt(vm.SelectedJabatanDocUnit) }, true);
                            if(d.length > 0 && d !=undefined)
                            {
                                vm.actWorkflowAssignToCawanganOptionDocUnit = d;
                                vm.SelectedCawanganDocUnit = a[0].ID;
                                vm.CawanganEnabledDocUnit = true;
                            }

                            var e = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, { ParentUnitID: parseInt(vm.SelectedCawanganDocUnit) }, true);

                            if (e != undefined && e.length != 0) {
                                vm.actWorkflowAssignToUnitOptionDocUnit = e;
                            }

                            //vm.SelectedUnitsDocUnit = false;
                            //vm.actWorkflowAssignToUnitOptionDocUnit = [];
                    }
                    else
                    {
                        var a = $filter('filter')(vm.WorkflowAssignToJabatanOption, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                        if(a.length > 0 && a !=undefined)
                        {
                            var b = $filter('filter')(vm.WorkflowAssignToSeksyenOptionDocUnit, { ID: a[0].SeksyenID.toString() }, true);
                            if (b != undefined && b.length != 0) {
                                vm.WorkflowAssignToSeksyenOptionDocUnit = b;
                                vm.SelectedTimbalanDocUnit = b[0].ID;
                                vm.SeksyenEnabledDocUnit = false;
                            }

                            var c = $filter('filter')(vm.WorkflowAssignToJabatanOption, { ParentUnitID: parseInt(vm.SelectedTimbalanDocUnit) }, true);
                            if (c != undefined && c.length > 0) {
                                vm.actWorkflowAssignToJabatanOptionDocUnit = c;
                                vm.SelectedJabatanDocUnit = a[0].ID;
                                vm.JabatanEnabledDocUnit = true;
                            }

                            var d = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, { ParentUnitID: parseInt(vm.SelectedJabatanDocUnit) }, true);
                            if (d.length > 0 && d != undefined) {
                                vm.actWorkflowAssignToCawanganOptionDocUnit = d;
                                //vm.SelectedCawanganDocUnit = d[0].ID;
                                vm.CawanganEnabledDocUnit = true;
                            }
                        }
                        else
                        {
                            var a = $filter('filter')(vm.WorkflowAssignToSeksyenOptionDocUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                            if(a.length > 0 && a!=undefined)
                            {
                                vm.SelectedTimbalanDocUnit = a[0].ID;
                                vm.SeksyenEnabledDocUnit = true;

                                var b = $filter('filter')(vm.WorkflowAssignToJabatanOption, { ParentUnitID: parseInt(vm.SelectedTimbalanDocUnit) }, true);
                                if(b.length > 0 && b!=undefined)
                                {
                                    vm.actWorkflowAssignToJabatanOptionDocUnit = b;
                                   // vm.SelectedJabatanDocUnit = a[0].ID;
                                    vm.JabatanEnabledDocUnit = true;
                                }
                            }

                        }
                    }
                }

                //For Additional Unit(predefined for unit name based on the requestor
                var a = $filter('filter')(vm.WorkflowAssignToUnitOptionAdditionalUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                if (a.length > 0 && a != undefined)
                {
                    var b = $filter('filter')(vm.WorkflowAssignToSeksyenOptionAdditionalUnit, { ID: a[0].SeksyenID.toString() }, true);
                    if (b != undefined && b.length != 0) {
                        vm.WorkflowAssignToSeksyenOptionAdditionalUnit = b;
                        vm.SelectedTimbalanAdditionalUnit = b[0].ID;
                        vm.SeksyenEnabledAdditionalUnit = false;

                    }

                    var c = $filter('filter')(vm.WorkflowAssignToJabatanOptionAdditionalUnit, { ID: a[0].JabatanID.toString() }, true);
                    if(c.length > 0 && c !=undefined)
                    {
                        vm.WorkflowAssignToJabatanOptionAdditionalUnit = c;
                        vm.SelectedJabatanAdditionalUnit = c[0].ID;
                        vm.JabatanEnabledAdditionalUnit = false;
                    }

                    var d = $filter('filter')(vm.WorkflowAssignToCawanganOptionAdditionalUnit, { ID: a[0].CawanganID.toString() }, true);
                    if(d.length > 0 && d !=undefined)
                    {
                        vm.actWorkflowAssignToCawanganOptionAdditionalUnit = d;
                        vm.SelectedCawanganAdditionalUnit = d[0].ID;
                        vm.CawanganEnabledAdditionalUnit = false;
                    }

                    var e = $filter('filter')(vm.WorkflowAssignToUnitOptionAdditionalUnit, { ParentUnitID: parseInt(vm.SelectedCawanganDocUnit) }, true);

                    if (e != undefined && e.length != 0) {
                        vm.actWorkflowAssignToUnitOptionAdditionalUnit = e;
                        vm.SelectedUnitsAdditionalUnit = a[0].ID;
                    }

                }
                else
                {
                    var a = $filter('filter')(vm.WorkflowAssignToCawanganOptionAdditionalUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                    if(a.length > 0 && a!=undefined)
                    {
                        var b = $filter('filter')(vm.WorkflowAssignToSeksyenOptionAdditionalUnit, { ID: a[0].SeksyenID.toString() }, true);
                        if (b != undefined && b.length != 0) {
                            vm.WorkflowAssignToSeksyenOptionAdditionalUnit = b;
                            vm.SelectedTimbalanAdditionalUnit = b[0].ID;
                            vm.SeksyenEnabledAdditionalUnit = false;

                        }

                        var c = $filter('filter')(vm.WorkflowAssignToJabatanOptionAdditionalUnit, { ID: a[0].JabatanID.toString() }, true);
                        if (c.length > 0 && c != undefined) {
                            vm.WorkflowAssignToJabatanOptionAdditionalUnit = c;
                            vm.SelectedJabatanAdditionalUnit = c[0].ID;
                            vm.JabatanEnabledAdditionalUnit = false;
                        }

                        var d = $filter('filter')(vm.WorkflowAssignToCawanganOptionAdditionalUnit, { ParentUnitID: parseInt(vm.SelectedJabatanAdditionalUnit) }, true);
                        if (d.length > 0 && d != undefined) {
                            vm.actWorkflowAssignToCawanganOptionAdditionalUnit = d;
                            vm.SelectedCawanganAdditionalUnit = a[0].ID;
                            vm.CawanganEnabledAdditionalUnit = true;   
                        }

                        var e = $filter('filter')(vm.WorkflowAssignToUnitOptionAdditionalUnit, { ParentUnitID: parseInt(vm.SelectedCawanganAdditionalUnit) }, true);

                        if (e != undefined && e.length != 0) {
                            vm.actWorkflowAssignToUnitOptionAdditionalUnit = e;
                        }
                    }
                    else
                    {
                        var a = $filter('filter')(vm.WorkflowAssignToJabatanOptionAdditionalUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                        if(a.length > 0 && a !=undefined)
                        {
                            var b = $filter('filter')(vm.WorkflowAssignToSeksyenOptionAdditionalUnit, { ID: a[0].SeksyenID.toString() }, true);
                            if (b != undefined && b.length != 0) {
                                vm.WorkflowAssignToSeksyenOptionAdditionalUnit = b;
                                vm.SelectedTimbalanAdditionalUnit = b[0].ID;
                                vm.SeksyenEnabledAdditionalUnit = false;

                            }

                            var c = $filter('filter')(vm.WorkflowAssignToJabatanOptionAdditionalUnit, { ParentUnitID: parseInt(vm.SelectedTimbalanAdditionalUnit) }, true);
                            if (c.length > 0 && c != undefined) {
                                vm.WorkflowAssignToJabatanOptionAdditionalUnit = c;
                                vm.SelectedJabatanAdditionalUnit = a[0].ID;
                                vm.JabatanEnabledAdditionalUnit = true;
                            }

                            var d = $filter('filter')(vm.WorkflowAssignToCawanganOptionAdditionalUnit, { ParentUnitID: parseInt(vm.SelectedJabatanAdditionalUnit) }, true);
                            if (d.length > 0 && d != undefined) {
                                vm.actWorkflowAssignToCawanganOptionAdditionalUnit = d;
                                //vm.SelectedCawanganAdditionalUnit = d[0].ID;
                                vm.CawanganEnabledAdditionalUnit = true;
                            }

                        }
                        else
                        {
                            var a = $filter('filter')(vm.WorkflowAssignToSeksyenOptionAdditionalUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                            if(a.length > 0 && a!=undefined)
                            {
                                vm.SelectedTimbalanAdditionalUnit = a[0].ID;
                                vm.SeksyenEnabledAdditionalUnit = true;
                            }
                        }
                    }
                }

                //var m = $filter('filter')(vm.WorkflowAssignToJabatanOptionAdditionalUnit, { ID: $window.objUser.Unit.Branch.UnitID.toString() }, true);

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

                //    var a = $filter('filter')(vm.WorkflowAssignToSeksyenOptionAdditionalUnit, { ID: m[0].ParentUnitID.toString() }, true);
                //    if (a != undefined && a.length != 0) {
                //        vm.WorkflowAssignToSeksyenOptionAdditionalUnit = a;
                //        vm.SelectedTimbalanAdditionalUnit = a[0].ID;
                //        vm.SeksyenEnabledAdditionalUnit = false;

                //    }

                //    vm.WorkflowAssignToJabatanOptionAdditionalUnit = m;
                //    vm.SelectedJabatanAdditionalUnit = m[0].ID;
                //    vm.JabatanEnabledAdditionalUnit = false;

                //    var b = $filter('filter')(vm.WorkflowAssignToCawanganOptionAdditionalUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                //    if (b != undefined && b.length != 0) {
                //        vm.actWorkflowAssignToCawanganOptionAdditionalUnit = b;
                //        vm.SelectedCawanganAdditionalUnit = b[0].ID;
                //        vm.CawanganEnabledAdditionalUnit = false;

                //        var m = $filter('filter')(vm.WorkflowAssignToUnitOptionAdditionalUnit, { ParentUnitID: parseInt(vm.SelectedCawanganDocUnit) }, true);

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

    }

    // Filter Default Unit
    vm.ShowFilterOptionDocUnit = function () {

        vm.showdetailDocUnit = !vm.showdetailDocUnit;
    }

    vm.ResetHierarchyDocUnit = function () {

        if (vm.userList.WFUserProfileID > 0) {
            vm.SelectedTimbalanDocUnit = "";
            vm.SelectedJabatanDocUnit = "";
            vm.SelectedCawanganDocUnit = "";
            vm.SelectedUnitsDocUnit = "";
            vm.JabatanOptionDocUnit = [];
            vm.CawanganOptionDocUnit = [];
            vm.UnitOptionDocUnit = [];

            vm.SeksyenEnabledDocUnit = true;
            vm.JabatanEnabledDocUnit = true;

            vm.actWorkflowAssignToJabatanOptionDocUnit = [];
            vm.actWorkflowAssignToCawanganOptionDocUnit = [];
            vm.actWorkflowAssignToUnitOptionDocUnit = [];
        }
        else
        {
            var b = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
            if (b.length > 0 && b != undefined)
            {
                vm.SeksyenEnabledDocUnit = false;
                vm.JabatanEnabledDocUnit = false;
                vm.SelectedUnitsDocUnit = "";
            }
            else 
            {
                var a = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                if(a.length > 0 && a!=undefined)
                {
                    vm.SeksyenEnabledDocUnit = false;
                    vm.JabatanEnabledDocUnit = false;
                    vm.SelectedUnitsDocUnit = "";
                    vm.SelectedCawanganDocUnit = "";
                }
                else
                {
                    var a = $filter('filter')(vm.WorkflowAssignToJabatanOption, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                    if(a.length > 0 && a !=undefined)
                    {
                        vm.SeksyenEnabledDocUnit = false;
                        vm.JabatanEnabledDocUnit = true;
                        vm.SelectedUnitsDocUnit = "";
                        vm.SelectedCawanganDocUnit = "";
                        vm.SelectedJabatanDocUnit = "";
                    }
                    else
                    {
                        vm.SelectedTimbalanDocUnit = "";
                        vm.SelectedJabatanDocUnit = "";
                        vm.SelectedCawanganDocUnit = "";
                        vm.SelectedUnitsDocUnit = "";
                        vm.JabatanOptionDocUnit = [];
                        vm.CawanganOptionDocUnit = [];
                        vm.UnitOptionDocUnit = [];

                        vm.SeksyenEnabledDocUnit = true;
                        vm.JabatanEnabledDocUnit = true;

                        vm.actWorkflowAssignToJabatanOptionDocUnit = [];
                        vm.actWorkflowAssignToCawanganOptionDocUnit = [];
                        vm.actWorkflowAssignToUnitOptionDocUnit = [];
                    }
                }
            }
       
        }

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

        vm.SeksyenUserEnabled = false;
        vm.JabatanUserEnabled = false;
        vm.CawanganUserEnabled = false;
        vm.UnitUserEnabled = false;

        // vm.AssignTo = "";


        //vm.UserResultOption = [];

    }

    vm.seksyenChange = function (selectedTimbalan) {

        vm.actWorkflowAssignToJabatanOption = [];

        if (selectedTimbalan != null) {
            var m = $filter('filter')(vm.WorkflowAssignToJabatanOption, { ParentUnitID: parseInt(selectedTimbalan) }, true);

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

                vm.actWorkflowAssignToJabatanOption = m;
            }


            if (vm.Other == constAssignToTypeUser) {
                SearchUserByUnitID(selectedTimbalan);
            }
        }

    };

    vm.seksyenChangeDocUnit = function (selectedTimbalanDocUnit) {

        vm.actWorkflowAssignToJabatanOptionDocUnit = [];

        if (selectedTimbalanDocUnit != null) {
            var m = $filter('filter')(vm.WorkflowAssignToJabatanOptionDocUnit, { ParentUnitID: parseInt(selectedTimbalanDocUnit) }, true);
            if (m != undefined && m.length != 0) {
                vm.actWorkflowAssignToJabatanOptionDocUnit = m;
            }
        }

    };

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

        vm.actWorkflowAssignToCawanganOption = [];

        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.actWorkflowAssignToCawanganOption = m;
            }

            if (vm.Other == constAssignToTypeUser) {
                SearchUserByUnitID(SelectedJabatan);
            }
        }

    };

    vm.jabatanChangeDocUnit = function (SelectedJabatanDocUnit) {
        //enable upper hierarchy
        vm.SeksyenEnabledDocUnit = true;
        vm.actWorkflowAssignToCawanganOptionDocUnit = [];

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

            if (m != undefined && m.length != 0) {
                vm.actWorkflowAssignToCawanganOptionDocUnit = m;
                vm.CawanganEnabledDocUnit = true;
            }
        }

    };

    vm.cawanganChange = function (SelectedCawangan) {

        //enable upper hierarchy
        vm.SeksyenEnabled = true;
        vm.JabatanEnabled = true;

        vm.actWorkflowAssignToUnitOption = [];

        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.actWorkflowAssignToUnitOption = m;
            }

            if (vm.Other == constAssignToTypeUser) {
                SearchUserByUnitID(SelectedCawangan);
            }

        }

    };
    vm.cawanganChangeDocUnit = function (SelectedCawanganDocUnit) {

        //enable upper hierarchy
        vm.SeksyenEnabledDocUnit = true;
        vm.JabatanEnabledDocUnit = true;

        vm.actWorkflowAssignToUnitOptionDocUnit = [];

        if (SelectedCawanganDocUnit != null) {
            //disable upper hierarchy
            vm.SeksyenEnabledDocUnit = false;
            vm.JabatanEnabledDocUnit = false;

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

            if (m != undefined && m.length != 0) {
                vm.actWorkflowAssignToUnitOptionDocUnit = m;
            }
        }

    };

    vm.unitChange = function (SelectedUnits) {

        if (vm.Other == constAssignToTypeUser) {
            SearchUserByUnitID(SelectedUnits);
        }


    };

    vm.SelectHierarchy = function () {
        vm.UserResultOption = [];
        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.UserResultOption = m;
            vm.AssignTo = m[0];
        }

    }

    vm.SelectHierarchyDocUnit = function () {
        vm.UnitPenerimaanDocOption = [];
        m = [];

        if (vm.userList.UnitID > 0 &&  (vm.userList.ManagerUserProfileID == null || vm.userList.ManagerUserProfileID == 0)) {
            swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangePengurusUnit, "error");
            vm.showNoManagerValidationMsg = true;
        }
        else
        {
            if (vm.SelectedUnitsDocUnit != "" && vm.SelectedUnitsDocUnit != null) {
                m = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, {
                    ID: vm.SelectedUnitsDocUnit
                }, true);
            }
            else if (vm.SelectedCawanganDocUnit != "" && vm.SelectedCawanganDocUnit != null) {
                m = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, {
                    ID: vm.SelectedCawanganDocUnit
                }, true);
            }
            else if (vm.SelectedJabatanDocUnit != "" && vm.SelectedJabatanDocUnit != null) {
                m = $filter('filter')(vm.WorkflowAssignToJabatanOptionDocUnit, {
                    ID: vm.SelectedJabatanDocUnit
                }, true);
            }

            else if (vm.SelectedTimbalanDocUnit != "" && vm.SelectedTimbalanDocUnit != null) {
                m = $filter('filter')(vm.WorkflowAssignToSeksyenOptionDocUnit, {
                    ID: vm.SelectedTimbalanDocUnit
                }, true);
            }
            if (m && (m.length != 0)) {
                vm.UnitPenerimaanDocOption = m;
                vm.DefaultUnitID = m[0];
            }

            if (vm.DefaultUnitID != null) {

                SearchHierachyByDefaultUnit(vm.DefaultUnitID);

            }
        }
    }

    vm.SearchUnitByNameDocUnit = function (query) {
        vm.UnitPenerimaanDocOption = [];
        vm.UnitDocloading = true;
        var wfuserProfileID = vm.userList.WFUserProfileID;

        if (query.length > 2) {
            UserSI.searchUserRequestUnitByName(query, wfuserProfileID).then(function (r) {
                if (r.data != null) {
                    var m = r.data;
                    if (m.length != 0) {
                        vm.UnitPenerimaanDocOption = m;
                        vm.userList.DefaultUnitID = m[0];
                    }
                } vm.UnitDocloading = false;
            });
        }
    }

    vm.SearchJabatanDefaultUnit = function (query) {
        vm.JabatanDefaultUnitOption = [];
        if (query.length > 1) {
            vm.JabatanDefaultUnitOption = vm.WorkflowAssignToJabatanOptionDocUnit;
        }
    }

    vm.SearchCawanganDefaultUnit = function (query) {
        vm.CawanganDefaultUnitOption = [];
        if (query.length > 1) {
            vm.CawanganDefaultUnitOption = vm.WorkflowAssignToCawanganOptionDocUnit;
        }
    }

    // Filter Default Unit

    // Show Additional Unit Filter
    vm.ShowFilterAdditionalUnit = function () {

        vm.showdetailAdditionalUnit = !vm.showdetailAdditionalUnit;
    }

    vm.ResetHierarchyAdditionalUnit = function () {
      

        if (vm.userList.WFUserProfileID > 0) {

            vm.SelectedTimbalanAdditionalUnit = "";
            vm.SelectedJabatanAdditionalUnit = "";
            vm.SelectedCawanganAdditionalUnit = "";
            vm.SelectedUnitsAdditionalUnit = "";

            vm.WorkflowAssignToJabatanOptionAdditionalUnit = [];
            vm.actWorkflowAssignToCawanganOptionAdditionalUnit = [];
            vm.actWorkflowAssignToUnitOptionAdditionalUnit = [];
            //vm.UserResultOption = [];

            vm.JabatanOptionDocUnit = [];
            vm.CawanganOptionDocUnit = [];
            vm.UnitOptionDocUnit = [];

            vm.SeksyenEnabledAdditionalUnit = true;
            vm.JabatanEnabledAdditionalUnit = true;
        }
        else
        {
            var a = $filter('filter')(vm.WorkflowAssignToUnitOptionAdditionalUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
            if (a.length > 0 && a != undefined)
            {
                vm.SelectedUnitsAdditionalUnit = "";
                vm.SeksyenEnabledAdditionalUnit = false;
                vm.JabatanEnabledAdditionalUnit = false;
            }
            else
            {
                var a = $filter('filter')(vm.WorkflowAssignToCawanganOptionAdditionalUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                if (a.length > 0 && a != undefined) {
                    vm.SelectedUnitsAdditionalUnit = "";
                    vm.SelectedCawanganAdditionalUnit = "";
                    vm.SeksyenEnabledAdditionalUnit = false;
                    vm.JabatanEnabledAdditionalUnit = false;
                }
                else
                {
                    var a = $filter('filter')(vm.WorkflowAssignToJabatanOptionAdditionalUnit, { ID: $window.objUser.Unit.UnitID.toString() }, true);
                    if (a.length > 0 && a != undefined) {
                        vm.SelectedUnitsAdditionalUnit = "";
                        vm.SelectedCawanganAdditionalUnit = "";
                        vm.SelectedJabatanAdditionalUnit = "";
                        vm.SeksyenEnabledAdditionalUnit = false;
                        vm.JabatanEnabledAdditionalUnit = true;
                    }
                    else
                    {
                        vm.SelectedTimbalanAdditionalUnit = "";
                        vm.SelectedJabatanAdditionalUnit = "";
                        vm.SelectedCawanganAdditionalUnit = "";
                        vm.SelectedUnitsAdditionalUnit = "";

                        vm.WorkflowAssignToJabatanOptionAdditionalUnit = [];
                        vm.actWorkflowAssignToCawanganOptionAdditionalUnit = [];
                        vm.actWorkflowAssignToUnitOptionAdditionalUnit = [];

                        vm.JabatanOptionDocUnit = [];
                        vm.CawanganOptionDocUnit = [];
                        vm.UnitOptionDocUnit = [];

                        vm.SeksyenEnabledAdditionalUnit = true;
                        vm.JabatanEnabledAdditionalUnit = true;
                    }
                }
            }


        }
    }

    vm.seksyenChangeAdditionalUnit = function (selectedTimbalanAdditionalUnit) {

        vm.WorkflowAssignToJabatanOptionAdditionalUnit = [];

        if (selectedTimbalanAdditionalUnit != null) {
            var m = $filter('filter')(vm.WorkflowAssignToJabatanOptionDocUnit, { ParentUnitID: parseInt(selectedTimbalanAdditionalUnit) }, true);
            if (m != undefined && m.length != 0) {
                vm.WorkflowAssignToJabatanOptionAdditionalUnit = m;
            }
        }

    };

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

        vm.actWorkflowAssignToCawanganOption = [];

        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.actWorkflowAssignToCawanganOption = m;
            }

            if (vm.Other == constAssignToTypeUser) {
                SearchUserByUnitID(SelectedJabatan);
            }
        }

    };

    vm.jabatanChangeAdditionalUnit = function (SelectedJabatanAdditionalUnit) {
        //enable upper hierarchy
        vm.SeksyenEnabledAdditionalUnit = true;
        vm.actWorkflowAssignToCawanganOptionAdditionalUnit = [];

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

            if (m != undefined && m.length != 0) {
                vm.actWorkflowAssignToCawanganOptionAdditionalUnit = m;
            
            }
        }

    };

    vm.cawanganChange = function (SelectedCawangan) {

        //enable upper hierarchy
        vm.SeksyenEnabled = true;
        vm.JabatanEnabled = true;

        vm.actWorkflowAssignToUnitOption = [];

        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.actWorkflowAssignToUnitOption = m;
            }

            if (vm.Other == constAssignToTypeUser) {
                SearchUserByUnitID(SelectedCawangan);
            }

        }

    };
    vm.cawanganChangeAdditionalUnit = function (SelectedCawanganAdditionalUnit) {

        //enable upper hierarchy
        vm.SeksyenEnabledAdditionalUnit = true;
        vm.JabatanEnabledAdditionalUnit = true;

        vm.actWorkflowAssignToUnitOptionAdditionalUnit = [];

        if (SelectedCawanganAdditionalUnit != null) {
            //disable upper hierarchy
            vm.SeksyenEnabledAdditionalUnit = false;
            vm.JabatanEnabledAdditionalUnit = false;

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

            if (m != undefined && m.length != 0) {
                vm.actWorkflowAssignToUnitOptionAdditionalUnit = m;
            }
        }

    };

    vm.unitChange = function (SelectedUnits) {

        if (vm.Other == constAssignToTypeUser) {
            SearchUserByUnitID(SelectedUnits);
        }


    };

    vm.SelectHierarchy = function () {
        vm.UserResultOption = [];
        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.UserResultOption = m;
            vm.AssignTo = m[0];
        }

    }

    vm.SelectHierarchyAdditionalUnit = function () {
        vm.UnitPenerimaanAdditionalUnitOption = [];
        m = [];

        if (vm.SelectedUnitsAdditionalUnit != "" && vm.SelectedUnitsAdditionalUnit != null) {
            m = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, {
                ID: vm.SelectedUnitsAdditionalUnit
            }, true);
        }
        else if (vm.SelectedCawanganAdditionalUnit != "" && vm.SelectedCawanganAdditionalUnit != null) {
            m = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, {
                ID: vm.SelectedCawanganAdditionalUnit
            }, true);
        }
        else if (vm.SelectedJabatanAdditionalUnit != "" && vm.SelectedJabatanAdditionalUnit != null) {
            m = $filter('filter')(vm.WorkflowAssignToJabatanOptionDocUnit, {
                ID: vm.SelectedJabatanAdditionalUnit
            }, true);
        }

        else if (vm.SelectedTimbalanAdditionalUnit != "" && vm.SelectedTimbalanAdditionalUnit != null) {
            m = $filter('filter')(vm.WorkflowAssignToSeksyenOptionAdditionalUnit, {
                ID: vm.SelectedTimbalanAdditionalUnit
            }, true);
        }
        if (m && (m.length != 0)) {
            vm.UnitPenerimaanAdditionalUnitOption = m;
            vm.AdditionalUnitID = m[0];
        }

        // Enhancement 
        if (vm.AdditionalUnitID != null) {

            SearchHierachyByAdditionUnit(vm.AdditionalUnitID);

        }
    }

    vm.SearchUnitByNameAdditionalUnit = function (query) {
        vm.UnitPenerimaanAdditionalUnitOption = [];
        vm.UnitDocloading = true;
        var wfuserProfileID = vm.userList.WFUserProfileID;

        if (query.length > 2) {
            UserSI.searchUserRequestUnitByName(query,wfuserProfileID).then(function (r) {
                if (r.data != null) {
                    var m = r.data;
                    if (m.length != 0) {
                        vm.UnitPenerimaanAdditionalUnitOption = m;
                        vm.userList.AdditionalUnitID = m[0];
                    }
                } vm.UnitDocloading = false;
            });
        }
    }

    vm.SearchJabatanAdditionalUnit = function (query) {
        vm.JabatanAdditionalUnitOption = [];
        if (query.length > 1) {
            vm.JabatanAdditionalUnitOption = vm.WorkflowAssignToJabatanOptionAdditionalUnit;
        }
    }

    vm.SearchCawanganAdditionalUnit = function (query) {
        vm.CawanganAdditionalUnitOption = [];
        if (query.length > 1) {
            vm.CawanganAdditionalUnitOption = vm.WorkflowAssignToCawanganOptionAdditionalUnit;
        }
    }
    // Show Additional Unit Filter

    //Filter user group
    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;
                vm.CawanganUserEnabled = false;
            }

            SearchUserByUnitID(selectedTimbalanUser);

            vm.filteredWorkflowAssignToCawanganUserOption = [];
        }
        else {
            vm.NoUserMessage = true;
            vm.UserResultOption.length = 0;
            vm.ManagerProfileID = "";
        }
    };

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

        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);
            vm.CawanganUserEnabled = true;

        } else {
            vm.seksyenUserChange(vm.SelectedTimbalanUser);
            vm.CawanganUserEnabled = false;
        }
    };

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

        vm.filteredWorkflowAssignToUnitUserOption = [];

        if (SelectedCawanganUser != null) {
            //disable upper hierarchy
            //vm.SeksyenUserEnabled = false;
            //vm.JabatanUserEnabled = false;
            if (SelectedUnitDetail != undefined) {
                if (SelectedUnitDetail.HierarchyType == 37) {
                    var m = $filter('filter')(vm.WorkflowAssignToUnitUserOption, { ParentUnitID: parseInt(SelectedCawanganUser) }, true);

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


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

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

    vm.unitUserChange = function (SelectedUnitsUser) {
        if (SelectedUnitsUser != null) {
            SearchUserByUnitID(SelectedUnitsUser);
        }
        else {
            vm.cawanganUserChange(vm.SelectedCawanganUser)
        }
    };

    function SearchUserByUnitID(selectedUnitID) {
        if (selectedUnitID) {
            vm.NoUserMessage = false;
           
            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;
                            vm.UserResultOption.length = 0;
                            vm.ManagerProfileID = "";

                            // Temporay Comment on 29062019
                            //if (vm.userList.UnitID != undefined && vm.userList.WFUserProfileID > 0 )
                            //{
                            //    swal("Gagal", "Tiada Pengurus Unit dalam unit ini.", "error");
                            //    GetDefaultUnitByUnitID(vm.userList.UnitID.toString());
                            //}
                            // Temporay Comment on 29062019
                            //else
                            //{
                            //    vm.DefaultUnitID = "";
                            //    vm.ManagerProfileID = "";
                            //    vm.NoUserMessage = false;
                            //}  
                        }
                        else
                        {
                            if (vm.userList.UnitID != undefined && vm.DefaultUnitID.ID != vm.userList.UnitID.toString())
                            {
                                 vm.ManagerProfileID = "";
                            }
                           
                        }
                    }
                }
            });
        }
    }

    vm.SearchUserByName = function (query, DefaultUnitID) {
        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.ShowFilterUserOption = function () {
        if (!vm.showUserdetail) {
            vm.showUserdetail = true;

            if (vm.DefaultUnitID != null) {
                SearchHierachyByDefaultUnit(vm.DefaultUnitID)
            }
            else {
                vm.SelectedTimbalanUser = "";
                vm.SelectedJabatanUser = "";
                vm.SelectedCawanganUser = "";
                vm.SelectedUnitsUser = "";

                vm.SeksyenUserEnabled = false;
                vm.JabatanUserEnabled = false;
                vm.CawanganUserEnabled = false;
            }

        }
        else {
            //vm.ResetUserHierarchy();
            vm.showUserdetail = false;
        }
    }

    function SearchHierachyByDefaultUnit(SelectedDefaultUnit) {

        if (vm.DefaultUnitID != null) {
            if (vm.DefaultUnitID.HierarchyType == 37) {
                //var model = vm.DefaultUnitID.AdditionalInfo.split(".");
                m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, {
                    ID: SelectedDefaultUnit.SeksyenID.toString()
                }, true);
                if (m.length > 0) {
                    vm.SelectedTimbalanUser = m[0].ID;
                    vm.JabatanUserEnabled = false;
                    if (vm.SelectedTimbalanUser != null) {
                        vm.SeksyenUserEnabled = false;

                        b = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, {
                            ID: SelectedDefaultUnit.JabatanID.toString()
                        }, true);

                        vm.filteredWorkflowAssignToJabatanUserOption = b;
                        vm.SelectedJabatanUser = b[0].ID;
                        if (vm.SelectedJabatanUser != null) {
                            var m = $filter('filter')(vm.WorkflowAssignToCawanganUserOption, { ParentUnitID: parseInt(vm.SelectedJabatanUser) }, true);
                            if (m != undefined && m.length != 0) {

                                vm.filteredWorkflowAssignToCawanganUserOption = m;
                                var m = $filter('filter')(vm.filteredWorkflowAssignToCawanganUserOption, { ID: SelectedDefaultUnit.CawanganID.toString() }, true);
                                if (m.length > 0) {
                                    vm.SelectedCawanganUser = m[0].ID;
                                    var m = $filter('filter')(vm.WorkflowAssignToUnitUserOption, { ParentUnitID: parseInt(vm.SelectedCawanganUser) }, true);
                                    if (m.length > 0) {
                                        vm.filteredWorkflowAssignToUnitUserOption = m;
                                        var m = $filter('filter')(vm.filteredWorkflowAssignToUnitUserOption, { ID: SelectedDefaultUnit.ID.toString() }, true);
                                        vm.SelectedUnitsUser = m[0].ID;
                                        SearchUserByUnitID(vm.SelectedUnitsUser);
                                        
                                    }
                                }

                            }

                            vm.CawanganUserEnabled = true;
                            vm.UnitUserEnabled = true;
                        }
                    }
                }

            }
            else
                if (vm.DefaultUnitID.HierarchyType == 36) {
                    //var model = vm.DefaultUnitID.AdditionalInfo.split(".");
                    m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, { ID: SelectedDefaultUnit.SeksyenID.toString() }, true);
                    if (m.length > 0) {
                        vm.SelectedTimbalanUser = m[0].ID;
                        //vm.JabatanUserEnabled = false;
                        if (vm.SelectedTimbalanUser != null) {
                            vm.SeksyenUserEnabled = false;
                            vm.JabatanUserEnabled = true;
                            vm.SelectedCawanganUser = false;
                            vm.CawanganUserEnabled = true;

                            b = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, { ParentUnitID: parseInt(vm.SelectedTimbalanUser) }, true);

                            vm.filteredWorkflowAssignToJabatanUserOption = b;
                            var m = $filter('filter')(vm.filteredWorkflowAssignToJabatanUserOption, { ID: SelectedDefaultUnit.JabatanID.toString() }, true);
                            if (m.length > 0) {
                                vm.SelectedJabatanUser = m[0].ID;
                                var m = $filter('filter')(vm.WorkflowAssignToCawanganUserOption, { ParentUnitID: parseInt(vm.SelectedJabatanUser) }, true);
                                if (m.length > 0) {
                                    vm.filteredWorkflowAssignToCawanganUserOption = m;
                                    m = $filter('filter')(vm.filteredWorkflowAssignToCawanganUserOption, { ID: SelectedDefaultUnit.CawanganID.toString() }, true)
                                    if (m.length > 0) {
                                        vm.SelectedCawanganUser = m[0].ID;
                                        SearchUserByUnitID(vm.SelectedCawanganUser);
                                    }
                                }

                            }
                            vm.filteredWorkflowAssignToUnitUserOption = [];
                        }
                    }
                }
                else if (vm.DefaultUnitID.HierarchyType == 35) {
                    //var model = vm.DefaultUnitID.AdditionalInfo.split(".");
                    m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, { ID: SelectedDefaultUnit.SeksyenID.toString() }, true);
                    if (m.length > 0) {
                        vm.SelectedTimbalanUser = m[0].ID;
                        b = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, {
                            ParentUnitID: parseInt(vm.SelectedTimbalanUser)
                        }, true);

                        vm.filteredWorkflowAssignToJabatanUserOption = b;
                        b = $filter('filter')(vm.filteredWorkflowAssignToJabatanUserOption, {
                            ID: SelectedDefaultUnit.JabatanID.toString()
                        }, true);
                        if (b.length > 0) {
                            vm.SelectedJabatanUser = b[0].ID;
                            SearchUserByUnitID(vm.SelectedJabatanUser);
                        }
                        vm.CawanganUserEnabled = false;
                    }


                    vm.SeksyenUserEnabled = true;
                }
                else {
                    m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, {
                        ID: vm.DefaultUnitID.ID
                    }, true);
                    if (m.length > 0) {
                        vm.SelectedTimbalanUser = m[0].ID;
                        vm.JabatanUserEnabled = false;
                        vm.CawanganUserEnabled = false;
                        vm.UnitUserEnabled = false;
                        vm.SelectedJabatanUser = "";
                        vm.SelectedCawanganUser = "";
                        vm.SelectedUnitsUser = "";
                        SearchUserByUnitID(vm.SelectedTimbalanUser);
                        //vm.WorkflowAssignToSeksyenUserOption
                    }
                }
        }
        else {
            vm.SelectedTimbalanUser = "";
            vm.SelectedJabatanUser = "";
            vm.SelectedCawanganUser = "";
            vm.SelectedUnitsUser = "";
        }
    }

    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.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 = [];
    }
    //Filter user group

    vm.GetReportManagerByUnit = function (defaultUnitID) {
       
        if (vm.userList.UnitID > 0 && defaultUnitID !=undefined && (vm.userList.ManagerUserProfileID == null || vm.userList.ManagerUserProfileID == 0)) {
            swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangePengurusUnit, "error");
            vm.showNoManagerValidationMsg = true;
            GetDefaultUnitByUnitID(vm.userList.UnitID.toString());
        }
        else
        {
            if (vm.DefaultUnitID != null) {
                if (vm.DefaultUnitID.HierarchyType == 37) {
                    //var model = vm.DefaultUnitID.AdditionalInfo.split(".");
                    m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, {
                        ID: defaultUnitID.SeksyenID.toString()
                    }, true);
                    if (m.length > 0) {
                        vm.SelectedTimbalanUser = m[0].ID;
                        vm.JabatanUserEnabled = false;
                        if (vm.SelectedTimbalanUser != null) {
                            vm.SeksyenUserEnabled = false;

                            b = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, {
                                ID: defaultUnitID.JabatanID.toString()
                            }, true);

                            vm.filteredWorkflowAssignToJabatanUserOption = b;
                            vm.SelectedJabatanUser = b[0].ID;
                            if (vm.SelectedJabatanUser != null) {
                                var m = $filter('filter')(vm.WorkflowAssignToCawanganUserOption, { ParentUnitID: parseInt(vm.SelectedJabatanUser) }, true);
                                if (m != undefined && m.length != 0) {

                                    vm.filteredWorkflowAssignToCawanganUserOption = m;
                                    var m = $filter('filter')(vm.filteredWorkflowAssignToCawanganUserOption, { ID: defaultUnitID.CawanganID.toString() }, true);
                                    if (m.length > 0) {
                                        vm.SelectedCawanganUser = m[0].ID;
                                        var m = $filter('filter')(vm.WorkflowAssignToUnitUserOption, { ParentUnitID: parseInt(vm.SelectedCawanganUser) }, true);
                                        if (m.length > 0) {
                                            vm.filteredWorkflowAssignToUnitUserOption = m;
                                            var m = $filter('filter')(vm.filteredWorkflowAssignToUnitUserOption, { ID: defaultUnitID.ID.toString() }, true);
                                            vm.SelectedUnitsUser = m[0].ID;

                                            SearchUserByUnitID(vm.SelectedUnitsUser);
                                        }
                                    }

                                }
                            }
                        }
                    }
                    vm.CawanganUserEnabled = true;
                    vm.UnitUserEnabled = true;
                }
                else
                    if (vm.DefaultUnitID.HierarchyType == 36) {
                        //var model = vm.DefaultUnitID.AdditionalInfo.split(".");
                        m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, { ID: defaultUnitID.SeksyenID.toString() }, true);
                        if (m.length > 0) {
                            vm.SelectedTimbalanUser = m[0].ID;
                            //vm.JabatanUserEnabled = false;
                            if (vm.SelectedTimbalanUser != null) {
                                vm.SeksyenUserEnabled = false;
                                vm.JabatanUserEnabled = true;
                                vm.SelectedCawanganUser = false;
                                vm.CawanganUserEnabled = true;

                                b = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, { ParentUnitID: parseInt(vm.SelectedTimbalanUser) }, true);

                                vm.filteredWorkflowAssignToJabatanUserOption = b;
                                var m = $filter('filter')(vm.filteredWorkflowAssignToJabatanUserOption, { ID: defaultUnitID.JabatanID.toString() }, true);
                                if (m.length > 0) {
                                    vm.SelectedJabatanUser = m[0].ID;
                                    var m = $filter('filter')(vm.WorkflowAssignToCawanganUserOption, { ParentUnitID: parseInt(vm.SelectedJabatanUser) }, true);
                                    if (m.length > 0) {
                                        vm.filteredWorkflowAssignToCawanganUserOption = m;
                                        m = $filter('filter')(vm.filteredWorkflowAssignToCawanganUserOption, { ID: defaultUnitID.CawanganID.toString() }, true)
                                        if (m.length > 0) {
                                            vm.SelectedCawanganUser = m[0].ID;
                                            vm.CawanganUserEnabled = true;

                                            SearchUserByUnitID(vm.SelectedCawanganUser);
                                        }
                                    }

                                }
                                vm.filteredWorkflowAssignToUnitUserOption = [];
                            }
                        }
                    }
                    else if (vm.DefaultUnitID.HierarchyType == 35) {
                        //var model = vm.DefaultUnitID.AdditionalInfo.split(".");
                        m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, { ID: defaultUnitID.SeksyenID.toString() }, true);
                        if (m.length > 0) {
                            vm.SelectedTimbalanUser = m[0].ID;
                            b = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, {
                                ParentUnitID: parseInt(vm.SelectedTimbalanUser)
                            }, true);

                            vm.filteredWorkflowAssignToJabatanUserOption = b;
                            b = $filter('filter')(vm.filteredWorkflowAssignToJabatanUserOption, {
                                ID: defaultUnitID.JabatanID.toString()
                            }, true);
                            if (b.length > 0) {
                                vm.SelectedJabatanUser = b[0].ID;
                                SearchUserByUnitID(vm.SelectedJabatanUser);
                            }
                            vm.CawanganUserEnabled = false;
                        }


                        vm.SeksyenUserEnabled = true;
                        vm.JabatanUserEnabled = true;
                    }
                    else {
                        m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, {
                            ID: vm.DefaultUnitID.ID
                        }, true);
                        if (m.length > 0) {
                            vm.SelectedTimbalanUser = m[0].ID;
                            vm.JabatanUserEnabled = false;
                            vm.CawanganUserEnabled = false;
                            vm.UnitUserEnabled = false;
                            SearchUserByUnitID(vm.SelectedTimbalanUser);
                            //vm.WorkflowAssignToSeksyenUserOption
                        }
                    }
            }
            else {
                vm.SelectedTimbalanUser = "";
                vm.SelectedJabatanUser = "";
                vm.SelectedCawanganUser = "";
                vm.SelectedUnitsUser = "";
            }
        }
      
    }

    vm.redirectTo = function (url) {

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

    vm.AddRoles = function () {

        if (vm.Defaultroles != undefined && vm.Defaultroles.selected.length > 0) {

            vm.showdetailRoles = true;
            var duplicateRoleAdd = null;
            angular.forEach(vm.Defaultroles.selected, function (value, key) {
                if (vm.DefaultrolesName.length > 0) {
                    m = $filter('filter')(vm.DefaultrolesName, { FunctionalRoleID: value }, true);
                    if (m.length > 0) {
                        
                        if (duplicateRoleAdd != null)
                        {
                            duplicateRoleAdd += "," +  m[0].RoleName;
                        }
                        else
                        {
                            duplicateRoleAdd = m[0].RoleName;
                        }

                        swal("Gagal", "Peranan (" + duplicateRoleAdd + ") ini sudah wujud", "error");
                        
                    }
                    else {
                        m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: parseInt(value) }, true);
                        if (m.length > 0) {

                            vm.DefaultrolesName.push(m[0]);
                            vm.AddNewDefaultRoleID.push(m[0].FunctionalRoleID);
                            //vm.selectedRolesID = value;
                            //vm.DefaultrolesID = vm.selectedRolesID.selected.join(" || ");
                        }
                        else {
                            vm.DefaultrolesName = "";
                        }
                    }
                }
                else {
                    m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: parseInt(value) }, true);
                    if (m.length > 0) {

                        vm.DefaultrolesName.push(m[0]);
                        vm.AddNewDefaultRoleID.push(m[0].FunctionalRoleID);
                        //vm.selectedRolesID = value;
                        //vm.DefaultrolesID = vm.selectedRolesID.selected.join(" || ");
                        // vm.DefaultrolesID.push(m[0].FunctionalRoleID);
                    }
                    else {
                        vm.DefaultrolesName = "";
                    }
                }

            });

            vm.showRoleNoRecord = false;
            vm.Defaultroles.selected = ""

            if (vm.DefaultrolesName.length > 0) {
                vm.showDefaultRoleValidationMsg = false;
            }
            else {
                vm.showDefaultRoleValidationMsg = true;
            }
        }
        else {

            swal("Gagal", "Sila Pilih Peranan untuk Jabatan/Cawangan/Unit", "error");
        }

    }

    vm.AddAdditionalRoles = function () {
        //if (vm.AdditionalUnitID != "" && vm.AdditionalUnitID != undefined && vm.AdditionalRoles.selected.length > 0) {
        if (vm.AdditionalUnitID != "" && vm.AdditionalUnitID != undefined && vm.AdditionalRoles != undefined && vm.AdditionalRoles.selected.length > 0) {
            if (vm.AdditionalUnitID.ID == vm.DefaultUnitID.ID) {
                swal("Gagal", vm.DefaultUnitID.DisplayName + " telah dipilih untuk Jabatan/Cawangan/Unit.", "error");
            }
            else
            {
                vm.showdetailAdditionalRoles = true;

                //Pengurus For Additional Unit
                if (vm.AdditionUserResultOption.length > 0) {
                    if (vm.AdditionManagerProfileID != null) {
                        vm.AdditionalUnitID.ManagerName = vm.AdditionManagerProfileID.DisplayName;
                        vm.AdditionalUnitID.ManagerId = vm.AdditionManagerProfileID.UserProfileID;
                    }
                    else
                    {
                        vm.AdditionalUnitID.ManagerName = '-';
                    }
                }
                else
                {
                    vm.AdditionalUnitID.ManagerName = '-';
					vm.NoAdditionUserMessage = false;
                    vm.AdditionManagerProfileID = "";
                }

                //if (vm.userList.AdditionalUnitUserProfileManager.length > 0 && vm.AdditionalUnitID.ManagerId >0)
                //{
                //    c = $filter('filter')(vm.userList.AdditionalUnitUserProfileManager, { UserProfileID: vm.AdditionalUnitID.ManagerId }, true);
                //}
                //Pengurus For Additional Unit

                vm.SelectedAdditionalUnitID = vm.AdditionalUnitID;
                if (vm.additionalUnitandRoles.length > 0) {
                    vm.AdditionalRolesName = [];
                    // check this unit added before or not.
                    a = $filter('filter')(vm.additionalUnitandRoles, { ID: vm.SelectedAdditionalUnitID.ID }, true);
                    if (a.length > 0) {
                        // Check duplicate roles add or not
                        var DuplicateRoleFound = a[0].UnitRoleFunctionalID
                        angular.forEach(vm.AdditionalRoles.selected, function (value, key) {
                            vm.AdditionalRolesName = [];
                            m = $filter('filter')(DuplicateRoleFound, { FunctionalRoleID: parseInt(value) }, true);
                            if (m.length > 0) {
                                swal("Gagal", "Peranan ( " + m[0].RoleName + " ) ini sudah wujud.", "error");
                            }
                            else {
                                m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: parseInt(value) }, true);
                                if (m.length > 0) {
                                    vm.AdditionalRolesName.push(m[0]);
                                    a[0].UnitRoleFunctionalID.push(vm.AdditionalRolesName[0]);
                                    vm.AdditionalrolesID.push(m[0].FunctionalRoleID);
                                    vm.AdditionalForUnitID = vm.SelectedAdditionalUnitID;

                                    if (vm.AdditionalUnitID.ManagerId > 0) {
                                        a[0].ManagerId = vm.AdditionalUnitID.ManagerId
                                        a[0].ManagerName = vm.AdditionalUnitID.ManagerName;
                                    }
                                }
                                else {
                                    vm.AdditionalRolesName = "";

                                }
                            }
                        });

                    }
                    else {
                        //If it is new unit,let them add
                        vm.SelectedAdditionalUnitAndRoles.push(vm.SelectedAdditionalUnitID);
                        b = $filter('filter')(vm.SelectedAdditionalUnitAndRoles, { ID: vm.SelectedAdditionalUnitID.ID }, true);
                        if (b.length > 0) {
                            angular.forEach(vm.AdditionalRoles.selected, function (value, key) {

                                m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: parseInt(value) }, true);
                                if (m.length > 0) {
                                    vm.AdditionalRolesName.push(m[0]);
                                    b[0].UnitRoleFunctionalID = vm.AdditionalRolesName;
                                }
                                else {
                                    vm.AdditionalRolesName = "";

                                }

                            })
                        }

                        vm.additionalUnitandRoles.push(vm.AdditionalUnitID);

                        vm.AdditionalUnitID = ""
                    }
                }
                else {
                    vm.SelectedAdditionalUnitAndRoles.push(vm.SelectedAdditionalUnitID);
                    angular.forEach(vm.AdditionalRoles.selected, function (value, key) {

                        m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: parseInt(value) }, true);
                        if (m.length > 0) {
                            vm.AdditionalRolesName.push(m[0]);
                            vm.SelectedAdditionalUnitAndRoles[0].UnitRoleFunctionalID = vm.AdditionalRolesName;
                        }
                        else {
                            vm.AdditionalRolesName = "";

                        }

                    })

                    vm.additionalUnitandRoles.push(vm.AdditionalUnitID);

                    vm.AdditionalUnitID = ""
                }
            }

            vm.AdditionalRoles.selected = ""
            vm.AdditionalUnitID = "";
            vm.AdditionManagerProfileID = "";

        }
        else
            //if (vm.AdditionalUnitID != "" && vm.AdditionalUnitID != undefined && vm.AdditionalRoles.selected.length == 0) {
            if (vm.AdditionalUnitID != "" && vm.AdditionalUnitID != undefined && vm.AdditionalRoles == undefined) {
                if (vm.userList.UserAdditionalFunctionRoles != null && vm.userList.UserAdditionalFunctionRoles != undefined) {

                    //Change Pengurus For Additional Unit without change roles for it.
                    if (vm.AdditionUserResultOption.length > 0) {
                        if (vm.AdditionManagerProfileID != null) {
      
                            angular.forEach(vm.additionalUnitandRoles, function (value, key) {
                                if (value.ID == vm.AdditionalUnitID.ID)
                                {
                                    vm.AdditionalUnitID.ManagerName = vm.AdditionManagerProfileID.DisplayName;
                                    vm.AdditionalUnitID.ManagerId = vm.AdditionManagerProfileID.UserProfileID;
                                    vm.additionalUnitandRoles[key].AdditionUnitManagerId = vm.AdditionalUnitID.ManagerId;
                                    vm.additionalUnitandRoles[key].ManagerName = vm.AdditionalUnitID.ManagerName;
                                    vm.ChangeAdditionUserManager = vm.additionalUnitandRoles[key];
                                    vm.lstAdditionUserManager.push(vm.ChangeAdditionUserManager);
                                }

                            });
                        }
                        else {
                            vm.AdditionalUnitID.ManagerName = '-';
                        }

                      
                    }
                    else {
                        vm.AdditionalUnitID.ManagerName = '-';
                    }

                    vm.AdditionalUnitID = "";
                    vm.AdditionManagerProfileID = "";
                }
                else
                {
                    swal("Gagal", "Sila Pilih Peranan untuk Unit Tambahan", "error");
                }
             
            }
            else {
                if(vm.AdditionalRoles.selected.length == 0 && vm.AdditionalUnitID != "" && vm.AdditionalUnitID != undefined  )
                {
                    if (vm.userList.UserAdditionalFunctionRoles != null && vm.userList.UserAdditionalFunctionRoles != undefined) {

                        //Change Pengurus For Additional Unit without change roles for it.
                        if (vm.AdditionUserResultOption.length > 0) {
                            if (vm.AdditionManagerProfileID != null) {

                                angular.forEach(vm.additionalUnitandRoles, function (value, key) {
                                    if (value.ID == vm.AdditionalUnitID.ID) {
                                        vm.AdditionalUnitID.ManagerName = vm.AdditionManagerProfileID.DisplayName;
                                        vm.AdditionalUnitID.ManagerId = vm.AdditionManagerProfileID.UserProfileID;
                                        vm.additionalUnitandRoles[key].AdditionUnitManagerId = vm.AdditionalUnitID.ManagerId;
                                        vm.additionalUnitandRoles[key].ManagerName = vm.AdditionalUnitID.ManagerName;
                                        vm.ChangeAdditionUserManager = vm.additionalUnitandRoles[key];
                                        vm.lstAdditionUserManager.push(vm.ChangeAdditionUserManager);
                                    }

                                });
                            }
                            else {
                                vm.AdditionalUnitID.ManagerName = '-';
                            }


                        }
                        else {
                            vm.AdditionalUnitID.ManagerName = '-';
                        }

                        vm.AdditionalUnitID = "";
                        vm.AdditionManagerProfileID = "";
                    }
                    else
                    {
                        swal("Gagal", "Sila Pilih Peranan untuk Unit Tambahan", "error");
                    }   
                }
                else
                {
                    swal("Gagal", "Sila Pilih Unit Tambahan dan Peranan Unit Tambahan", "error");
                }
            
            }
    }

    vm.batal = function () {
        swal({
            title: "Adakah anda mahu batal permohonan pengguna yang sedang dikemaskini?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                vm.redirectTo('/UserRequest/Search');
            }
            else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });


    }

    vm.cancel = function()
    {
        vm.redirectTo('/UserRequest/Search');
    }

    vm.save = function (userProfileForm) {

        var result = null;
        var tarikhluput = null;
        var IsEmailValid = null;
        var IsDuplicateUnit = null;
        var DuplicateUnitName = null;
        var IsNoManagerInExistUnit = null;
        var IsDateToGreatThanDateFrom = null;

        if (vm.DefaultrolesName.length > 0)
        {
            vm.showDefaultRoleValidationMsg = false;
        }
        else
        {
            vm.showDefaultRoleValidationMsg = true;
        }
         
        if (vm.userList.JawatanID > 0)
        {
            vm.showJawatanValidationMsg = false;
        }
        else
        {
            vm.userList.JawatanID = null;
            vm.showJawatanValidationMsg = true;
            userProfileForm.$valid = false;
        }

        if (userProfileForm.$valid)
        {
            var isDirty = userProfileForm.$dirty;
            if (vm.AddNewDefaultRoleID.length > 0) {
                    isDirty = true;
                    vm.DefaultrolesIDs = vm.AddNewDefaultRoleID.join(" || ");
                }
                else {
                    // If user change unit, remain default role for it.
                    if (vm.userList.UnitID != undefined) {
                        if (vm.DefaultUnitID.ID != vm.userList.UnitID.toString()) {
                            vm.DefaultrolesIDs = vm.DefaultrolesID.join(" || ");
                        }
                        else
                        {
                            vm.DefaultrolesIDs = vm.DefaultrolesID;
                        }
                    }

                }

                if (vm.userList.UnitID != undefined && vm.DefaultUnitID.ID != vm.userList.UnitID.toString()) {
                    if ((vm.userList.ManagerUserProfileID == null || vm.userList.ManagerUserProfileID == 0) && (vm.ManagerProfileID == undefined || vm.ManagerProfileID == "") && (vm.userList.WFStatusID == ClosedStatus)) {
                        IsNoManagerInExistUnit = true;
                    }
                }

                if (vm.userList.Email == undefined) {
                    swal("Gagal", "Sila isi semua ruangan yang bertanda * ", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                    vm.showValidationMsg = true;
                    vm.showInvalidEmailMsg = false;
                }
                else {
                    var IsEmailValid = validateEmail(vm.userList.Email);
                    if (!IsEmailValid)
                    {
                        swal("Gagal", "Format alamat emel tidak sah.", "error");
                        vm.showValidationMsg = false;
                        vm.showInvalidEmailMsg = true;
                        var deferred = $q.defer();
                        deferred.reject('');
                        result = deferred.promise;
                    }
                }

                //if ((vm.TarikhLuput != null || vm.TarikhLuput != undefined ) && vm.userList.ActiveCondition == Expiry)
                //{
                //    var tarikhluput = vm.TarikhLuput;
                //    var dd = tarikhluput.getDate();
                //    var mm = tarikhluput.getMonth() + 1; //January is 0!
                //    var yyyy = tarikhluput.getFullYear();

                //    tarikhluput = mm + '/' + dd + '/' + yyyy;
                //}

                if ((vm.DateFrom != null || vm.DateFrom != undefined) && (vm.DateTo != null || vm.DateTo != undefined)) {
                    if (vm.DateFrom > vm.DateTo && vm.userList.ActiveCondition == Dormant) {
                        IsDateToGreatThanDateFrom = true;
                    }
                }

                if (vm.additionalUnitandRoles.length > 0 && vm.DefaultUnitID != "") {
                    m = $filter('filter')(vm.additionalUnitandRoles, { ID: vm.DefaultUnitID.ID }, true);
                    if (m.length > 0) {
                        IsDuplicateUnit = true;
                        DuplicateUnitName = m[0].DisplayName;
                    }
                }

                m = $filter('filter')(vm.duplicateLoginData, { LoginID: vm.userList.LoginID }, true);
                if (m.length > 0 && m[0].WFUserProfileID != vm.userList.WFUserProfileID) {
                    swal("Gagal", "Login ID ini telah digunakan.", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                }
                else if (!IsEmailValid) {
                    swal("Gagal", "Format alamat emel tidak sah.", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                    vm.showValidationMsg = false;
                    vm.showInvalidEmailMsg = true;
                }
                else if (vm.userList.LoginID == null || vm.userList.LoginID == undefined || vm.userList.LoginID == "") {
                    swal("Gagal", "Login ID perlu diisikan.", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                }
                else if ((vm.DefaultUnitID == undefined || vm.DefaultUnitID == "") && vm.DefaultrolesIDs == undefined) {
                    swal("Gagal", "Sila isi semua ruangan yang bertanda *", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                    vm.showValidationMsg = true;
                }
                else if ((vm.DefaultUnitID == undefined || vm.DefaultUnitID == "") && vm.DefaultrolesIDs != undefined) {
                    swal("Gagal", "Sila pilih Jabatan/Cawangan/Unit bagi user ini", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                    vm.showValidationMsg = true;
                }
                else if ((vm.DefaultUnitID != undefined || vm.DefaultUnitID != "") && vm.DefaultrolesIDs == undefined) {
                    swal("Gagal", "Sila pilih peranan bagi user ini", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                    vm.showValidationMsg = true;
                }
                else if (vm.DefaultrolesName.length == 0) //Check default roles 
                {
                    swal("Gagal", "Sila pilih peranan untuk user ini.", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                }
                else if ((vm.DateFrom == null || vm.DateFrom == undefined) && (vm.DateTo == null || vm.DateTo == undefined) && vm.userList.ActiveCondition == Dormant) {
                    swal("Gagal", "Sila pilih Tempoh Dorman(Dari) dan Tempoh Dorman(Hingga)", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                }
                else if (vm.DateFrom == null && vm.DateTo != null && vm.userList.ActiveCondition == Dormant) {
                    swal("Gagal", "Sila pilih Tempoh Dorman Tarikh From", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                }
                else if (IsDateToGreatThanDateFrom) {
                    swal("Gagal", "Tarikh Dorman(Hingga) mesti melebihi Tarikh Dorman(Dari)", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                }
                else if (vm.TarikhLuput == null && vm.userList.ActiveCondition == Expiry) {
                    swal("Gagal", "Sila pilih Tarikh Luput", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                }
                else if (tarikhluput < today && vm.userList.ActiveCondition == Expiry) {
                    swal("Gagal", "Tarikh luput tidak boleh sebelum tarikh hari ini", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                }
                else if (vm.AdditionalUnitID != "" && vm.AdditionalUnitID != undefined && (vm.AdditionalRoles == undefined || vm.AdditionalRoles.selected.length == 0)) {
                    swal("Gagal", "Sila pilih Peranan Unit Tambahan", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                }
                else if (vm.AdditionalUnitID != "" && vm.AdditionalUnitID != undefined && vm.AdditionalRoles.selected.length > 0) {
                    swal("Gagal", "Sila tekan butang “Tambah Unit Tambahan dan Peranan” sebelum simpan permohonan ini.", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                }
                else if (IsDuplicateUnit) {
                    swal("Gagal", DuplicateUnitName + " telah dipilih untuk Jabatan/Cawangan/Unit.", "error");
                    var deferred = $q.defer();
                    deferred.reject('');
                    result = deferred.promise;
                }
                else if (vm.Defaultroles != undefined && vm.Defaultroles.selected.length > 0)
                {
                    swal("Gagal", "Sila tekan butang “Tambah Peranan” sebelum simpan permohonan ini.", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                    vm.showValidationMsg = true;
                    vm.showInvalidEmailMsg = false;
                }
                else
                    // IF the user plan to change default unit and previous unit didnot have manager
                    if (IsNoManagerInExistUnit) {
                        swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangePengurusUnit, "error");
                        vm.showNoManagerValidationMsg = true;
                        var deferred = $q.defer();
                        deferred.reject('');
                        result = deferred.promise;
                    }
                        //else if ((vm.userList.ManagerUserProfileID == null || vm.userList.ManagerUserProfileID == 0) && (vm.userList.WFUserProfileID > 0) && (vm.userList.UserProfileID > 0) && (vm.userList.ActiveCondition == Dormant || vm.userList.ActiveCondition == Expiry || vm.userList.ActiveCondition == InActive))
                        //{
                        //    swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangePengurusUnit, "error");
                        //    vm.showNoManagerValidationMsg = true;
                        //    var deferred = $q.defer();
                        //    deferred.reject('');
                        //    result = deferred.promise;
                        //}
                    else {
                        //Add new roles for existing additional Unit
                        if (vm.SelectedAdditionalUnitAndRoles == 0 && vm.AdditionalrolesID.length > 0) {
                            vm.AdditionalrolesID = vm.AdditionalrolesID.join(" || ");
                            vm.AdditionalUnitID = vm.AdditionalForUnitID;
                        }

                        if (vm.DefaultrolesIDRemove.length > 0) {
                            isDirty = true;
                            vm.DefaultrolesIDRemoves = vm.DefaultrolesIDRemove.join(" , ");
                        }

                        if (vm.AdditionalRolesIDRemove.length > 0) {
                            isDirty = true;
                            vm.AdditionalRolesIDRemoves = vm.AdditionalRolesIDRemove.join(" , ");
                        }

                        if (vm.RemoveUnitAndRoles.length > 0) {
                            isDirty = true;
                            vm.additionalUnitandRoles = "";
                            vm.RemoveUnitAndRoless = vm.RemoveUnitAndRoles.join(" , ");
                        }

                        if (vm.userList.UserWFActiveCondition != null && vm.userList.UserWFActiveCondition != undefined) {
                            if (vm.userList.UserWFActiveCondition.DormantDateTo != vm.DateTo) {
                                isDirty = true;
                            }
                        }

                        //if (vm.lstAdditionUserManager != null && vm.lstAdditionUserManager != undefined)
                        //{

                        //}
                        if (vm.lstRemoveAdditionUserManager.length > 0)
                        {
                            isDirty = true;
                        }

                        if (userProfileForm.$valid) {
                            if (isDirty) {
                                getChangeHistory(userProfileForm);

                                //if(vm.userList.UserWFActiveCondition!=null)
                                //{
                                //    vm.userList.ActiveCondition = vm.userList.UserWFActiveCondition.ActiveCondition;
                                //}

                                if (vm.userList.ActiveCondition == Active) {
                                    vm.DateFrom = null;
                                    vm.DateTo = null;
                                    vm.TarikhLuput = null;
                                    vm.userList.IsActive = true;
                                }
                                else {
                                    if (vm.userList.ActiveCondition == InActive) {
                                        vm.DateFrom = null;
                                        vm.DateTo = null;
                                        vm.TarikhLuput = null;
                                        vm.userList.IsActive = false;
                                    }
                                    else if (vm.userList.ActiveCondition == Expiry) {
                                        vm.DateFrom = null;
                                        vm.DateTo = null;
                                        vm.userList.IsActive = true;
                                    }
                                    else {
                                        vm.userList.IsActive = true;
                                        vm.TarikhLuput = null;
                                    }

                                }

                                // To be
                                if (vm.userList.UserProfileID > 0)
                                {
                                    if (vm.userList.WFStatusID == ClosedStatus || vm.userList.WFStatusID == null || vm.userList.WFStatusID == newStatus) {
                                        if (vm.userList.ActiveCondition != vm.userList.UserWFActiveCondition.ActiveCondition || vm.DefaultUnitID.ID != vm.userList.UnitID.toString() || vm.DefaultrolesName.length != vm.userList.UserFunctionRoles.length) {
                                            IsSentForApproval = true;
                                        }
                                        else {

                                            if (vm.userList.IsSendApproval && (vm.userList.WFStatusID == ClosedStatus || vm.userList.WFStatusID == null || vm.userList.WFStatusID == newStatus))
                                            {
                                                IsSentForApproval = true;
                                            }
                                            else
                                            {
                                                IsSentForApproval = false;
                                            }
                                           
                                        }
                                    }
                                    else {
                                        IsSentForApproval = true;
                                    }
                                }
                                else
                                {
                                    IsSentForApproval = false;
                                }

                            
                          
                                var userModel = {
                                    WFUserProfileID: vm.userList.WFUserProfileID,
                                    UserProfileID : vm.userList.UserProfileID,
                                    Gred: vm.userList.Gred == null ? "" : vm.userList.Gred,
                                    NRIC: vm.userList.NRIC == null ? "" : vm.userList.NRIC,
                                    UnitID: (vm.DefaultUnitID == undefined || vm.DefaultUnitID == "") ? 0 : vm.DefaultUnitID.ID == "0" ? 0 : parseInt(vm.DefaultUnitID.ID),
                                    ManagerUserProfileID: (vm.ManagerProfileID == undefined || vm.ManagerProfileID == "") ? 0 : vm.ManagerProfileID.UserProfileID == 0 ? 0 : vm.ManagerProfileID.UserProfileID,
                                    LoginID: vm.userList.LoginID,
                                    DisplayName: vm.userList.DisplayName,
                                    Email: vm.userList.Email,
                                    IsActive: vm.userList.IsActive,
                                    DefaultRolesID: vm.DefaultrolesIDs == null ? 0 : vm.DefaultrolesIDs,
                                    RemoveDefaultRolesID: vm.DefaultrolesIDRemoves == null ? 0 : vm.DefaultrolesIDRemoves,
                                    RemoveUnitAndRoles: vm.RemoveUnitAndRoless == null ? 0 : vm.RemoveUnitAndRoless,
                                    RemoveAdditionalRolesID: vm.AdditionalRolesIDRemoves == null ? 0 : vm.AdditionalRolesIDRemoves,
                                    JawatanID: vm.userList.JawatanID, // CR Jan2020 (Chew)
                                    ShortName: vm.userList.ShortName,
                                    AdditionalRolesID: vm.AdditionalrolesID == null ? 0 : vm.AdditionalrolesID,
                                    AdditionalUnitID: (vm.AdditionalUnitID == undefined || vm.AdditionalUnitID == "") ? 0 : vm.AdditionalUnitID.ID == "0" ? 0 : parseInt(vm.AdditionalUnitID.ID),
                                    AdditionalManagerID: (vm.AdditionalUnitID == undefined || vm.AdditionalUnitID == "") ? 0 : vm.AdditionalUnitID.ID == "0" ? 0 : parseInt(vm.AdditionalUnitID.ManagerId),
                                    ChangeUnitAdditionManager: vm.lstAdditionUserManager,///vm.ChangeAdditionUserManager.ManagerId,
                                    //ChangeUnitAdditionManagerUnitID: vm.ChangeAdditionUserManager == null ? 0 : vm.ChangeAdditionUserManager.ID,
                                    RemoveAdditionalUnitID: vm.AdditionalForUnitID,
                                    RemoveUnitAdditionManager: vm.lstRemoveAdditionUserManager,
                                    //UserAdditionalUnitAndRoles: vm.additionalUnitandRoles,
                                    UserAdditionalUnitAndRoles: vm.SelectedAdditionalUnitAndRoles,
                                    IsSubmitReviewAction: false,
                                    IsSubmitApprovalAction: false,
                                    IsApproveAction: false,
                                    IsRejectAction: false,
                                    ExpiryDate: (vm.TarikhLuput == undefined || vm.TarikhLuput == null) ? null : $filter('date')(vm.TarikhLuput, $scope.DateTimeFormat),
                                    DormantDateFrom: (vm.DateFrom == undefined || vm.DateFrom == null) ? null : $filter('date')(vm.DateFrom, $scope.DateTimeFormat),
                                    DormantDateTo: (vm.DateTo == undefined || vm.DateTo == null) ? null : $filter('date')(vm.DateTo, $scope.DateTimeFormat),
                                    ActiveCondition: vm.userList.ActiveCondition,
                                    IsSendApproval: IsSentForApproval,
                                    IsSubmitButtonClick : false
                                }

                                var model = {
                                    WFUserProfile: userModel,
                                    ChangeHistory: vm.changesHistory
                                }

                                UserSI.updateWFUserProfileDetail(model).then(function (r) {
                                    if (r.status === 200) {
                                        if (r.data) {
                                            if (r.data.WFUserProfile.WFUserProfileID == -1) {
                                                swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangePengurusUnit, "error");
                                                vm.userList.IsActive = r.data.WFUserProfile.ActiveCondition;
                                                GetDefaultUnitByUnitID(vm.userList.UnitID.toString());
                                            }
                                            else {
                                                swal({
                                                    title: "Berjaya Kemaskini!",
                                                    type: "success",
                                                    timer: 2500,
                                                    showConfirmButton: false
                                                }, function () {
                                                    //location.reload();

                                                    vm.redirectTo('/UserRequest/Profile/Detail/' + r.data.WFUserProfile.WFUserProfileID);
                                                });
                                            }
                                        }
                                        else {
                                            swal("Gagal", r.data, "error");
                                            var deferred = $q.defer(); // required for click and disabled
                                            deferred.reject('');
                                            result = deferred.promise;
                                        }

                                    } else {
                                        swal("Gagal", r.data, "error");
                                        var deferred = $q.defer(); // required for click and disabled
                                        deferred.reject('');
                                        result = deferred.promise;
                                    }
                                });

                                var deferred = $q.defer(); // required for click and disabled
                                deferred.reject('');
                                result = deferred.promise;
                            }
                            else {
                                swal("Gagal", "Tiada perubahan maklumat dilakukan!", "error");
                                var deferred = $q.defer(); // required for click and disabled
                                deferred.reject('');
                                result = deferred.promise;
                            }
                        }
                        else {
                            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                            vm.showValidationMsg = true;
                        }
                    }
            
           
        }
        else
        {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            var deferred = $q.defer(); // required for click and disabled
            deferred.reject('');
            result = deferred.promise;
            vm.showValidationMsg = true;
            vm.showJawatanValidationMsg = true;

            if (vm.DefaultrolesName.length > 0) {
                vm.showDefaultRoleValidationMsg = false;
            }
            else {
                vm.showDefaultRoleValidationMsg = true;
            }
        }
       
        return result;
    }

    vm.removeRoles = function (selectFunctionRoleID, index) {
        if (selectFunctionRoleID != null) {

            vm.DefaultrolesName.splice(index, 1);

            if (vm.UserProfileID != "") {
                m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: selectFunctionRoleID }, true);
                if (m.length > 0) {
                    vm.DefaultrolesIDRemove.push(m[0].FunctionalRoleID);
                }
            }
            else {
                if (vm.AddNewDefaultRoleID.length > 0) {
                    angular.forEach(vm.AddNewDefaultRoleID, function (value, key) {
                        if (value == selectFunctionRoleID) {

                            m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: selectFunctionRoleID }, true);
                            if (m.length > 0) {
                                var index = vm.AddNewDefaultRoleID.indexOf(value);
                                if (index > -1) {
                                    vm.AddNewDefaultRoleID.splice(index, 1);
                                }

                            }
                        }
                    });

                }
            }

            vm.CheckRemainRecord();
        }
    }

    vm.removeAdditionalRoles = function (selectFunctionRoleID, index, UnitID) {
    
            if (selectFunctionRoleID != null) {

                vm.AdditionalRolesName.splice(index, 1);
                b = $filter('filter')(vm.additionalUnitandRoles, { ID: UnitID.toString() }, true);
                if (b.length > 0) {
                    m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: parseInt(selectFunctionRoleID) }, true);
                    if (m.length > 0) {
                        b[0].UnitRoleFunctionalID.splice(index, 1);
                        if (b[0].UnitRoleFunctionalID.length == 0 && b[0].ID == UnitID.toString()) {
                            swal("Informasi", "Tiada peranan untuk unit tambahan ini.Unit tambahan tidak akan disimpan.", "warning");
                            vm.showAdditionalRoleNoRecord = true;
                            vm.additionalremoveunit = b[0].ID;
                        }
                        else {
                            vm.showAdditionalRoleNoRecord = false;
                        }

                    }
                }

                if (vm.UserProfileID != "") {
                    m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: selectFunctionRoleID }, true);
                    if (m.length > 0) {
                        vm.AdditionalRolesIDRemove.push(m[0].FunctionalRoleID);
                        vm.AdditionalForUnitID = UnitID;

                    }
                }
            }
      
    }

    vm.deleteUnit = function (selectedUnit) {
  
            swal({
                title: "BATAL UNIT ?",
                text: "Semua peranan di unit ini dihapuskan.",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: true,
                closeOnCancel: true
            }, function (isConfirm) {
                if (isConfirm) {
                    angular.forEach(vm.additionalUnitandRoles, function (obj, i) {
                        if (obj.ID == selectedUnit.ID) {
                            vm.additionalUnitandRoles.splice(i, 1);
                            vm.RemoveUnitAndRoles.push(selectedUnit.ID);
                        }
                    });

                    if (vm.SelectedAdditionalUnitAndRoles.length > 0) {
                        angular.forEach(vm.SelectedAdditionalUnitAndRoles, function (value, key) {
                            if (value.ID == selectedUnit.ID) {
                                vm.SelectedAdditionalUnitAndRoles.splice(key, 1);
                            }
                        });
                    }
                    $scope.$apply();
                }
            });
      
    }

    vm.CheckRemainRecord = function () {
        if (vm.DefaultrolesName == null || vm.DefaultrolesName.length == 0) {
            swal("Gagal", "Sila pilih satu Peranan bagi user ini", "error");
            vm.showRoleNoRecord = true;
        }
        else {
            vm.showRoleNoRecord = false;
        }

    }

    vm.Submit = function (userProfileForm, userApprovalForm, btnId) {

        var result = null;
        var tarikhluput = null;
        var IsEmailValid = null;
        var IsDuplicateUnit = null;
        var DuplicateUnitName = null;
        var isDirty = false;
        var IsNoManagerInExistUnit = null;
        var IsDateToGreatThanDateFrom = null;

        //if reject button is click and remark is null
        if ((vm.Remarks == null || vm.Remarks == "") && btnId == 4) {
            swal("Gagal", "Sila masukkan catatan.", "error");
            var deferred = $q.defer();
            deferred.reject('');
            result = deferred.promise;
            vm.showApprovalValidationMsg = true;
        }
        else if (userProfileForm.$valid && userApprovalForm.$valid)
        {

                if (vm.DefaultrolesName.length > 0) {
                    vm.showDefaultRoleValidationMsg = false;
                }
                else {
                    vm.showDefaultRoleValidationMsg = true;
                }

                if (vm.userList.JawatanID > 0) {
                    vm.showJawatanValidationMsg = false;
                }
                else {
                    vm.userList.JawatanID = null;
                    vm.showValidationMsg = true;
                    vm.showJawatanValidationMsg = true;
                    userProfileForm.$valid = false;
                }

                if (userApprovalForm.$valid) {
                    // optional to fill remark
                    if (vm.Remarks == null || vm.Remarks == undefined) {
                        userApprovalForm.$dirty = true;
                    }

                    if (userProfileForm.$dirty || userApprovalForm.$dirty) {
                        //isDirty = true;
                        var isDirty = userProfileForm.$dirty;
                        //Not Submit button click
                        if (btnId == 2 || btnId == 3 || btnId == 4 || vm.userList.UserProfileID == null || vm.userList.WFStatusID == newStatus || vm.userList.WFStatusID == RejectedStatus)
                        {
                            isDirty = true;
                        }

                        if (vm.AddNewDefaultRoleID.length > 0) {
                            vm.DefaultrolesIDs = vm.AddNewDefaultRoleID.join(" || ");
                        }
                        else {
                            // If user change unit, remain default role for it.
                            if (vm.userList.UnitID != undefined) {
                                if (vm.DefaultUnitID.ID != vm.userList.UnitID.toString()) {
                                    vm.DefaultrolesIDs = vm.DefaultrolesID.join(" || ");
                                }
                                else {
                                    vm.DefaultrolesIDs = vm.DefaultrolesID;
                                }


                            }

                        }

                        if (vm.userList.UnitID != undefined && vm.DefaultUnitID.ID != vm.userList.UnitID.toString()) {
                            if ((vm.userList.ManagerUserProfileID == null || vm.userList.ManagerUserProfileID == 0) && (vm.ManagerProfileID == undefined || vm.ManagerProfileID == "") && (vm.userList.WFStatusID == ClosedStatus)) {
                                IsNoManagerInExistUnit = true;
                            }
                        }

                        //if (vm.TarikhLuput != null && vm.userList.ActiveCondition == Expiry) {
                        //    var tarikhluput = vm.TarikhLuput;
                        //    var dd = tarikhluput.getDate();
                        //    var mm = tarikhluput.getMonth() + 1; //January is 0!
                        //    var yyyy = tarikhluput.getFullYear();

                        //    tarikhluput = mm + '/' + dd + '/' + yyyy;
                        //}

                        if ((vm.DateFrom != null || vm.DateFrom != undefined) && (vm.DateTo != null || vm.DateTo != undefined)) {
                            if (vm.DateFrom > vm.DateTo && vm.userList.ActiveCondition == Dormant) {
                                IsDateToGreatThanDateFrom = true;
                            }
                        }

                        if (vm.userList.Email == undefined) {
                            swal("Gagal", "Sila isi semua ruangan yang bertanda * ", "error");
                            vm.showValidationMsg = true;
                            vm.showInvalidEmailMsg = false;
                            var deferred = $q.defer();
                            deferred.reject('');
                            result = deferred.promise;

                        }
                        else {
                            var IsEmailValid = validateEmail(vm.userList.Email);
                            if (!IsEmailValid) {
                                swal("Gagal", "Format alamat emel tidak sah.", "error");
                                vm.showValidationMsg = false;
                                vm.showInvalidEmailMsg = true;
                                var deferred = $q.defer();
                                deferred.reject('');
                                result = deferred.promise;
                            }
                        }

                        if (vm.additionalUnitandRoles.length > 0 && vm.DefaultUnitID != "") {
                            m = $filter('filter')(vm.additionalUnitandRoles, { ID: vm.DefaultUnitID.ID }, true);
                            if (m.length > 0) {
                                IsDuplicateUnit = true;
                                DuplicateUnitName = m[0].DisplayName;
                            }
                        }

                        m = $filter('filter')(vm.duplicateLoginData, { LoginID: vm.userList.LoginID }, true);
                        if (m.length > 0 && m[0].WFUserProfileID != vm.userList.WFUserProfileID) {
                            swal("Gagal", "Login ID ini telah digunakan.", "error");
                            var deferred = $q.defer();
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if (!IsEmailValid) {
                            swal("Gagal", "Format alamat emel tidak sah.", "error");
                            vm.showValidationMsg = false;
                            vm.showInvalidEmailMsg = true;
                            var deferred = $q.defer();
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if (vm.userList.LoginID == null || vm.userList.LoginID == undefined || vm.userList.LoginID == "") {
                            swal("Gagal", "Login ID perlu diisikan.", "error");
                            var deferred = $q.defer();
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if ((vm.DefaultUnitID == undefined || vm.DefaultUnitID == "") && vm.DefaultrolesIDs == undefined) {
                            swal("Gagal", "Sila isi semua ruangan yang bertanda *", "error");
                            vm.showValidationMsg = true;
                            var deferred = $q.defer();
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if ((vm.DefaultUnitID == undefined || vm.DefaultUnitID == "") && vm.DefaultrolesIDs != undefined) {
                            swal("Gagal", "Sila pilih Jabatan/Cawangan/Unit bagi user ini", "error");
                            vm.showValidationMsg = true;
                            var deferred = $q.defer();
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if ((vm.DefaultUnitID != undefined || vm.DefaultUnitID != "") && vm.DefaultrolesIDs == undefined) {
                            swal("Gagal", "Sila pilih Peranan bagi user ini", "error");
                            vm.showValidationMsg = true;
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if (vm.DefaultrolesName.length == 0) //Check default roles 
                        {
                            swal("Gagal", "Sila pilih Peranan untuk user ini.", "error");
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if (vm.Remarks == null && btnId == 4) {
                            swal("Gagal", "Sila masukkan catatan.", "error");
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if ((vm.DateFrom == null || vm.DateFrom == undefined) && (vm.DateTo == null || vm.DateTo == undefined) && vm.userList.ActiveCondition == Dormant) {
                            swal("Gagal", "Sila pilih Tempoh Dorman(Dari) dan Tempoh Dorman(Hingga)", "error");
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if (vm.DateFrom == null && vm.DateTo != null && vm.userList.ActiveCondition == Dormant) {
                            swal("Gagal", "Sila pilih Tempoh Dorman Tarikh From", "error");
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if (IsDateToGreatThanDateFrom) {
                            swal("Gagal", "Tarikh Dorman(Hingga) mesti melebihi Tarikh Dorman(Dari)", "error");
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if (vm.TarikhLuput == null && vm.userList.ActiveCondition == Expiry) {
                            swal("Gagal", "Sila pilih Tarikh Luput", "error");
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if (tarikhluput < today && vm.userList.ActiveCondition == Expiry) {
                            swal("Gagal", "Tarikh luput tidak boleh sebelum tarikh hari ini", "error");
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if (vm.AdditionalUnitID != "" && vm.AdditionalUnitID != undefined && (vm.AdditionalRoles == undefined || vm.AdditionalRoles.selected.length == 0)) {
                            swal("Gagal", "Sila pilih Peranan bagi Unit Tambahan", "error");
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else if (vm.AdditionalUnitID != "" && vm.AdditionalUnitID != undefined && vm.AdditionalRoles.selected.length > 0) {
                            swal("Gagal", "Sila tekan butang “Tambah Unit Tambahan dan Peranan” sebelum simpan permohonan ini.", "error");
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                        }
                            //Check Additional Unit select duplicate with default unit.
                        else if (IsDuplicateUnit) {
                            swal("Gagal", DuplicateUnitName + " telah dipilih untuk Jabatan/Cawangan/Unit.", "error");
                            var deferred = $q.defer();
                            deferred.reject('');
                            result = deferred.promise;
                        }
                        else
                            ///IF the user plan to change default unit and previous unit didnot have manager
                            if (IsNoManagerInExistUnit) {
                                swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangePengurusUnit, "error");
                                vm.showNoManagerValidationMsg = true;
                                var deferred = $q.defer();
                                deferred.reject('');
                                result = deferred.promise;
                            }
                            else if (vm.Defaultroles != undefined && vm.Defaultroles.selected.length > 0) {
                                swal("Gagal", "Sila tekan butang “Tambah Peranan” sebelum simpan permohonan ini.", "error");
                                var deferred = $q.defer(); // required for click and disabled
                                deferred.reject('');
                                result = deferred.promise;
                                vm.showValidationMsg = true;
                                vm.showInvalidEmailMsg = false;

                            }    // when status is inactive,dormont and luput and no manager for the user inside 
                                //    else if ((vm.userList.ManagerUserProfileID == null || vm.userList.ManagerUserProfileID == 0) && (vm.userList.WFUserProfileID > 0) && (vm.userList.UserProfileID >0) && (vm.userList.ActiveCondition == Dormant || vm.userList.ActiveCondition == Expiry || vm.userList.ActiveCondition == InActive)) {
                                //        swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangePengurusUnit, "error");
                                //    vm.showNoManagerValidationMsg = true;
                                //    var deferred = $q.defer();
                                //    deferred.reject('');
                                //    result = deferred.promise;
                                //}
                            else {
                                //Add new roles for existing additional Unit
                                if (vm.SelectedAdditionalUnitAndRoles == 0 && vm.AdditionalrolesID.length > 0) {
                                    vm.AdditionalrolesID = vm.AdditionalrolesID.join(" || ");
                                    vm.AdditionalUnitID = vm.AdditionalForUnitID;
                                }

                                if (vm.DefaultrolesIDRemove.length > 0) {
                                    isDirty = true;
                                    vm.DefaultrolesIDRemoves = vm.DefaultrolesIDRemove.join(" , ");
                                }

                                if (vm.AdditionalRolesIDRemove.length > 0) {
                                    isDirty = true;
                                    vm.AdditionalRolesIDRemoves = vm.AdditionalRolesIDRemove.join(" , ");
                                }

                                if (vm.RemoveUnitAndRoles.length > 0) {
                                    isDirty = true;
                                    vm.additionalUnitandRoles = "";
                                    vm.RemoveUnitAndRoless = vm.RemoveUnitAndRoles.join(" , ");
                                }

                                if (vm.userList.UserWFActiveCondition != null && vm.userList.UserWFActiveCondition != undefined) {
                                    if (vm.userList.UserWFActiveCondition.DormantDateTo != vm.DateTo) {
                                        isDirty = true;
                                    }
                                }
                                //if (vm.userList.UnitID != undefined) {
                                //    if (vm.DefaultUnitID.ID == vm.userList.UnitID.toString() && userProfileForm.DefaultUnitID.$dirty == true && vm.DefaultUnitID.ID == vm.userList.UnitID.toString() && userProfileForm.DefaultUnitID.$dirty == true && userProfileForm.DefaultRoleName.$dirty == false
                                //&& userProfileForm.ShortName.$dirty == false && userProfileForm.DisplayName.$dirty == false && userProfileForm.Gred.$dirty == false
                                //&& userProfileForm.NRIC.$dirty == false && vm.DefaultrolesIDRemove.length == 0 && vm.AdditionalRolesIDRemove.length == 0 && vm.RemoveUnitAndRoles.length == 0 && userApprovalForm.$dirty == false) {
                                //        isDirty = false;
                                //    }
                                //}

                                if (userProfileForm.$valid) {
                                    if (isDirty) {
                                        getChangeHistory(userProfileForm);
                                        var userModel = {};

                                        if (vm.userList.ActiveCondition == Active) {

                                            vm.DateFrom = null;
                                            vm.DateTo = null;
                                            vm.TarikhLuput = null;
                                            vm.userList.IsActive = true;
                                        }
                                        else {
                                            if (vm.userList.ActiveCondition == InActive) {

                                                vm.DateFrom = null;
                                                vm.DateTo = null;
                                                vm.TarikhLuput = null;
                                                vm.userList.IsActive = false;
                                            }
                                            else if (vm.userList.ActiveCondition == Expiry) {

                                                vm.DateFrom = null;
                                                vm.DateTo = null;
                                                vm.userList.IsActive = true;

                                            }
                                            else {

                                                vm.userList.IsActive = true;
                                                vm.TarikhLuput = null;
                                            }

                                        }

                                        if (vm.userList.UserProfileID > 0) {
                                            if (vm.userList.WFStatusID == ClosedStatus || vm.userList.WFStatusID == null || vm.userList.WFStatusID == newStatus) {
                                                if (vm.userList.ActiveCondition != vm.userList.UserWFActiveCondition.ActiveCondition || vm.DefaultUnitID.ID != vm.userList.UnitID.toString() || vm.DefaultrolesName.length != vm.userList.UserFunctionRoles.length) {
                                                    IsSentForApproval = true;
                                                }
                                                else {
                                                    if (vm.userList.IsSendApproval) {

                                                        IsSentForApproval = vm.userList.IsSendApproval;
                                                    }
                                                    else {

                                                        IsSentForApproval = false
                                                    }

                                                }
                                            }
                                            else {
                                                IsSentForApproval = true;
                                            }
                                        }
                                        else {
                                            IsSentForApproval = true;
                                        }


                                        // Pending Review
                                        if (btnId == 1) {
                                            var userWorkflowModel = {
                                                DecisionID: 59,
                                                Remarks: vm.Remarks

                                            }

                                            userModel = {
                                                WFUserProfileID: vm.userList.WFUserProfileID,
                                                UserProfileID: vm.userList.UserProfileID,
                                                Gred: vm.userList.Gred == null ? "" : vm.userList.Gred,
                                                NRIC: vm.userList.NRIC == null ? "" : vm.userList.NRIC,
                                                UnitID: (vm.DefaultUnitID == undefined || vm.DefaultUnitID == "") ? 0 : vm.DefaultUnitID.ID == "0" ? 0 : parseInt(vm.DefaultUnitID.ID),
                                                ManagerUserProfileID: (vm.ManagerProfileID == undefined || vm.ManagerProfileID == "") ? 0 : vm.ManagerProfileID.UserProfileID == 0 ? 0 : vm.ManagerProfileID.UserProfileID,
                                                LoginID: vm.userList.LoginID,
                                                DisplayName: vm.userList.DisplayName,
                                                Email: vm.userList.Email,
                                                IsActive: vm.userList.IsActive,
                                                DefaultRolesID: vm.DefaultrolesIDs == null ? 0 : vm.DefaultrolesIDs,
                                                RemoveDefaultRolesID: vm.DefaultrolesIDRemoves == null ? 0 : vm.DefaultrolesIDRemoves,
                                                RemoveUnitAndRoles: vm.RemoveUnitAndRoless == null ? 0 : vm.RemoveUnitAndRoless,
                                                RemoveAdditionalRolesID: vm.AdditionalRolesIDRemoves == null ? 0 : vm.AdditionalRolesIDRemoves,
                                                JawatanID: vm.userList.JawatanID, // CR Jan2020 (Chew)
                                                ShortName: vm.userList.ShortName,
                                                AdditionalRolesID: vm.AdditionalrolesID == null ? 0 : vm.AdditionalrolesID,
                                                AdditionalUnitID: (vm.AdditionalUnitID == undefined || vm.AdditionalUnitID == "") ? 0 : vm.AdditionalUnitID.ID == "0" ? 0 : parseInt(vm.AdditionalUnitID.ID),
                                                AdditionalManagerID: (vm.AdditionalUnitID == undefined || vm.AdditionalUnitID == "") ? 0 : vm.AdditionalUnitID.ID == "0" ? 0 : parseInt(vm.AdditionalUnitID.ManagerId),
                                                ChangeUnitAdditionManager: vm.lstAdditionUserManager,///vm.ChangeAdditionUserManager.ManagerId,
                                                RemoveAdditionalUnitID: vm.AdditionalForUnitID,
                                                RemoveUnitAdditionManager: vm.lstRemoveAdditionUserManager,
                                                UserAdditionalUnitAndRoles: vm.SelectedAdditionalUnitAndRoles,
                                                Remarks: vm.Remarks,
                                                IsSubmitReviewAction: true,
                                                IsSubmitApprovalAction: false,
                                                IsApproveAction: false,
                                                UserWorkFlow: userWorkflowModel,
                                                ExpiryDate: (vm.TarikhLuput == undefined || vm.TarikhLuput == null) ? null : $filter('date')(vm.TarikhLuput, $scope.DateTimeFormat),
                                                DormantDateFrom: (vm.DateFrom == undefined || vm.DateFrom == null) ? null : $filter('date')(vm.DateFrom, $scope.DateTimeFormat),
                                                DormantDateTo: (vm.DateTo == undefined || vm.DateTo == null) ? null : $filter('date')(vm.DateTo, $scope.DateTimeFormat),
                                                ActiveCondition: vm.userList.ActiveCondition,
                                                IsSendApproval: IsSentForApproval,
                                                IsSubmitButtonClick: true

                                            }
                                        }
                                        else if (btnId == 2) {
                                            var userWorkflowModel = {
                                                DecisionID: 60,
                                                WFUserProfileID: vm.userList.WFUserProfileID
                                            }
                                            // Pending Approval
                                            userModel = {
                                                WFUserProfileID: vm.userList.WFUserProfileID,
                                                UserProfileID: vm.userList.UserProfileID,
                                                Gred: vm.userList.Gred == null ? "" : vm.userList.Gred,
                                                NRIC: vm.userList.NRIC == null ? "" : vm.userList.NRIC,
                                                UnitID: (vm.DefaultUnitID == undefined || vm.DefaultUnitID == "") ? 0 : vm.DefaultUnitID.ID == "0" ? 0 : parseInt(vm.DefaultUnitID.ID),
                                                ManagerUserProfileID: (vm.ManagerProfileID == undefined || vm.ManagerProfileID == "") ? 0 : vm.ManagerProfileID.UserProfileID == 0 ? 0 : vm.ManagerProfileID.UserProfileID,
                                                LoginID: vm.userList.LoginID,
                                                DisplayName: vm.userList.DisplayName,
                                                Email: vm.userList.Email,
                                                IsActive: vm.userList.IsActive,
                                                DefaultRolesID: vm.DefaultrolesIDs == null ? 0 : vm.DefaultrolesIDs,
                                                RemoveDefaultRolesID: vm.DefaultrolesIDRemoves == null ? 0 : vm.DefaultrolesIDRemoves,
                                                RemoveUnitAndRoles: vm.RemoveUnitAndRoless == null ? 0 : vm.RemoveUnitAndRoless,
                                                RemoveAdditionalRolesID: vm.AdditionalRolesIDRemoves == null ? 0 : vm.AdditionalRolesIDRemoves,
                                                JawatanID: vm.userList.JawatanID, // CR Jan2020 (Chew)
                                                ShortName: vm.userList.ShortName,
                                                AdditionalRolesID: vm.AdditionalrolesID == null ? 0 : vm.AdditionalrolesID,
                                                AdditionalUnitID: (vm.AdditionalUnitID == undefined || vm.AdditionalUnitID == "") ? 0 : vm.AdditionalUnitID.ID == "0" ? 0 : parseInt(vm.AdditionalUnitID.ID),
                                                AdditionalManagerID: (vm.AdditionalUnitID == undefined || vm.AdditionalUnitID == "") ? 0 : vm.AdditionalUnitID.ID == "0" ? 0 : parseInt(vm.AdditionalUnitID.ManagerId),
                                                ChangeUnitAdditionManager: vm.lstAdditionUserManager,///vm.ChangeAdditionUserManager.ManagerId,
                                                RemoveAdditionalUnitID: vm.AdditionalForUnitID,
                                                RemoveUnitAdditionManager: vm.lstRemoveAdditionUserManager,
                                                UserAdditionalUnitAndRoles: vm.SelectedAdditionalUnitAndRoles,
                                                Remarks: vm.Remarks,
                                                IsSubmitReviewAction: false,
                                                IsSubmitApprovalAction: true,
                                                IsApproveAction: false,
                                                UserWorkFlow: userWorkflowModel,
                                                ExpiryDate: (vm.TarikhLuput == undefined || vm.TarikhLuput == null) ? null : $filter('date')(vm.TarikhLuput, $scope.DateTimeFormat),
                                                DormantDateFrom: (vm.DateFrom == undefined || vm.DateFrom == null) ? null : $filter('date')(vm.DateFrom, $scope.DateTimeFormat),
                                                DormantDateTo: (vm.DateTo == undefined || vm.DateTo == null) ? null : $filter('date')(vm.DateTo, $scope.DateTimeFormat),
                                                ActiveCondition: vm.userList.ActiveCondition,
                                                IsSendApproval: IsSentForApproval,
                                                IsSubmitButtonClick: true

                                            }
                                        }
                                        else if (btnId == 3) {
                                            //Approved
                                            var userWorkflowModel = {
                                                DecisionID: 61,
                                                WFUserProfileID: vm.userList.WFUserProfileID
                                            }
                                            // Approved
                                            userModel = {
                                                WFUserProfileID: vm.userList.WFUserProfileID,
                                                UserProfileID: vm.userList.UserProfileID,
                                                Gred: vm.userList.Gred == null ? "" : vm.userList.Gred,
                                                NRIC: vm.userList.NRIC == null ? "" : vm.userList.NRIC,
                                                UnitID: (vm.DefaultUnitID == undefined || vm.DefaultUnitID == "") ? 0 : vm.DefaultUnitID.ID == "0" ? 0 : parseInt(vm.DefaultUnitID.ID),
                                                ManagerUserProfileID: (vm.ManagerProfileID == undefined || vm.ManagerProfileID == "") ? 0 : vm.ManagerProfileID.UserProfileID == 0 ? 0 : vm.ManagerProfileID.UserProfileID,
                                                LoginID: vm.userList.LoginID,
                                                DisplayName: vm.userList.DisplayName,
                                                Email: vm.userList.Email,
                                                IsActive: vm.userList.IsActive,
                                                DefaultRolesID: vm.DefaultrolesIDs == null ? 0 : vm.DefaultrolesIDs,
                                                RemoveDefaultRolesID: vm.DefaultrolesIDRemoves == null ? 0 : vm.DefaultrolesIDRemoves,
                                                RemoveUnitAndRoles: vm.RemoveUnitAndRoless == null ? 0 : vm.RemoveUnitAndRoless,
                                                RemoveAdditionalRolesID: vm.AdditionalRolesIDRemoves == null ? 0 : vm.AdditionalRolesIDRemoves,
                                                JawatanID: vm.userList.JawatanID, // CR Jan2020 (Chew)
                                                ShortName: vm.userList.ShortName,
                                                AdditionalRolesID: vm.AdditionalrolesID == null ? 0 : vm.AdditionalrolesID,
                                                AdditionalUnitID: (vm.AdditionalUnitID == undefined || vm.AdditionalUnitID == "") ? 0 : vm.AdditionalUnitID.ID == "0" ? 0 : parseInt(vm.AdditionalUnitID.ID),
                                                AdditionalManagerID: (vm.AdditionalUnitID == undefined || vm.AdditionalUnitID == "") ? 0 : vm.AdditionalUnitID.ID == "0" ? 0 : parseInt(vm.AdditionalUnitID.ManagerId),
                                                ChangeUnitAdditionManager: vm.lstAdditionUserManager,///vm.ChangeAdditionUserManager.ManagerId,
                                                RemoveAdditionalUnitID: vm.AdditionalForUnitID,
                                                RemoveUnitAdditionManager: vm.lstRemoveAdditionUserManager,
                                                UserAdditionalUnitAndRoles: vm.SelectedAdditionalUnitAndRoles,
                                                Remarks: vm.Remarks,
                                                IsSubmitReviewAction: false,
                                                IsSubmitApprovalAction: false,
                                                IsApproveAction: true,
                                                UserWorkFlow: userWorkflowModel,
                                                ExpiryDate: (vm.TarikhLuput == undefined || vm.TarikhLuput == null) ? null : $filter('date')(vm.TarikhLuput, $scope.DateTimeFormat),
                                                DormantDateFrom: (vm.DateFrom == undefined || vm.DateFrom == null) ? null : $filter('date')(vm.DateFrom, $scope.DateTimeFormat),
                                                DormantDateTo: (vm.DateTo == undefined || vm.DateTo == null) ? null : $filter('date')(vm.DateTo, $scope.DateTimeFormat),
                                                ActiveCondition: vm.userList.ActiveCondition,
                                                IsSendApproval: IsSentForApproval,
                                                IsSubmitButtonClick: true

                                            }

                                        }
                                        else {
                                            //Reject 
                                            var userWorkflowModel = {
                                                DecisionID: 62,
                                                WFUserProfileID: vm.userList.WFUserProfileID
                                            }
                                            // Reject
                                            userModel = {
                                                WFUserProfileID: vm.userList.WFUserProfileID,
                                                UserProfileID: vm.userList.UserProfileID,
                                                Gred: vm.userList.Gred == null ? "" : vm.userList.Gred,
                                                NRIC: vm.userList.NRIC == null ? "" : vm.userList.NRIC,
                                                UnitID: (vm.DefaultUnitID == undefined || vm.DefaultUnitID == "") ? 0 : vm.DefaultUnitID.ID == "0" ? 0 : parseInt(vm.DefaultUnitID.ID),
                                                ManagerUserProfileID: (vm.ManagerProfileID == undefined || vm.ManagerProfileID == "") ? 0 : vm.ManagerProfileID.UserProfileID == 0 ? 0 : vm.ManagerProfileID.UserProfileID,
                                                LoginID: vm.userList.LoginID,
                                                DisplayName: vm.userList.DisplayName,
                                                Email: vm.userList.Email,
                                                IsActive: vm.userList.IsActive,
                                                DefaultRolesID: vm.DefaultrolesIDs == null ? 0 : vm.DefaultrolesIDs,
                                                RemoveDefaultRolesID: vm.DefaultrolesIDRemoves == null ? 0 : vm.DefaultrolesIDRemoves,
                                                RemoveUnitAndRoles: vm.RemoveUnitAndRoless == null ? 0 : vm.RemoveUnitAndRoless,
                                                RemoveAdditionalRolesID: vm.AdditionalRolesIDRemoves == null ? 0 : vm.AdditionalRolesIDRemoves,
                                                JawatanID: vm.userList.JawatanID, // CR Jan2020 (Chew)
                                                ShortName: vm.userList.ShortName,
                                                AdditionalRolesID: vm.AdditionalrolesID == null ? 0 : vm.AdditionalrolesID,
                                                AdditionalUnitID: (vm.AdditionalUnitID == undefined || vm.AdditionalUnitID == "") ? 0 : vm.AdditionalUnitID.ID == "0" ? 0 : parseInt(vm.AdditionalUnitID.ID),
                                                AdditionalManagerID: (vm.AdditionalUnitID == undefined || vm.AdditionalUnitID == "") ? 0 : vm.AdditionalUnitID.ID == "0" ? 0 : parseInt(vm.AdditionalUnitID.ManagerId),
                                                ChangeUnitAdditionManager: vm.lstAdditionUserManager,///vm.ChangeAdditionUserManager.ManagerId,
                                                RemoveAdditionalUnitID: vm.AdditionalForUnitID,
                                                RemoveUnitAdditionManager: vm.lstRemoveAdditionUserManager,
                                                UserAdditionalUnitAndRoles: vm.SelectedAdditionalUnitAndRoles,
                                                Remarks: vm.Remarks,
                                                IsSubmitReviewAction: false,
                                                IsSubmitApprovalAction: false,
                                                IsApproveAction: false,
                                                IsRejectAction: true,
                                                UserWorkFlow: userWorkflowModel,
                                                ExpiryDate: (vm.TarikhLuput == undefined || vm.TarikhLuput == null) ? null : $filter('date')(vm.TarikhLuput, $scope.DateTimeFormat),
                                                DormantDateFrom: (vm.DateFrom == undefined || vm.DateFrom == null) ? null : $filter('date')(vm.DateFrom, $scope.DateTimeFormat),
                                                DormantDateTo: (vm.DateTo == undefined || vm.DateTo == null) ? null : $filter('date')(vm.DateTo, $scope.DateTimeFormat),
                                                ActiveCondition: vm.userList.ActiveCondition,
                                                IsSendApproval: IsSentForApproval,
                                                IsSubmitButtonClick: true

                                            }
                                        }

                                        var model = {
                                            WFUserProfile: userModel,
                                            ChangeHistory: vm.changesHistory
                                        }

                                        if (IsSentForApproval) {

                                           if (btnId == 1) {
                                                var promptMessage = "Kemaskini profil dihantar untuk semakan dan kelulusan";
                                                            }
                                            else if (btnId == 2) {
                                                var promptMessage = "Kemaskini profil dihantar untuk kelulusan JOC";
                                            }
                                            else if (btnId == 3)
                                                                {
                                                var promptMessage = "Permohonan diluluskan JOC";
                                            }
                                            else if (vm.isApprovedLogin)
                                            {
                                                var promptMessage = "Permohonan ditolak JOC";
                                            }
                                            else
                                            {
                                                var promptMessage = "Permohonan ditolak";
                                            }

                                            swal({
                                                title: promptMessage ,
                                                text: "",
                                                type: "warning",
                                                showCancelButton: true,
                                                confirmButtonText: "Ya",
                                                cancelButtonText: "Tidak",
                                                closeOnConfirm: false,
                                                closeOnCancel: false
                                            }, function (isConfirm) {
                                                if (isConfirm) {
                                                    UserSI.updateWFUserProfileDetail(model).then(function (r) {
                                                        if (r.status === 200) {
                                                            if (r.data) {
                                                                if (r.data.WFUserProfile.WFStatusID == -1) {
                                                                    swal("Gagal", " Tiada reviewer dalam unit anda", "error");
                                                                    vm.userList.IsActive = r.data.WFUserProfile.ActiveCondition;
                                                                    var deferred = $q.defer(); // required for click and disabled
                                                                    deferred.reject('');
                                                                    result = deferred.promise;
                                                                }
                                                                else if (r.data.WFUserProfile.WFStatusID == -2) {

                                                                    swal("Gagal", "Tiada approver", "error");
                                                                    vm.userList.IsActive = r.data.WFUserProfile.ActiveCondition;
                                                                    var deferred = $q.defer(); // required for click and disabled
                                                                    deferred.reject('');
                                                                    result = deferred.promise;
                                                                }
                                                                else if (r.data.WFUserProfile.WFUserProfileID == -1) {
                                                                    swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangePengurusUnit, "error");
                                                                    vm.userList.IsActive = r.data.WFUserProfile.ActiveCondition;
                                                                    GetDefaultUnitByUnitID(vm.userList.UnitID.toString());
                                                                }
                                                                else {
                                                                     
                                                                    if (btnId == 1 || btnId == 2)
                                                                    {
                                                                        swal({
                                                                            title: "Semakan Berjaya.",
                                                                            text: "Dihantar Untuk Kelulusan JOC. ",
                                                                            type: "success",
                                                                            timer: 2500,
                                                                            showConfirmButton: false
                                                                        }, function () {
                                                                            window.open('', '_self', '');
                                                                            window.close();
                                                                            //vm.redirectTo('/UserRequest/Profile/Detail/' + r.data.WFUserProfile.WFUserProfileID);
                                                                        });
                                                                    }
                                                                    else if (btnId == 3)
                                                                    {
                                                                        swal({
                                                                            title: "Kelulusan Berjaya",
                                                                            type: "success",
                                                                            timer: 2500,
                                                                            showConfirmButton: false
                                                                        }, function () {
                                                                            //vm.redirectTo('/UserRequest/Search');
                                                                            window.open('', '_self', '');
                                                                            window.close();
                                                                        });
                                                                    }
                                                                    else if(vm.isApprovedLogin) // If reject
                                                                    {
                                                                        swal({
                                                                            title: "Permohonan ditolak JOC",
                                                                            type: "success",
                                                                            timer: 2500,
                                                                            showConfirmButton: false
                                                                        }, function () {
                                                                            //vm.redirectTo('/UserRequest/Search');
                                                                            window.open('', '_self', '');
                                                                            window.close();
                                                                        });
                                                                    }
                                                                    else
                                                                    {
                                                                        swal({
                                                                            title: "Permohonan ditolak",
                                                                            type: "success",
                                                                            timer: 2500,
                                                                            showConfirmButton: false
                                                                        }, function () {
                                                                            //vm.redirectTo('/UserRequest/Search');
                                                                            window.open('', '_self', '');
                                                                            window.close();
                                                                        });
                                                                    }
                                                                  
                                                                }
                                                                  
                                                                  
                                                            }
                                                            else {
                                                                swal("Gagal", r.data, "error");
                                                                var deferred = $q.defer();
                                                                deferred.reject('');
                                                                result = deferred.promise;
                                                            }

                                                        } else {
                                                            swal("Gagal", r.data, "error");
                                                            var deferred = $q.defer();
                                                            deferred.reject('');
                                                            result = deferred.promise;
                                                        }

                                                    });

                                                }
                                                else {
                                                    swal("Batal!", "Permohonan telah dibatalkan.", "error");

                                                }
                                            });
                                        }
                                        else {
                                            swal({
                                                title: "Kemaskini profil dihantar untuk semakan. ",
                                                text: "",
                                                type: "warning",
                                                showCancelButton: true,
                                                confirmButtonText: "Ya",
                                                cancelButtonText: "Tidak",
                                                closeOnConfirm: false,
                                                closeOnCancel: false
                                            }, function (isConfirm) {
                                                if (isConfirm) {
                                                    UserSI.updateWFUserProfileDetail(model).then(function (r) {
                                                        if (r.status === 200) {
                                                            if (r.data) {
                                                                if (r.data.WFUserProfile.WFStatusID == -1) {
                                                                    swal("Gagal", " Tiada reviewer dalam unit anda", "error");
                                                                    vm.userList.IsActive = r.data.WFUserProfile.ActiveCondition;
                                                                    var deferred = $q.defer(); // required for click and disabled
                                                                    deferred.reject('');
                                                                    result = deferred.promise;
                                                                }
                                                                else if (r.data.WFUserProfile.WFStatusID == -2) {

                                                                    swal("Gagal", "Tiada approver", "error");
                                                                    vm.userList.IsActive = r.data.WFUserProfile.ActiveCondition;
                                                                    var deferred = $q.defer(); // required for click and disabled
                                                                    deferred.reject('');
                                                                    result = deferred.promise;
                                                                }
                                                                else if (r.data.WFUserProfile.WFUserProfileID == -1) {
                                                                    swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangePengurusUnit, "error");
                                                                    vm.userList.IsActive = r.data.WFUserProfile.ActiveCondition;
                                                                    GetDefaultUnitByUnitID(vm.userList.UnitID.toString());
                                                                }
                                                                else {
                                                                    swal({
                                                                        title: "Semakan Berjaya!",
                                                                        type: "success",
                                                                        timer: 2500,
                                                                        showConfirmButton: false
                                                                    }, function () {
                                                                        window.open('', '_self', '');
                                                                        window.close();
                                                                        //vm.redirectTo('/UserRequest/Profile/Detail/' + r.data.WFUserProfile.WFUserProfileID);
                                                                    });
                                                                }

                                                            }
                                                            else {
                                                                swal("Gagal", r.data, "error");
                                                                var deferred = $q.defer();
                                                                deferred.reject('');
                                                                result = deferred.promise;
                                                            }

                                                        } else {
                                                            swal("Gagal", r.data, "error");
                                                            var deferred = $q.defer();
                                                            deferred.reject('');
                                                            result = deferred.promise;
                                                        }

                                                    });

                                                }
                                                else {
                                                    swal("Batal!", "Permohonan telah dibatalkan.", "error");

                                                }
                                            });
                                        }


                                        var deferred = $q.defer(); // required for click and disabled
                                        deferred.reject('');
                                        result = deferred.promise;
                                    }
                                    else {
                                        swal("Gagal", "Tiada perubahan maklumat dilakukan!", "error");
                                        var deferred = $q.defer(); // required for click and disabled
                                        deferred.reject('');
                                        result = deferred.promise;
                                    }
                                }
                                else {
                                    swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
                                    var deferred = $q.defer(); // required for click and disabled
                                    deferred.reject('');
                                    result = deferred.promise;
                                    vm.showValidationMsg = true;
                                }
                            }
                    }
                    else {
                        swal("Gagal", "Tiada perubahan maklumat dilakukan!", "error");
                        var deferred = $q.defer(); // required for click and disabled
                        deferred.reject('');
                        result = deferred.promise;
                    }
                }
                else {
                    swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                    vm.showValidationMsg = true;
                    vm.showJawatanValidationMsg = true;
                }

              
        }
        else
        {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            if (!userProfileForm.$valid && !userApprovalForm.$valid)
            {
                vm.showValidationMsg = true;
                vm.showApprovalValidationMsg = true;
            }
            else if (!userApprovalForm.$valid && userProfileForm.$valid)
            {
                vm.showApprovalValidationMsg = true;
            }
            else if (userApprovalForm.$valid && !userProfileForm.$valid)
            {
                vm.showValidationMsg = true;
            }

            if (vm.DefaultrolesName.length > 0) {
                vm.showDefaultRoleValidationMsg = false;
            }
            else {
                vm.showDefaultRoleValidationMsg = true;
            }
                    vm.showJawatanValidationMsg = true;
            var deferred = $q.defer(); // required for click and disabled
            deferred.reject('');
            result = deferred.promise;
            
        }

        return result;
    }


    $scope.CheckDuplicateLogin = function (userloginID) {    
        if (userloginID != undefined && userloginID != "" && userloginID != null) {
            UserSI.checkWFUserDuplicateLogin(userloginID).then(function (r) {
                if (r.status === 200) {
                    vm.duplicateLoginData = r.data;
                    if (r.data != null && r.data.length > 0) {
                        if (r.data[0].WFUserProfileID != vm.userList.WFUserProfileID) {
                            vm.userList.LoginID = "";
                            vm.userList.DisplayName = "";
                            vm.userList.Gred = "";
                            vm.userList.NRIC = "";
                            swal("Gagal", "User ini telah wujud dalam system.", "error");
                            vm.showInvalidLoginMsg = true;
                        }
                        else {
                            vm.showInvalidLoginMsg = false;
                        }
                    }
                    else {
                        vm.showInvalidLoginMsg = false;
                    }

                }
            });
        }

    }

    function getDDLOptions() {
        var deferred = $q.defer();
        UserSI.getUserGroupHierarcyOptions().then(function (r) {
            if (r.status === 200) {
                deferred.resolve(r.data);
            }
        });
        return deferred.promise;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');

            if (value.$pristine == false) {
                var newvalue = "";
                if ($(document.getElementById(key))[0].tagName == 'SELECT' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if ($(document.getElementById(key))[0]) {
                        if ($(document.getElementById(key))[0].selectedIndex && $(document.getElementById(key))[0].selectedIndex >= 0)
                            newvalue = $(document.getElementById(key))[0].options[$(document.getElementById(key))[0].selectedIndex].text;
                    }
                }
                else if ($(document.getElementById(key))[0].tagName == 'INPUT' && $(document.getElementById(key))[0].type == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    newvalue = value.$viewValue;
                }
                else {
                    newvalue = value.$viewValue;
                }

                vm.changesHistory.push({
                    ID: vm.WFConfigID,
                    FieldName: key,
                    DisplayName: displayName,
                    OldValue: '',
                    NewValue: newvalue,
                    IsChanged: !value.$pristine
                });
            }
        });
    };

    function validateEmail(email) {
        var re = GeneralService.Validation.Email;
        return re.test(String(email).toLowerCase());
    }

    function GetDefaultUnitByUnitID(DefaultUnitID)
    {
        m = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, { ID: DefaultUnitID }, true);
        if (m.length > 0) {
            //vm.editing.DefaultUnitID = m[0].Value;
            vm.DefaultUnitID = m[0];
        }
        else {
            m = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, { ID: DefaultUnitID }, true);
            if (m.length > 0) {
                vm.DefaultUnitID = m[0];
            }
            else {
                m = $filter('filter')(vm.WorkflowAssignToJabatanOptionDocUnit, { ID: DefaultUnitID }, true);
                if (m.length > 0) {
                    vm.DefaultUnitID = m[0];
                }
                else {
                    m = $filter('filter')(vm.WorkflowAssignToSeksyenOptionDocUnit, { ID: DefaultUnitID }, true);
                    if (m.length > 0) {
                        vm.DefaultUnitID = m[0];
                    }
                    else {
                        vm.userList.UnitID = "";
                    }

                }

            }

        }

        if (vm.userList.ManagerUserProfileID != null && vm.userList.ManagerUserProfileID > 0) {
            ManagerID = vm.userList.ManagerUserProfileID;
            vm.UserResultOption = vm.UserManagerResultOption;

            if (ManagerID != "") {
                vm.ManagerProfileID = vm.UserResultOption[0];
                vm.NoUserMessage = false;
            }
        }
    }

    vm.GetUserFromAD = function () {
        if (vm.userList.Email != null && vm.userList.Email != undefined && vm.userList.Email != "") {

            UserSI.getUserFromAD(vm.userList.Email).then(function (r) {
                if (r.status === 200) {
                    if (r.data != null && r.data["LoginID"] != null) {            
                        UserSI.checkWFUserDuplicateLogin(r.data["LoginID"]).then(function (u) {
                            if (u.status === 200) {                              
                                if (u.data != null && u.data.length > 0) {
                                    vm.userList.LoginID = "";
                                    vm.userList.DisplayName = "";
                                    vm.userList.Gred = "";
                                    vm.userList.NRIC = "";
                                    swal("Informasi", "User ini telah wujud dalam sistem.", "warning");
                                }
                                else {
                                    vm.userList.LoginID = r.data["LoginID"];
                                    vm.userList.DisplayName = r.data["DisplayName"];
                                    vm.userList.Gred = r.data["Gred"];
                                    vm.userList.NRIC = r.data["NRIC"];
                                }
                            }
                        });
                    }
                    else {
                        swal("Gagal", "Emel ini tidak wujud dalam AD.", "error");
                    }
                }
                else {
                    swal("Gagal", "Connection failed to AD.", "error");
                }

            });
        }
        else {
            swal("Gagal", "Sila masukkan Emel.", "error");
        }
    }

    // datepicker
    vm.openDateFrom = function () {
        if (vm.IsCurrentLogin == 0 || vm.userList.WFStatusID == ApprovedStatus) {
            vm.dateFromOpened = false;
        }
        else {
            vm.dateFromOpened = true;
        }
    };

    vm.openDateTo = function () {
        if (vm.IsCurrentLogin == 0 || vm.userList.WFStatusID == ApprovedStatus)
        {
            vm.dateToOpened = false;
        }
        else
        {
            vm.dateToOpened = true;
        }
      
    };

    vm.clearDateFrom = function () {
       // if (vm.IsCurrentLogin > 0) {
            vm.DateFrom = null;
       // }
    
    };
    vm.clearDateTo = function () {
        //if (vm.IsCurrentLogin > 0)
        //{
            vm.DateTo = null;
        //}
       
    };

    vm.clearTarikhDaftar = function () {
        //if (vm.IsCurrentLogin > 0) {
            vm.TarikhLuput = '';
       // }
        
    }

    vm.OpenHideAktiveCondition = function(id,objUnit)
    {
        if (id == Dormant)
        {
            vm.showDormanDate = true;
            vm.showExpiryDate = false;

            if ((vm.userList.ManagerUserProfileID == null || vm.userList.ManagerUserProfileID == 0) && vm.userList.WFUserProfileID > 0) {
                swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangePengurusUnit, "error");
                vm.showNoManagerValidationMsg = true;
            }
            else
            {
                SearchUserByUnitID(objUnit.ID);
            }

            //SearchUserByUnitID(objUnit.ID);
        }
        else if (id == Expiry)
        {
            vm.showExpiryDate = true;
            vm.showDormanDate = false;
            if ((vm.userList.ManagerUserProfileID == null || vm.userList.ManagerUserProfileID == 0) && vm.userList.WFUserProfileID > 0) {
                swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangePengurusUnit, "error");
                vm.showNoManagerValidationMsg = true;
            }
            else
            {
                SearchUserByUnitID(objUnit.ID);
            }
           
        }
        else if (id == InActive)
        {
            vm.showExpiryDate = false;
            vm.showDormanDate = false;
            if ((vm.userList.ManagerUserProfileID == null || vm.userList.ManagerUserProfileID == 0) && vm.userList.WFUserProfileID > 0) {
                swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangePengurusUnit, "error");
                vm.showNoManagerValidationMsg = true;
            }
            else
            {
                SearchUserByUnitID(objUnit.ID);
            }
            //SearchUserByUnitID(objUnit.ID);
        }
        else {
            vm.showExpiryDate = false;
            vm.showDormanDate = false;
        }
    }

    vm.cancelRequest = function()
    {
        var result = null;

            var userWorkflowModel = {
                DecisionID: CancelRequest,
                Remarks: vm.Remarks

            }

            var usermodel = {
                WFUserProfileID: vm.userList.WFUserProfileID,
                UserProfileID: vm.userList.UserProfileID,
                UserWorkFlow: userWorkflowModel
            }

            var model = {
                WFUserProfile: usermodel
            }

            swal({
                title: "Adakah Anda mahu batalkan permohonan pengguna ini? ",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Ya",
                cancelButtonText: "Tidak",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    UserSI.cancelRequestWFUserProfile(model).then(function (r) {
                        if (r.status === 200) {
                            if (r.data != null) {
                                if (r.data.WFUserProfileID > 0) {
                                    vm.redirectTo('/UserRequest/Profile/Detail/' + r.data.WFUserProfileID);
                                }
                            }
                            else {
                                vm.redirectTo('/UserRequest/Search/');
                            }
                        }
                        else {
                            swal("Gagal", r.data, "error");
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                        }
                    });
                }
                else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                  
                }
            });

            var deferred = $q.defer(); 
            deferred.reject('');
            result = deferred.promise;
      

        return result;
    }

    // For Pengurus Additional Unit - Start
    vm.ShowFilterPengurusAdditionUnitOption = function () {
        if (!vm.showPengurusAdditionUnitDetail) {
            vm.showPengurusAdditionUnitDetail = true;

            if (vm.AdditionalUnitID != null) {
                SearchHierachyByAdditionUnit(vm.AdditionalUnitID)
            }
            else {
                vm.SelectedTimbalanAdditionUser = "";
                vm.SelectedJabatanAdditionUser = "";
                vm.SelectedCawanganAdditionUser = "";
                vm.SelectedUnitsAdditionUser = "";

                vm.SeksyenUserAdditionEnabled = false;
                vm.JabatanUserAdditionEnabled = false;
                vm.CawanganUserAdditionEnabled = false;
            }

        }
        else {
            vm.showPengurusAdditionUnitDetail = false;
        }
    }

    function SearchHierachyByAdditionUnit(SelectedAdditionUnit) {

        if (vm.AdditionalUnitID != null) {
            if (vm.AdditionalUnitID.HierarchyType == 37) {
                //var model = vm.DefaultUnitID.AdditionalInfo.split(".");
                m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, {
                    ID: SelectedAdditionUnit.SeksyenID.toString()
                }, true);
                if (m.length > 0) {
                    vm.SelectedTimbalanAdditionUser = m[0].ID;
                    vm.JabatanUserAdditionEnabled = false;
                    if (vm.SelectedTimbalanAdditionUser != null) {
                        vm.SeksyenUserAdditionEnabled = false;

                        b = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, {
                            ID: SelectedAdditionUnit.JabatanID.toString()
                        }, true);

                        vm.filteredWorkflowAssignToJabatanUserOption = b;
                        vm.SelectedJabatanAdditionUser = b[0].ID;
                        if (vm.SelectedJabatanAdditionUser != null) {
                            var m = $filter('filter')(vm.WorkflowAssignToCawanganUserOption, { ParentUnitID: parseInt(vm.SelectedJabatanAdditionUser) }, true);
                            if (m != undefined && m.length != 0) {

                                vm.filteredWorkflowAssignToCawanganUserOption = m;
                                var m = $filter('filter')(vm.filteredWorkflowAssignToCawanganUserOption, { ID: SelectedAdditionUnit.CawanganID.toString() }, true);
                                if (m.length > 0) {
                                    vm.SelectedCawanganAdditionUser = m[0].ID;
                                    var m = $filter('filter')(vm.WorkflowAssignToUnitUserOption, { ParentUnitID: parseInt(vm.SelectedCawanganAdditionUser) }, true);
                                    if (m.length > 0) {
                                        vm.filteredWorkflowAssignToUnitUserOption = m;
                                        var m = $filter('filter')(vm.filteredWorkflowAssignToUnitUserOption, { ID: SelectedAdditionUnit.ID.toString() }, true);
                                        vm.SelectedUnitsAdditionUser = m[0].ID;
                                        SearchAdditionUnitUserByUnitID(vm.SelectedUnitsAdditionUser);

                                    }
                                }

                            }

                            vm.CawanganUserAdditionEnabled = true;
                            vm.UnitUserAdditionEnabled = true;
                        }
                    }
                }

            }
            else
                if (vm.AdditionalUnitID.HierarchyType == 36) {
                    //var model = vm.DefaultUnitID.AdditionalInfo.split(".");
                    m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, { ID: SelectedAdditionUnit.SeksyenID.toString() }, true);
                    if (m.length > 0) {
                        vm.SelectedTimbalanAdditionUser = m[0].ID;
                        //vm.JabatanUserEnabled = false;
                        if (vm.SelectedTimbalanAdditionUser != null) {
                            vm.SeksyenUserAdditionEnabled = false;
                            vm.JabatanUserAdditionEnabled = true;
                            vm.SelectedCawanganAdditionUser = false;
                            vm.CawanganUserAdditionEnabled = true;

                            b = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, { ParentUnitID: parseInt(vm.SelectedTimbalanAdditionUser) }, true);

                            vm.filteredWorkflowAssignToJabatanUserOption = b;
                            var m = $filter('filter')(vm.filteredWorkflowAssignToJabatanUserOption, { ID: SelectedAdditionUnit.JabatanID.toString() }, true);
                            if (m.length > 0) {
                                vm.SelectedJabatanAdditionUser = m[0].ID;
                                var m = $filter('filter')(vm.WorkflowAssignToCawanganUserOption, { ParentUnitID: parseInt(vm.SelectedJabatanAdditionUser) }, true);
                                if (m.length > 0) {
                                    vm.filteredWorkflowAssignToCawanganUserOption = m;
                                    m = $filter('filter')(vm.filteredWorkflowAssignToCawanganUserOption, { ID: SelectedAdditionUnit.CawanganID.toString() }, true)
                                    if (m.length > 0) {
                                        vm.SelectedCawanganAdditionUser = m[0].ID;
                                        SearchAdditionUnitUserByUnitID(vm.SelectedCawanganAdditionUser);
                                    }
                                }

                            }
                            vm.filteredWorkflowAssignToUnitUserOption = [];
                        }
                    }
                }
                else if (vm.AdditionalUnitID.HierarchyType == 35) {
                    //var model = vm.DefaultUnitID.AdditionalInfo.split(".");
                    m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, { ID: SelectedAdditionUnit.SeksyenID.toString() }, true);
                    if (m.length > 0) {
                        vm.SelectedTimbalanAdditionUser = m[0].ID;
                        b = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, {
                            ParentUnitID: parseInt(vm.SelectedTimbalanAdditionUser)
                        }, true);

                        vm.filteredWorkflowAssignToJabatanUserOption = b;
                        b = $filter('filter')(vm.filteredWorkflowAssignToJabatanUserOption, {
                            ID: SelectedAdditionUnit.JabatanID.toString()
                        }, true);
                        if (b.length > 0) {
                            vm.SelectedJabatanAdditionUser = b[0].ID;
                            SearchAdditionUnitUserByUnitID(vm.SelectedJabatanAdditionUser);
                        }
                        vm.CawanganUserAdditionEnabled = false;
                    }


                    vm.SeksyenUserAdditionEnabled = true;
                }
                else {
                    m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, {
                        ID: vm.DefaultUnitID.ID
                    }, true);
                    if (m.length > 0) {
                        vm.SelectedTimbalanAdditionUser = m[0].ID;
                        vm.JabatanUserAdditionEnabled = false;
                        vm.CawanganUserAdditionEnabled = false;
                        vm.UnitUserAdditionEnabled = false;
                        vm.SelectedJabatanAdditionUser = "";
                        vm.SelectedCawanganAdditionUser = "";
                        vm.SelectedUnitsAdditionUser = "";
                        SearchAdditionUnitUserByUnitID(vm.SelectedTimbalanAdditionUser);
                        //vm.WorkflowAssignToSeksyenUserOption
                    }
                }
        }
        else {
            vm.SelectedTimbalanAdditionUser = "";
            vm.SelectedJabatanAdditionUser = "";
            vm.SelectedCawanganAdditionUser = "";
            vm.SelectedUnitsAdditionUser = "";
        }
    }

    vm.seksyenUserAdditionChange = function (SelectedTimbalanAdditionUser) {
        vm.filteredWorkflowAssignToJabatanUserOption = [];

        if (SelectedTimbalanAdditionUser != null) {
            var m = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, { ParentUnitID: parseInt(SelectedTimbalanAdditionUser) }, true);
            vm.filteredWorkflowAssignToJabatanUserOption = [];
            if (m != undefined && m.length != 0) {
                vm.filteredWorkflowAssignToJabatanUserOption = m;
                vm.CawanganUserAdditionEnabled = false;
            }

            SearchUserByUnitID(SelectedTimbalanAdditionUser);

            vm.filteredWorkflowAssignToCawanganUserOption = [];
        }
        else {
            vm.NoUserMessage = true;
            vm.UserResultOption.length = 0;
            vm.ManagerProfileID = "";
        }
    };

    vm.jabatanUserAdditionChange = function (SelectedJabatanAdditionUser) {
        //enable upper hierarchy
        // vm.SeksyenUserEnabled = false;

        vm.filteredWorkflowAssignToCawanganUserOption = [];

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

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

                vm.filteredWorkflowAssignToCawanganUserOption = m;
            }
            SearchUserByUnitID(SelectedJabatanAdditionUser);
            vm.CawanganUserAdditionEnabled = true;

        } else {
            vm.seksyenUserAdditionChange(vm.SelectedTimbalanAdditionUser);
            vm.CawanganUserAdditionEnabled = false;
        }
    };

    vm.cawanganUserAdditionChange = function (SelectedCawanganAdditionUser, SelectedUnitDetail) {
        //enable upper hierarchy
        //vm.SeksyenUserEnabled = true;
        //vm.JabatanUserEnabled = true;

        vm.filteredWorkflowAssignToUnitUserOption = [];

        if (SelectedCawanganAdditionUser != null) {
            //disable upper hierarchy
            //vm.SeksyenUserEnabled = false;
            //vm.JabatanUserEnabled = false;
            if (SelectedUnitDetail != undefined) {
                if (SelectedUnitDetail.HierarchyType == 37) {
                    var m = $filter('filter')(vm.WorkflowAssignToUnitUserOption, { ParentUnitID: parseInt(SelectedCawanganAdditionUser) }, true);

                    if (m != undefined && m.length != 0) {
                        vm.filteredWorkflowAssignToUnitUserOption = m;
                    }
                    SearchUserByUnitID(SelectedCawanganAdditionUser);
                }
                else {
                    vm.SelectedCawanganAdditionUser = SelectedCawanganAdditionUser;
                    vm.UnitUserAdditionEnabled = false;
                }


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

                if (m != undefined && m.length != 0) {
                    vm.filteredWorkflowAssignToUnitUserOption = m;
                }
                SearchUserByUnitID(SelectedCawanganAdditionUser);
            }
        }
        else {
            vm.jabatanUserAdditionChange(vm.SelectedJabatanAdditionUser);
        }
    };

    vm.unitUserAdditionChange = function (SelectedUnitsAdditionUser) {
        if (SelectedUnitsAdditionUser != null) {
            SearchUserByUnitID(SelectedUnitsAdditionUser);
        }
        else {
            vm.cawanganUserAdditionChange(vm.SelectedCawanganAdditionUser)
        }
    };

    function SearchAdditionUnitUserByUnitID(selectedAdditionUnitID) {
        if (selectedAdditionUnitID) {
            vm.NoAdditionUserMessage = false;

            vm.AssignToUser = "";
            UserSI.searchUserByUnitID(selectedAdditionUnitID).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        vm.AdditionUserResultOption = r.data;

                        if (vm.AdditionUserResultOption.length == 0) {
                            vm.NoAdditionUserMessage = true;
                            vm.AdditionUserResultOption.length = 0;
                            vm.AdditionManagerProfileID = "";

                        }
                        else {
                            if (vm.userList.UnitID != undefined && vm.DefaultUnitID.ID != vm.userList.UnitID.toString()) {
                                vm.AdditionManagerProfileID = "";
                            }

                        }
                    }
                }
            });
        }
    }


    vm.SearchAdditionUserByName = function (query, AdditionUnitID) {
        vm.AdditionUserResultOption = [];
        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.AdditionUserResultOption = m;
                    }
                } vm.loading = false;
            });
        }

    }

    vm.removePengurus = function (selectManagerID, index, UnitID) {

        if (selectManagerID != null) {

            angular.forEach(vm.additionalUnitandRoles, function (value, key) {
                if(value.ID == UnitID.toString())
                {
                    value.ManagerID = null;
                    value.ManagerName = "-";
                    vm.RemoveAdditionUserManager = value;
                    vm.lstRemoveAdditionUserManager.push(vm.RemoveAdditionUserManager);
                }

            });
            //b = $filter('filter')(vm.additionalUnitandRoles, { ID: UnitID.toString() }, true);
            //if (b.length > 0) {
            //    b[0].ManagerID = null;
            //    b[0].ManagerName = "-";

            //    lstRemoveAdditionUserManager.push(b[0]);

            //}

        }

    }

    vm.GetAdditionalReportManagerByUnit = function (SelectedAdditionUnitID) {

        if (vm.AdditionalUnitID != null) {
            if (vm.AdditionalUnitID.HierarchyType == 37) {
                //var model = vm.DefaultUnitID.AdditionalInfo.split(".");
                m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, {
                    ID: SelectedAdditionUnitID.SeksyenID.toString()
                }, true);
                if (m.length > 0) {
                    vm.SelectedTimbalanAdditionUser = m[0].ID;
                    vm.JabatanUserAdditionEnabled = false;
                    if (vm.SelectedTimbalanAdditionUser != null) {
                        vm.SeksyenUserAdditionEnabled = false;

                        b = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, {
                            ID: SelectedAdditionUnitID.JabatanID.toString()
                        }, true);

                        vm.filteredWorkflowAssignToJabatanUserOption = b;
                        vm.SelectedJabatanAdditionUser = b[0].ID;
                        if (vm.SelectedJabatanAdditionUser != null) {
                            var m = $filter('filter')(vm.WorkflowAssignToCawanganUserOption, { ParentUnitID: parseInt(vm.SelectedJabatanAdditionUser) }, true);
                            if (m != undefined && m.length != 0) {

                                vm.filteredWorkflowAssignToCawanganUserOption = m;
                                var m = $filter('filter')(vm.filteredWorkflowAssignToCawanganUserOption, { ID: SelectedAdditionUnitID.CawanganID.toString() }, true);
                                if (m.length > 0) {
                                    vm.SelectedCawanganAdditionUser = m[0].ID;
                                    var m = $filter('filter')(vm.WorkflowAssignToUnitUserOption, { ParentUnitID: parseInt(vm.SelectedCawanganAdditionUser) }, true);
                                    if (m.length > 0) {
                                        vm.filteredWorkflowAssignToUnitUserOption = m;
                                        var m = $filter('filter')(vm.filteredWorkflowAssignToUnitUserOption, { ID: SelectedAdditionUnitID.ID.toString() }, true);
                                        vm.SelectedUnitsAdditionUser = m[0].ID;
                                        SearchAdditionUnitUserByUnitID(vm.SelectedUnitsAdditionUser);

                                    }
                                }

                            }

                            vm.CawanganUserAdditionEnabled = true;
                            vm.UnitUserAdditionEnabled = true;
                        }
                    }
                }

            }
            else
                if (vm.AdditionalUnitID.HierarchyType == 36) {
                    //var model = vm.DefaultUnitID.AdditionalInfo.split(".");
                    m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, { ID: SelectedAdditionUnitID.SeksyenID.toString() }, true);
                    if (m.length > 0) {
                        vm.SelectedTimbalanAdditionUser = m[0].ID;
                        //vm.JabatanUserEnabled = false;
                        if (vm.SelectedTimbalanAdditionUser != null) {
                            vm.SeksyenUserAdditionEnabled = false;
                            vm.JabatanUserAdditionEnabled = true;
                            vm.SelectedCawanganAdditionUser = false;
                            vm.CawanganUserAdditionEnabled = true;

                            b = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, { ParentUnitID: parseInt(vm.SelectedTimbalanAdditionUser) }, true);

                            vm.filteredWorkflowAssignToJabatanUserOption = b;
                            var m = $filter('filter')(vm.filteredWorkflowAssignToJabatanUserOption, { ID: SelectedAdditionUnitID.JabatanID.toString() }, true);
                            if (m.length > 0) {
                                vm.SelectedJabatanAdditionUser = m[0].ID;
                                var m = $filter('filter')(vm.WorkflowAssignToCawanganUserOption, { ParentUnitID: parseInt(vm.SelectedJabatanAdditionUser) }, true);
                                if (m.length > 0) {
                                    vm.filteredWorkflowAssignToCawanganUserOption = m;
                                    m = $filter('filter')(vm.filteredWorkflowAssignToCawanganUserOption, { ID: SelectedAdditionUnitID.CawanganID.toString() }, true)
                                    if (m.length > 0) {
                                        vm.SelectedCawanganAdditionUser = m[0].ID;
                                        SearchAdditionUnitUserByUnitID(vm.SelectedCawanganAdditionUser);
                                    }
                                }

                            }
                            vm.filteredWorkflowAssignToUnitUserOption = [];
                        }
                    }
                }
                else if (vm.AdditionalUnitID.HierarchyType == 35) {
                    //var model = vm.DefaultUnitID.AdditionalInfo.split(".");
                    m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, { ID: SelectedAdditionUnitID.SeksyenID.toString() }, true);
                    if (m.length > 0) {
                        vm.SelectedTimbalanAdditionUser = m[0].ID;
                        b = $filter('filter')(vm.WorkflowAssignToJabatanUserOption, {
                            ParentUnitID: parseInt(vm.SelectedTimbalanAdditionUser)
                        }, true);

                        vm.filteredWorkflowAssignToJabatanUserOption = b;
                        b = $filter('filter')(vm.filteredWorkflowAssignToJabatanUserOption, {
                            ID: SelectedAdditionUnitID.JabatanID.toString()
                        }, true);
                        if (b.length > 0) {
                            vm.SelectedJabatanAdditionUser = b[0].ID;
                            SearchAdditionUnitUserByUnitID(vm.SelectedJabatanAdditionUser);
                        }
                        vm.CawanganUserAdditionEnabled = false;
                    }


                    vm.SeksyenUserAdditionEnabled = true;
                }
                else {
                    m = $filter('filter')(vm.WorkflowAssignToSeksyenUserOption, {
                        ID: vm.DefaultUnitID.ID
                    }, true);
                    if (m.length > 0) {
                        vm.SelectedTimbalanAdditionUser = m[0].ID;
                        vm.JabatanUserAdditionEnabled = false;
                        vm.CawanganUserAdditionEnabled = false;
                        vm.UnitUserAdditionEnabled = false;
                        vm.SelectedJabatanAdditionUser = "";
                        vm.SelectedCawanganAdditionUser = "";
                        vm.SelectedUnitsAdditionUser = "";
                        SearchAdditionUnitUserByUnitID(vm.SelectedTimbalanAdditionUser);
                        //vm.WorkflowAssignToSeksyenUserOption
                    }
                }
        }
        else {
            vm.SelectedTimbalanAdditionUser = "";
            vm.SelectedJabatanAdditionUser = "";
            vm.SelectedCawanganAdditionUser = "";
            vm.SelectedUnitsAdditionUser = "";
        }


    }
    // For Pengurus Additional Unit - End


}