crmApp.controller("UserProfileController", UserProfileController);

function UserProfileController($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;
    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;
    vm.showNoManagerValidationMsg = false;
    vm.showUserdetail = false;
    vm.showPengurusAdditionUnitDetail = false;
    vm.changesHistory = [];
    vm.userList = {};
    vm.DefaultrolesID = [];
    vm.AdditionalrolesID = [];
    vm.showRoleNoRecord = false;
    vm.showAdditionalRoleNoRecord = false;
    vm.DefaultrolesNameOri = [];
    vm.DefaultrolesIDRemove = [];
    vm.DefaultrolesName = [];
    vm.AdditionalRolesName = [];
    vm.additionalUnitandRoles = [];
    vm.RemoveUnitAndRoles = [];
    vm.AddNewDefaultRoleID = [];

    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.Validation = {};
    vm.duplicateLoginData = [];
    vm.lstAdditionUserManager = [];
    vm.lstRemoveAdditionUserManager = [];

    vm.UserResultOption = [];
    vm.UserManagerResultOption = [];
    vm.ChangeAdditionUserManager = [];
    vm.RemoveAdditionUserManager = [];

    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 constChangeDefaultUnit = 'Notis: Sila pastikan pengguna ini mempunyai Pengurus Unit sebelum menukar Jabatan/Cawangan/Unit atau Status ID.';

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

    today = mm + '/' + dd + '/' + yyyy;

    vm.UserProfileID = $window.userProfileID;

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

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

    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.getUserProfileDetailByID(vm.UserProfileID).then(function (r) {
                    if (r.status == 200) {
                        vm.userList = r.data;
                        vm.UserResultOption = r.data.UserProfileManager;
                        vm.AdditionalUnitIDMultiple = vm.userList.AdditionalUnitIDMultiple;
                        vm.editTitle = "Kemaskini Profil Pengguna "

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

                            if (vm.userList.UserActiveCondition.ExpiryDate != null) {
                                vm.TarikhLuput = new Date(vm.userList.UserActiveCondition.ExpiryDate);
                            }
                            vm.userList.ActiveCondition = vm.userList.UserActiveCondition.ActiveCondition

                            if (vm.userList.UserActiveCondition.ActiveCondition == Dormant) {
                                vm.showDormanDate = true;
                                vm.showExpiryDate = false;
                            }
                            else if (vm.userList.UserActiveCondition.ActiveCondition == Expiry) {
                                vm.showExpiryDate = true;
                                vm.showDormanDate = false;
                            }
                            else {
                                vm.showExpiryDate = false;
                                vm.showDormanDate = false;
                            }
                        }

                        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 {
                            ManagerID = "";
                        }

                        if (ManagerID != "") {
                            //m = $filter('filter')(vm.UserResultOption, { ID: ManagerID }, true);
                            //if (m.length > 0) {
                            vm.UserManagerResultOption = r.data.UserProfileManager;
                            vm.ManagerProfileID = vm.UserResultOption[0];
                            //}
                            //else
                            //{
                            //    vm.ManagerProfileID = "";
                            //}
                        }
                        else {
                            vm.ManagerProfileID = "";
                        }

                        //if (vm.userList.UserRoles.length > 0)
                        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].RoleName);
                                    vm.DefaultrolesName.push(m[0]);
                                   // DefaultrolesNameOri = vm.DefaultrolesName;
                                   vm.DefaultrolesID.push(m[0].FunctionalRoleID);
                                }
                                else {
                                    vm.DefaultrolesName = "";

                                }
                            })
                        }
                        else {
                            vm.showRoleNoRecord = true;
                        }

                        //For addition Unit
                        //if (vm.userList.AdditionalUnitID != null && vm.userList.AdditionalUnitID > 0) {
                        //    AdditionalUnitID = vm.userList.AdditionalUnitID.toString();
                        //}
                        //else {
                        //    AdditionalUnitID = "";
                        //}

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

                        //            }

                        //        }

                        //    }
                        //}
                        //else {
                        //    vm.userList.UnitID = "";
                        //}
                        //For addition Unit

                        //For Addition Role ID
                        //if (vm.userList.UserAdditionalFunctionRoles.length > 0) {


                        //    vm.AdditionalRolesName = [];
                        //    angular.forEach(vm.userList.UserAdditionalFunctionRoles, function (value, key) {

                        //        m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: value.FunctionalRoleID }, true);
                        //        if (m.length > 0) {

                        //            vm.AdditionalRolesName.push(m[0]);

                        //            vm.AdditionalrolesID.push(m[0].FunctionalRoleID);
                        //        }
                        //        else {
                        //            vm.AdditionalRolesName = "";

                        //        }
                        //    })
                        //}
                        //else
                        //{
                        //    vm.showAdditionalRoleNoRecord = true;
                        //}
                        //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 = "Tambah Profil Pengguna "
                //vm.userList.IsActive = true;
                vm.userList.ActiveCondition = Active;
                vm.showdetailRoles = false;
                vm.showdetailAdditionalRoles = false;
                vm.AdditionalUnitID = "";
                vm.SelectedTimbalanUser = "";
                vm.SelectedJabatanUser = "";
                vm.SelectedCawanganUser = "";
                vm.SelectedUnitsUser = "";

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

            }
        });
  
    }

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

        vm.showdetailDocUnit = !vm.showdetailDocUnit;
    }

    vm.ResetHierarchyDocUnit = function () {
        vm.SeksyenEnabledDocUnit = true;
        vm.JabatanEnabledDocUnit = true;

        vm.SelectedTimbalanDocUnit = "";
        vm.SelectedJabatanDocUnit = "";
        vm.SelectedCawanganDocUnit = "";
        vm.SelectedUnitsDocUnit = "";

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

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

        // vm.AssignTo = "";

        vm.actWorkflowAssignToJabatanOptionDocUnit = [];
        vm.actWorkflowAssignToCawanganOptionDocUnit = [];
        vm.actWorkflowAssignToUnitOptionDocUnit = [];
        //vm.UserResultOption = [];

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

    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.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" + constChangeDefaultUnit, "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;

        if (query.length > 2) {
            UserSI.searchUnitByName(query).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 () {
        vm.SeksyenEnabledAdditionalUnit = true;
        vm.JabatanEnabledAdditionalUnit = true;

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

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

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

    vm.seksyenChangeAdditionalUnit = function (selectedTimbalanAdditionalUnit) {

        vm.actWorkflowAssignToJabatanOptionAdditionalUnit = [];

        if (selectedTimbalanAdditionalUnit != null) {
            var m = $filter('filter')(vm.WorkflowAssignToJabatanOptionDocUnit, { ParentUnitID: parseInt(selectedTimbalanAdditionalUnit) }, true);
            if (m != undefined && m.length != 0) {
                vm.actWorkflowAssignToJabatanOptionAdditionalUnit = 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;

        if (query.length > 2) {
            UserSI.searchUnitByName(query).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.AssignToUser = "";
        }
    };

    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;

                    SearchUserByUnitID(SelectedCawanganUser);
                }

              
            }
            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.UserResultOption = [];
            vm.AssignToUser = "";
            UserSI.searchUserByUnitID(selectedUnitID).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        vm.UserResultOption = r.data;

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

                            //if (vm.userList.UnitID != undefined && vm.userList.UserProfileID > 0) {
                            //    swal("Gagal", "Tiada Pengurus Unit dalam unit ini.", "error");
                            //    GetDefaultUnitByUnitID(vm.userList.UnitID.toString());
                            //}

                            //swal("Gagal", "Tiada Reporting Manager dalam unit ini", "error");
                            //if (vm.userList.UnitID != undefined) {
                            //    GetDefaultUnitByUnitID(vm.userList.UnitID.toString());
                            //}
                            //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" + constChangeDefaultUnit, "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.DefaultrolesID = vm.Defaultroles.selected.join(" || ");
            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 = "";
                }
              
                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 = ""
                        vm.AdditionManagerProfileID = "";
                    }
                }
                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");
                }

            }
        console.log(vm.additionalUnitandRoles);
    }

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

       
    }

    vm.save = function (userProfileForm)
    {
        var isDirty = userProfileForm.$dirty;
        var result = null;
        var IsEmailValid = null;
        var tarikhluput = 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)
        {
                if (vm.AddNewDefaultRoleID.length > 0)
                {
                    vm.DefaultrolesID = 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.DefaultrolesID = vm.DefaultrolesID.join(" || ");
                        }
                    }
  
                }

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

                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");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                    vm.showValidationMsg = true;
                    vm.showInvalidEmailMsg = false;
                    //return false;
                }
                else
                {
                    var IsEmailValid = validateEmail(vm.userList.Email);
                }
                


                m = $filter('filter')(vm.duplicateLoginData, { LoginID: vm.userList.LoginID }, true);
                if (m.length > 0 && m[0].UserProfileID != vm.userList.UserProfileID)
                {
                        swal("Gagal", "Login ID ini telah dipakai.", "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(); 
                    deferred.reject('');
                    result = deferred.promise;
                    vm.showValidationMsg = false;
                    vm.showInvalidEmailMsg = true;

                }
                else if ((vm.DefaultUnitID == undefined || vm.DefaultUnitID == "") && vm.DefaultrolesID.length == 0)
                {
                    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.DefaultrolesID.length > 0)
                {
                    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.DefaultrolesID.length == 0)
                {
                    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(); 
                    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(); 
                    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(); 
                    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(); 
                    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(); 
                    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(); 
                    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 (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" + constChangeDefaultUnit, "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.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" + constChangeDefaultUnit, "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.DefaultrolesIDRemove = vm.DefaultrolesIDRemove.join(" , ");
                        }

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

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

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

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

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

                                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;
                                    }

                                }

                                var userModel = {
                                    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.DefaultrolesID == null ? 0 : vm.DefaultrolesID,
                                    RemoveDefaultRolesID: vm.DefaultrolesIDRemove == null ? 0 : vm.DefaultrolesIDRemove,
                                    RemoveUnitAndRoles: vm.RemoveUnitAndRoles == null ? 0 : vm.RemoveUnitAndRoles,
                                    RemoveAdditionalRolesID: vm.AdditionalRolesIDRemove == null ? 0 : vm.AdditionalRolesIDRemove,
                                    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,
                                    RemoveAdditionalUnitID: vm.AdditionalForUnitID,
                                    RemoveUnitAdditionManager: vm.lstRemoveAdditionUserManager,
                                    //UserAdditionalUnitAndRoles: vm.additionalUnitandRoles,
                                    UserAdditionalUnitAndRoles: vm.SelectedAdditionalUnitAndRoles,
                                    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
                                }

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

                                UserSI.updateUserProfileDetail(model).then(function (r) {
                                    if (r.status === 200) {
                                        if (r.data) {
                 
                                            swal({
                                                title: "Berjaya Kemaskini!",
                                                type: "success",
                                                timer: 2500,
                                                showConfirmButton: false
                                            }, function () {
                                                //location.reload();
                                  
                                                vm.redirectTo('/user/Profile/Detail/' + r.data.UserProfile.UserProfileID);
                                            });
                                        }
                                        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("Gagal", "Tiada perubahan maklumat dilakukan!", "error");
                                var deferred = $q.defer(); 
                                deferred.reject('');
                                result = deferred.promise;
                            }
                        }
                        else {
                            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
                            var deferred = $q.defer(); 
                            deferred.reject('');
                            result = deferred.promise;
                            vm.showValidationMsg = true;

                            if (vm.DefaultrolesName.length > 0) {
                                vm.showDefaultRoleValidationMsg = false;
                            }
                            else {
                                vm.showDefaultRoleValidationMsg = 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;
        }

    }

    $scope.CheckDuplicateLogin = function (userloginID)
    {
        if (userloginID != undefined && userloginID != "" && userloginID != null)
        {
            UserSI.checkDuplicateLogin(userloginID).then(function (r) {
                if (r.status === 200) {
                    vm.duplicateLoginData = r.data;
                    if (r.data != null && r.data.length > 0) {
                        if (r.data[0].UserProfileID != vm.userList.UserProfileID)
                        {
                            swal("Gagal", "Login ID ini telah dipakai.", "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 {
                    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;
            }
        }
    }

    // datepicker
    vm.openDateFrom = function () {
        vm.dateFromOpened = true;
    };

    vm.openDateTo = function () {
       vm.dateToOpened = true;
    };

    vm.clearDateFrom = function () {
        vm.DateFrom = null;
    };
    vm.clearDateTo = function () {
        vm.DateTo = null;
    };

    vm.clearTarikhDaftar = function () {
        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.UserProfileID > 0) {
                swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangeDefaultUnit, "error");
                vm.showNoManagerValidationMsg = true;
            }
            else {
                SearchUserByUnitID(objUnit.ID);
            }
        }
        else if (id == Expiry) {
            vm.showExpiryDate = true;
            vm.showDormanDate = false;

            if ((vm.userList.ManagerUserProfileID == null || vm.userList.ManagerUserProfileID == 0) && vm.userList.UserProfileID > 0) {
                swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangeDefaultUnit, "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.UserProfileID > 0) {
                swal("Gagal", "Anda tidak dibenarkan untuk menukar Jabatan/Cawangan/Unit atau Status ID.\n\n" + constChangeDefaultUnit, "error");
                vm.showNoManagerValidationMsg = true;
            }
            else
            {
                SearchUserByUnitID(objUnit.ID);
            }
        }
        else {
            vm.showExpiryDate = false;
            vm.showDormanDate = 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");
        }
    }

    // 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.filteredWorkflowAssignToCawanganUserOption = [];

        if (SelectedJabatanAdditionUser != null) {
            //disable upper hierarchy
            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.filteredWorkflowAssignToUnitUserOption = [];

        if (SelectedCawanganAdditionUser != null) {
            //disable upper hierarchy
            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);
                }

            });

        }

    }

    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

 
}