crmApp.controller("DashboardController", DashboardController);
crmApp.controller("DashboardDetailController", DashboardDetailController);

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

    vm.init = function () {
        initBasicTable();
    };

    vm.dtInstanceDashboard = {};
    vm.addNewDashboard = function () {
        window.open('/Admin/Dashboard/Detail/', '_blank');
    };

    function initBasicTable() {

        var ajaxCallback = function (data, callback, settings) {

            data.DashboardName = !vm.DashboardName ? '' : vm.DashboardName;
            data.CreatedBy = !vm.CreatedBy ? '' : vm.CreatedBy;
            AdminSI.getDashboardListing(data).then(function (r) {
                if (r.status == 200 && (r.data)) {
                    callback(r.data);
                }
            });
        }

        vm.dtColumnsDashboard = [
            DTColumnBuilder.newColumn('DashboardName').withTitle('Nama').renderWith(function (data, type, row) {
                return '<a href="/Admin/Dashboard/detail/' + row.DashboardID + '" target="_blank">' + row.DashboardName + '</a>'
            }).withOption('width', '13%'),
            DTColumnBuilder.newColumn('CreatedBy').withTitle('Dihasilkan Oleh'),
            DTColumnBuilder.newColumn('CreatedDateTime').withTitle('Tarikh Dihasilkan').renderWith(function (data, type) {
                return $filter('date')(data ? data : '-', 'dd MMM yyyy hh:mm a');
            }),
            DTColumnBuilder.newColumn('LastUpdatedBy').withTitle('Dikemaskini Oleh'),
            DTColumnBuilder.newColumn('LastUpdatedDateTime').withTitle('Tarikh Dikemaskini').renderWith(function (data, type) {
                return $filter('date')(data ? data : '-', 'dd MMM yyyy hh:mm a');
            }),
            DTColumnBuilder.newColumn('IsActive').withTitle('Aktif?').renderWith(function (data, type, row) {
                if (row.IsActive)
                    return '<i class="fa fa-check"</i>'
                else
                    return '<i class="fa fa-close"></i>'
            }).withOption('width', '13%')
            ,
            DTColumnBuilder.newColumn('DashboardID').withTitle('').renderWith(function (data, type, row) {
                var link;
                link = '<i class="fa fa-trash pull-right" title="Delete Dashboard" ng-click="search.deleteDashboard('+ row.DashboardID +')"></i>';
                return link;
            })
        ];

        vm.dtOptionsDashboard = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallback)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('searching', true)
            .withOption('serverSide', true)
            .withPaginationType('full_numbers')
            .withOption('autoWidth', false)
            .withOption('createdRow', function (row, data, dataIndex) {
                $compile(angular.element(row).contents())($scope);
            })
            .withDisplayLength(10);
    }

    vm.searchDashboard = function () {
        vm.dtInstanceDashboard.reloadData()
    };

    vm.clearSearch = function () {
        vm.DashboardName = '';
        vm.CreatedBy = '';
    };

    vm.deleteDashboard = function (dashboardID, dashboardName) {
        swal({
            title: "Adakah anda pasti untuk padamkan dashboard ini?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: true,
            closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                model = {
                    DashboardID: dashboardID,
                    DashboardName: dashboardName
                };
                AdminSI.deleteDashboard(model).then(function (r) {
                    if (r.status == 200 && (r.data)) {
                        swal({
                            title: "Berjaya!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false,
                            confirmButtonText: "Ya",
                            cancelButtonText: "Tidak",
                        });
                        vm.searchDashboard();
                    }
                });
            }
        });
    };

}


function DashboardDetailController($scope, $mdDialog, $window, $q, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $filter, $compile, AdminSI, UserSI, GeneralSI, AntiForgeryService) {
    var vm = this;
    var TabID = "01";
    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                          { Text: 'Tidak', Value: false }];

    vm.ViewTypeOptions = [{ Text: 'Activity', Value: 3 },
                          { Text: 'Case', Value: 2 },
                          { Text: 'HCL Email Blast', Value: 6 },
                          { Text: 'Outbound', Value: 5 },
                          { Text: 'Tax Payer', Value: 1 }];

    vm.DashboardID = $window.dashboardId == '' ? '0' : $window.dashboardId;
    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;
    vm.PermissionType = '1'; //set default
    vm.IsActive = true; //set default
    vm.IsPublished = true; //set default
    vm.showdetail = false;
    vm.SelectedTimbalan = "";
    vm.SelectedJabatan = "";
    vm.SelectedCawangan = "";
    vm.SelectedUnits = "";
    vm.SeksyenEnabled = true;
    vm.JabatanEnabled = true;
    vm.SeksyenUserEnabled = true;
    vm.JabatanUserEnabled = true;
    vm.SpecificUnitList = [];
    vm.JenisUnitList = [];
    vm.DuplicateNameMsg = "Nama Dashboard ini telah digunakan. Sila guna nama lain.";
    vm.ValidateInputMsg = ""


    vm.init = function () {

        var querystring = location.search;
        if (querystring) {
            TabID = $.urlParam('t') || "01";
        }


        tabAction(TabID);

        vm.ResetHierarchy();
        GetUserGroupHierarcyOptions();
        GetDashboardSavedView();
        GetRefChartAction();

        var dashboardID = vm.DashboardID;
        if (dashboardID > 0) {
            vm.Title = 'Kemaskini Dashboard'
            AdminSI.getDashboardDetails(dashboardID).then(function (r) {
                if (r.status === 200) {

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

                    var m = $filter('filter')(vm.DashboardUnit, { Type: 'Unit' }, true);
                    if (m && (m.length > 0)) {
                        vm.SpecificUnitList = m;
                    }

                    var m = $filter('filter')(vm.DashboardUnit, { Type: 'Type' }, true);
                    if (m && (m.length > 0)) {
                        vm.JenisUnitList = m;
                    }

                    vm.DashboardZonesEdit = $.extend(true, {}, vm.DashboardZones);



                }
                vm.CheckRecord();
            });

        }
        else {
            vm.Title = 'Dashboard Baru'
        }
        vm.CheckRecord();
    };

    function GetDashboardSavedView() {
        AdminSI.getDashboardSavedView().then(function (r) {
            if (r.status === 200) {
                if (r.data) {
                    vm.AllDashboardSavedViewOptions = r.data;
                }
            }
        });
    }

    function GetRefChartAction() {
        AdminSI.getChartAction().then(function (r) {
            if (r.status === 200) {
                if (r.data) {
                    vm.ChartActionOptions = r.data;
                }
            }
        });
    }

    function GetZonList() {
        vm.DashboardZones = [];
        AdminSI.getDashboardZonList(vm.DashboardID).then(function (r) {
            vm.DashboardZones = r.data;
            vm.DashboardZonesEdit = $.extend(true, {}, vm.DashboardZones);

        });
    }

    $.urlParam = function (name) {
        var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
        if (results == null) {
            return null;
        }
        else {
            return decodeURI(results[1]) || 0;
        }
    }

    vm.tabAction = tabAction;
    function tabAction(cls) {
        vm.tabProfile01Active = false;
        vm.tabProfile02Active = false;

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

    }

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

    }

    vm.SaveDashboard = function (dashboardForm) {

        var isDirty = dashboardForm.$dirty;


        if (!vm.DashboardName) {
            vm.showNameValidationMsg = true;
        }
        else if (vm.showDuplicateNameMsg) {
            swal("Gagal", vm.DuplicateNameMsg, "error");
            //result = returnResultPromise();
        }
        else {
            vm.DashboardUnit = [];
            vm.DashboardUnit = vm.JenisUnitList.concat(vm.SpecificUnitList);
            vm.DashboardZones = [];

            var model = {
                DashboardID: vm.DashboardID,
                DashboardName: vm.DashboardName,
                IsActive: vm.IsActive,
                DashboardUnit: vm.DashboardUnit,
                DasboardZones: vm.DashboardZones
            };

            UpdateDashboard(model, vm.tabProfile02Active);
        }
    }

    function UpdateDashboard(model, isFromZon) {
        var data = AdminSI.updateDashboard(model);

        data.then(function (r) {

            vm.DashboardID = r.data.DashboardID;

            swal({
                title: 'Berjaya Kemaskini!',
                type: "success",
                timer: 2500,
                showConfirmButton: true
            }, function () {

                if (isFromZon)
                    vm.redirectTo('/admin/dashboard/detail/' + r.data.DashboardID + '?t=02');
                else
                    vm.redirectTo('/admin/dashboard/detail/' + r.data.DashboardID);
            });
        });

    }


    vm.redirectTo = function (url) {

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


    vm.zonOnClick = function ($event, zonid) {
        vm.ZonDetail = {
        };
        vm.SavedViewOptions = [];
        vm.ZonDetail.DashboardZonID = 0;
        var m = $filter('filter')(vm.DashboardZones, { DashboardZonID: parseInt(zonid) }, true);
        console.log('Test 1:', m);
        if (m && (m.length > 0)) {
            console.log('Test:', m[0]);
            vm.ZonDetail = angular.copy(m[0]);//$.extend(true, {}, m[0]);
            $scope.localXFieldMappingID = angular.copy(vm.ZonDetail.AxisXFieldMappingID);//vm.ZonDetail.AxisXFieldMappingID;
            $scope.localYFieldMappingID = angular.copy(m[0].AxisYFieldMappingID);

            console.log('2', vm.ZonDetail);
            var s = $filter('filter')(vm.AllDashboardSavedViewOptions, { ViewTypeID: vm.ZonDetail.ViewTypeID }, true);
            if (s && (s.length > 0)) {
                vm.SavedViewOptions = s
            }

            vm.savedViewChange().then(function (result) {

                vm.openDialog($event, '#ZonDialog');
            });

            console.log(vm.ZonDetail);
        }
    };
    vm.openDialog = function (e, id) {
        $mdDialog.show({
            contentElement: id,
            parent: angular.element(document.body),
            targetEvent: e,
            clickOutsideToClose: false
        }, function() {

            vm.redirectTo('/admin/dashboard/detail/' + vm.DashboardID + '?t=02');
        });
    }

    vm.SaveZon = function (dashboardForm) {
        if (!vm.DashboardName) {
            vm.showNameValidationMsg = true;
        }
        else if (vm.showDuplicateNameMsg) {
            swal("Gagal", vm.DuplicateNameMsg, "error");
        }
        else if (vm.validateZon()) {
            vm.DashboardZonesEdit = [];
            vm.DashboardZonesEdit[0] = vm.ZonDetail;

            //vm.DashboardZonesEdit[0].AxisYFieldMappingID = vm.AxisYFieldMappingID;

            vm.DashboardUnit = vm.JenisUnitList.concat(vm.SpecificUnitList);
            $mdDialog.hide();
            var model = {
                DashboardID: vm.DashboardID,
                DashboardName: vm.DashboardName,
                IsActive: vm.IsActive,
                DashboardUnit: vm.DashboardUnit,
                DashboardZones: vm.DashboardZonesEdit
            };

            UpdateDashboard(model, true);
        }

    }

    vm.addNewZon = function ($event) {
        if (!vm.DashboardName) {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            return false;
        }
        vm.openDialog($event, '#ZonDialog');
        vm.ZonDetail = {
        }; //Object.assign({}, []);
        vm.ZonDetail.DashboardZonID = 0;
        vm.ZonDetail.DashboardType = 'T'; //set default
        vm.ZonDetail.IsActive = true; //set default
        vm.ZonDetail.IsPublished = true; //set default
        vm.SavedViewOptions = []; //set default
        vm.DisplayColumnsOptions = [];
    }

    vm.CancelZon = function () {
        GetZonList();
        $mdDialog.hide();
    }

    vm.validateZon = function () {
        //$scope.makAmForm.$valid
        var isInValid = false;
        if (!vm.ZonDetail.ZonName) isInValid = true;
        if (!vm.ZonDetail.Sequence) isInValid = true;
        if (!vm.ZonDetail.ViewTypeID) isInValid = true;
        if (!vm.ZonDetail.SavedViewID) isInValid = true;
        if (vm.ZonDetail.DashboardType == 'C') {
            if (!vm.ZonDetail.AxisYChartAction || vm.ZonDetail.AxisYChartAction == 0) isInValid = true;
            if (!vm.ZonDetail.AxisXFieldMappingID || vm.ZonDetail.AxisXFieldMappingID == 0) isInValid = true;
            if (!vm.ZonDetail.AxisXTitle || vm.ZonDetail.AxisXTitle == '') isInValid = true;
            if (!vm.ZonDetail.AxisYFieldMappingID || vm.ZonDetail.AxisYFieldMappingID == 0) isInValid = true;
            if (!vm.ZonDetail.AxisYFieldMappingID || vm.ZonDetail.AxisYFieldMappingID == 0) isInValid = true;
            if (!vm.ZonDetail.AxisYTitle || vm.ZonDetail.AxisYTitle == '') isInValid = true;
        }
        if (isInValid) {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            return false;
        }
        return true;
    }

    vm.viewTypeChange = function () {
        vm.SavedViewOptions = [];
        var s = $filter('filter')(vm.AllDashboardSavedViewOptions, { ViewTypeID: vm.ZonDetail.ViewTypeID }, true);
        if (s && (s.length > 0)) {
            vm.SavedViewOptions = s
        }
    }

    vm.savedViewChange = function () {
        var deferred = $q.defer();
        vm.DisplayColumnsOptions = [];

        if (vm.ZonDetail.SavedViewID == null || vm.ZonDetail.SavedViewID == undefined) vm.ZonDetail.SavedViewID = 0;
        GeneralSI.getDashboardDisplaySetting(vm.ZonDetail.ViewTypeID, vm.ZonDetail.SavedViewID, 0).then(function (r) {
            if (r.status == 200) {
                vm.DisplayColumnsOptions = r.data;
                angular.forEach(vm.DisplayColumnsOptions, function (item, key) {
                    item.DisableSelection = false;
                });
                console.log('vm.DisplayColumnsOptions', vm.DisplayColumnsOptions);
                vm.ZonDetail.AxisXFieldMappingID = $scope.localXFieldMappingID;
                vm.ZonDetail.AxisYFieldMappingID = $scope.localYFieldMappingID;
                deferred.resolve(r.data);
            }
        });

        return deferred.promise;
    }

    vm.chartActionChange = function (selected) {
        console.log('selected', selected);
        var filtered = $filter('filter')(vm.DisplayColumnsOptions, { FieldType: 13, FieldType: 38 });
        if (selected == 1 || selected == '1') {
            angular.forEach(vm.DisplayColumnsOptions, function (item, key) {
                if (item.FieldType != 13 && item.FieldType != 38)
                    item.DisableSelection = true;
                else
                    item.DisableSelection = false;
            });
            //if (filtered && filtered != null && filtered.length > 0) {
            //    angular.forEach(filtered, function (item, key) {
            //        item.DisableSelection = false;
            //    });
            //}
        }
        else {
                angular.forEach(vm.DisplayColumnsOptions, function (item, key) {
                    item.DisableSelection = false;
                });
            }
        
        console.log('Char Action', vm.DisplayColumnsOptions);
    }

    function validateAddJenisUnit() {

        if (!vm.AssignJenisUnit || vm.AssignJenisUnit == null) {
            vm.showJenisUnitRequiredMsg = true;
            return false;
        }
        else
            return true;
    }

    function validateAddSpecificUnit() {

        if (!vm.AssignUnit || vm.AssignUnit == null) {
            vm.showSpecificUnitRequiredMsg = true;
            return false;
        }
        else
            return true;
    }


    vm.SearchUnitTypeByName = function (query) {
        vm.UnitTypeResultOption = [];
        vm.roleloading = true;

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

    vm.SearchDuplicateDashboardName = function () {


        vm.showValidationMsg = false;
        var model = {
            DashboardName: vm.DashboardName.trim(),
            DashboardID: vm.DashboardID
        }
        AdminSI.searchDuplicateDashboardName(model).then(function (r) {
            if (r.status === 200) {
                if (r.data == true) {
                    vm.showDuplicateNameMsg = true;
                }
                else {
                    vm.showDuplicateNameMsg = false;
                }
            }
        });


    };

    vm.addJenisUnit = function () {

        if (validateAddJenisUnit()) {

            var unit = $filter('filter')(vm.JenisUnitList, { UnitID: parseInt(vm.AssignJenisUnit.UnitTypeID) }, true);
            if (unit.length > 0) {
                swal("Gagal", "Jenis Unit ini telah ditambah", "error");
            }
            else {

                var unitType = [];
                unitType = {
                    IsNew: true,
                    UnitID: vm.AssignJenisUnit.UnitTypeID,
                    DisplayName: vm.AssignJenisUnit.TypeName,
                    Type: 'Type'
                }

                vm.JenisUnitList.unshift(unitType);
                vm.CheckRecord();
            }
            vm.reset();
        }

    }

    vm.addSpecificUnit = function () {

        if (validateAddSpecificUnit()) {

            var unit = $filter('filter')(vm.SpecificUnitList, { UnitID: parseInt(vm.AssignUnit.ID) }, true);
            if (unit.length > 0) {
                swal("Gagal", "Unit ini telah ditambah", "error");
            }
            else {
                var unit = [];
                unit = {
                    IsNew: true,
                    UnitID: vm.AssignUnit.ID,
                    DisplayName: vm.AssignUnit.DisplayName,
                    Type: 'Unit',
                    AdditionalInfo: vm.AssignUnit.AdditionalInfo
                }

                vm.SpecificUnitList.unshift(unit);
                vm.CheckRecord();
            }

            vm.reset();
        }

    }


    vm.removeJenisUnitRow = function (list, index) {
        if (list != null) {
            vm.JenisUnitList.splice(index, 1);
            vm.CheckRecord();
        }
    }

    vm.removeUnitRow = function (list, index) {
        if (list != null) {
            vm.SpecificUnitList.splice(index, 1);
            vm.CheckRecord();
        }
    }


    vm.permissionTypeChange = function () {
        vm.reset();
        vm.showdetail = false;
    }


    vm.CheckRecord = function () {
        vm.showJenisUnitNoRecord = vm.JenisUnitList == null || vm.JenisUnitList.length == 0;
        vm.showUnitNoRecord = vm.SpecificUnitList == null || vm.SpecificUnitList.length == 0;
        vm.showZonNoRecord = vm.DashboardZones == null || vm.DashboardZones.length == 0;
    }




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

                }
            }
        });
    }



    vm.reset = function () {
        vm.AssignUnit = [];
        vm.AssignJenisUnit = [];
        vm.ResetHierarchy();
        //vm.showdetail = false;

    }

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

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

        vm.filteredWorkflowAssignToCawanganOption = [];

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

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

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

        }
    };

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

        vm.filteredWorkflowAssignToUnitOption = [];

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

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

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

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

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

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

        if (query.length > 2) {
            UserSI.searchUnitByName(query).then(function (r) {
                if (r.data != null) {
                    var m = r.data;
                    if (m.length != 0) {
                        vm.UnitResultOption = m;
                    }
                } vm.loading = false;
            });
        }
    }
    vm.ShowFilterOption = function () {
        if (!vm.showdetail) {
            vm.showdetail = true;
        }
        else {
            //vm.ResetHierarchy();
            vm.showdetail = false;
        }
    }


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

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

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

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

        vm.UnitTypeResultOption = [];
    }

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

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

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

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

            vm.UnitResultOption = m;
            vm.AssignUnit = m[0];
            vm.addSpecificUnit();
        }

    }


}