crmApp.controller("OutboundSegmentiseController", OutboundSegmentiseController);

function OutboundSegmentiseController($scope, $window, $compile, $q, $http, $location, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $filter, OutboundSI, GeneralSI, AdminSI, GeneralService, AntiForgeryService, AdvanceRulesService, $mdDialog, $timeout) {
    var vm = this;
    var TabID = "01";
    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;
    vm.viewID = $window.viewid;
    vm.SessionKey = $window.sessionkey == '' ? null : $window.sessionkey;
    vm.isBasicMode = true;
    vm.isDashboardViewChecked = true;
    vm.CreateCampaignCheck = false;
    vm.hideBasicMode = false;
    vm.showValidationMsg = false
    vm.seg = {};
    vm.campaign = {};
    //vm.campaign.Kategori1ID = 8;
    vm.dtInstanceTPSearchSavedView = {};
    vm.dtInstanceOutboundSchedule = {};
    vm.dtInstanceOutboundHistory = {};
    vm.PopupID = "#scheduleModal";
    vm.isFirstLoadSavedView = true;
    vm.isFirstLoadAdvancedRules = true;
    vm.isFirstLoadBasicRules = true;
    vm.disableCampaign = false;
    vm.todayDate = ($filter('date')(new Date() + 1, 'dd MMM yyyy'))
    vm.isExact = false;
    vm.blnHasSchedule = false;
    //var newCampaignID = 0;

    //Get from outbound listing
    //vm.basicFilter = $window.jSonStringBasic;
    //vm.advancedFilter = $window.jSonStringAdvanced;

    vm.basicFilter = convertFromJson($window.jSonStringBasic);
    vm.advancedFilter = convertFromJson($window.jSonStringAdvanced);

    vm.newSegViewID = $window.newSegViewID;
    vm.newSegJenisKempenID = $window.newSegJenisKempenID;
    vm.isHCLEmailBlast = $window.isHCLEmailBlast;

    vm.constStatusNew = 27;
    vm.constStatusVerified = 39;

    $scope.permissionSetting = [];

    vm.isManageOutboundCampaignRole = $window.ismanageoutboundcampaignrole;
    vm.isManageHCLCampaignRole = $window.ismanagehclcampaignrole;

    //Chew 2019-12-04 --to include kempen duplication
    vm.newSegCCCampaignID = $window.newSegCCCampaignID;
    vm.newSegCampaignName = $window.newSegCampaignName;
    vm.newSegInteractionChannelID = $window.newSegInteractionChannelID;
    vm.newSegKategori1ID = $window.newSegKategori1ID;
    vm.newSegKategori2ID = $window.newSegKategori2ID;
    vm.newSegKategori3ID = $window.newSegKategori3ID;
    vm.newSegEmailTemplateID = $window.newSegEmailTemplateID;
    vm.newSegCCFromID = $window.newSegCCFromID;
    vm.CheckCampaignExist = $window.CheckCampaignExist;

    $scope.$on('AdvanceRules', function (event, data) {
        if (data == 'ADVInitializeComplete') {
            vm.init();
        }

    });

    //Start init
    vm.init = function () {
        var querystring = location.search;
        if (querystring) {
            TabID = querystring.substring(querystring.indexOf("=") + 1, querystring.length);
        }
        tabAction(TabID);
        console.log(vm);
        initSavedViewTable();
        if (vm.advancedFilter != undefined && vm.advancedFilter.AdvancedRules != null)
            AdvanceRulesService.updateItem(vm.advancedFilter.AdvancedRules);

        $scope.DisablePartialFieldMapping = true;
        if (vm.isHCLEmailBlast)
            $scope.tableType = 6;
        else
            $scope.tableType = 5;
        // datepicker
        vm.dateFromMinDate = null;
        vm.dateFromMaxDate = null;
        vm.buttonBarObj = $scope.ButtonBar;

        vm.dateFromOptions = {
            minDate: null, // 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: null, // 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.campaignDateOptions = {
            minDate: getSelectableDate(), // 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.schedule = {
        };
        vm.schedule.ScheduleStartDate = getSelectableDate();
        vm.schedule.ScheduleExpiryDate = getSelectableDate();

        vm.CreateCampaign = function () {

            //Chew 2019-12-04 --to include kempen duplication
            vm.CheckCampaignIsOut = 'Yes';
            angular.element('#CheckCampaignExist').val(vm.CheckCampaignIsOut);

            if (vm.CreateCampaignCheck) {
                vm.CreateCampaignCheck = false;

                //Chew 2019-12-04 --to include kempen duplication
                vm.campaign = {};
                tabAction("01");
            } else {

                vm.CreateCampaignCheck = true;
                vm.campaign = {};

                vm.kategori1Change(vm.campaign.Kategori1ID);
                vm.campaign.CampaignName = vm.seg.ViewName;
                vm.CampaignDirty = true;

                if (vm.isHCLEmailBlast) {
                    vm.campaign.InteractionChannelID = 2;
                    vm.campaign.Kategori1ID = 7;
                    vm.kategori1Change(vm.campaign.Kategori1ID);
                }
                else {
                    vm.campaign.InteractionChannelID = 5;
                    vm.campaign.Kategori1ID = 8;            
                    vm.kategori1Change(vm.campaign.Kategori1ID);
                }
                vm.toggleInteractionChannel(vm.campaign.InteractionChannelID, vm.isHCLEmailBlast);

            }
        };

        GetAllOutboundSchedule();
        getOutboundHistoryListByID();

        if (!vm.isHCLEmailBlast)
            vm.isHCLEmailBlast = false;

        if (vm.viewID > 0) {
            if (vm.isHCLEmailBlast) {
                OutboundSI.getEmailBlastSegmentise(vm.viewID).then(function (r) {
                    assignSegmentiseValue(r);
                });
            }
            else {
                OutboundSI.getOutboundSegmentise(vm.viewID).then(function (r) {
                    assignSegmentiseValue(r);
                });
            }

        }
        else {
            OutboundSI.getDropdown(vm.isHCLEmailBlast).then(function (r) {
                for (var key in r.data) {
                    vm[key] = r.data[key];
                }

                //Chew 2019-12-04 --to include kempen duplication
                if (vm.CheckCampaignExist == 'Yes') {
                    vm.CreateCampaignCheck = true;
                }

                //For new, default to Outbound/Phone
                if (vm.newSegInteractionChannelID)
                {
                    vm.campaign.InteractionChannelID = vm.newSegInteractionChannelID;
                }
                else {
                    vm.campaign.InteractionChannelID = 5;
                }
                vm.toggleInteractionChannel(vm.campaign.InteractionChannelID, vm.isHCLEmailBlast);
                //Chew --modify to fulfill the copy function
                if (vm.newSegKategori1ID) {
                    vm.campaign.Kategori1ID = vm.newSegKategori1ID;
                }
                else {
                    vm.campaign.Kategori1ID = 8;
                }
                vm.kategori1Change(vm.campaign.Kategori1ID);

                if(vm.newSegCampaignName)
                {
                    vm.campaign.CampaignName = vm.newSegCampaignName;
                }

                if (vm.newSegCCCampaignID)
                {
                    vm.campaign.CCCampaignID = vm.newSegCCCampaignID;
                }
               
                if (vm.newSegKategori2ID) {
                    vm.campaign.Kategori2ID = vm.newSegKategori2ID;
                    vm.kategori2Change(vm.campaign.Kategori2ID);
                }

                if (vm.newSegKategori3ID) {
                    vm.campaign.Kategori3ID = vm.newSegKategori3ID;
                    vm.kategori3Change(vm.campaign.Kategori3ID);
                }

                if (vm.newSegEmailTemplateID) {
                    vm.campaign.EmailTemplateID = vm.newSegEmailTemplateID;
                }

                if (vm.newSegCCFromID) {
                    vm.campaign.CCFromID = vm.newSegCCFromID;
                }

                vm.CCTemplateOptionEmail = $filter('filter')(vm.CCTemplateOption, { CCTemplateType: "E" }, true);
                vm.CCTemplateOptionSMS = $filter('filter')(vm.CCTemplateOption, { CCTemplateType: "S" }, true);
                if (vm.advancedFilter && vm.advancedFilter.DisplaySetting)
                    AdvanceRulesService.updateDisplaySetting(vm.advancedFilter.DisplaySetting);
                else
                    setTimeout(loadDisplaySetting(), 10);
                AdvanceRulesService.setOriDisplaySetting();
                $scope.$broadcast('AdvanceRules_DisplayColumn', 'INIT');

                //export excel record
                var m = $filter('filter')(vm.ParameterSettings, { ParameterID: 22 }, true);
                if (m && (m.length != 0)) {
                    vm.maxExportRecord = m[0].ParameterValue;
                }
            });
        }

        /**Save as Segmentise from Outbound Listing**/
        if ($scope.isSaveNewSeg === undefined) {
            if (vm.basicFilter) {
                $scope.jenisKempenID = vm.newSegJenisKempenID;
                vm.seg.JenisKempenID = vm.newSegJenisKempenID;

                if (vm.newSegViewID) {
                    AdminSI.getAdvanceRulesDropdown(5, $scope.jenisKempenID).then(function (r) {
                        for (var key in r.data) {
                            vm[key] = r.data[key];
                        }
                        assignDropdownOptiontoScope(r.data);

                        if (vm.isHCLEmailBlast) {
                            GeneralSI.getAdvancedRulesDetails(vm.newSegViewID, 6).then(function (r) {
                                console.log('Advance Rules Details', r.data);
                                $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
                                $scope.displaySetting.DisplayColumns = r.data.DisplaySetting.DisplayColumns;
                                //if (r.data.FieldsSorting != null && r.data.FieldsSorting && r.data.FieldsSorting.len > 0) $scope.displaySetting.FieldsSorting = r.data.DisplaySetting.FieldsSorting;
                                $scope.displaySetting.FieldsSorting = AdvanceRulesService.assignFieldsSorting(r.data.DisplaySetting.FieldsSorting, r.data.DisplaySetting.DisplayColumns);
                                AdvanceRulesService.updateDisplaySetting($scope.displaySetting);
                                AdvanceRulesService.setOriDisplaySetting();
                                populateBasicRulesFromOutboundListing();
                                vm.convertToAdvance();
                                $scope.AdvancedRulesDBNewSeg = r.data.Rules;


                                $scope.permissionSetting = AdvanceRulesService.getPermissionSetting();
                                $scope.permissionSetting.PermissionTypeID = r.data.PermissionType;
                                $scope.permissionUsers = r.data.PermissionUsers;
                                $scope.permissionRoles = r.data.PermissionRoles;
                                //populateBasicRules();
                            });
                        }
                        else {
                            GeneralSI.getAdvancedRulesDetails(vm.newSegViewID, 5).then(function (r) {
                                console.log('Advance Rules Details', r.data);
                                $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
                                $scope.displaySetting.DisplayColumns = r.data.DisplaySetting.DisplayColumns;
                                //if (r.data.FieldsSorting != null && r.data.FieldsSorting && r.data.FieldsSorting.len > 0) $scope.displaySetting.FieldsSorting = r.data.DisplaySetting.FieldsSorting;
                                $scope.displaySetting.FieldsSorting = AdvanceRulesService.assignFieldsSorting(r.data.DisplaySetting.FieldsSorting, r.data.DisplaySetting.DisplayColumns);
                                AdvanceRulesService.updateDisplaySetting($scope.displaySetting);
                                AdvanceRulesService.setOriDisplaySetting();
                                populateBasicRulesFromOutboundListing();
                                vm.convertToAdvance();
                                $scope.AdvancedRulesDBNewSeg = r.data.Rules;

                                $scope.permissionSetting = AdvanceRulesService.getPermissionSetting();
                                $scope.permissionSetting.PermissionTypeID = r.data.PermissionType;
                                $scope.permissionUsers = r.data.PermissionUsers;
                                $scope.permissionRoles = r.data.PermissionRoles;
                                //populateBasicRules();
                            });
                        }
                        $scope.$broadcast('AdvanceRules_DisplayColumn', 'INIT');
                        $scope.$broadcast('AdvanceRules_Permission', 'INIT');
                    });
                }

                if (!vm.newSegViewID) {
                    populateBasicRulesFromOutboundListing();
                    AdminSI.getAdvanceRulesDropdown(5, $scope.jenisKempenID).then(function (r) {
                        for (var key in r.data) {
                            vm[key] = r.data[key];
                        }
                        assignDropdownOptiontoScope(r.data);

                        setTimeout(loadDisplaySetting(), 10);
                        //$scope.$broadcast('AdvanceRules_DisplayColumn', 'INIT');
                    });
                }

            } else if (vm.advancedFilter) {
                vm.isBasicMode = false;

                AdvanceRulesService.setDynamicDisplayInd(true);
                //vm.seg.JenisKempenID = vm.newSegJenisKempenID;
                // CHIN TATvm.advancedFilter = angular.fromJson((vm.advancedFilter).replace(/&quot;/g, '"'));
                vm.seg.JenisKempenID = vm.advancedFilter.AdvancedRules[0].RuleGroup[0].FieldValues[0].FieldValue; //get the first row from advance rules
                $scope.jenisKempenID = vm.seg.JenisKempenID;
                //vm.advancedFilter.viewID = 1;
                //if (vm.advancedFilter.viewID > 0) {
                //	GeneralSI.getAdvancedRulesDetails(vm.advancedFilter.viewID, 5).then(function (r) {
                //		if (r.status == 200) {
                //			console.log('Advance Rules Details', r.data);
                //			vm.advanceRulesDetails = r.data;
                //			$scope.AdvancedRulesDB = r.data.Rules;
                //			$scope.broadcastPopulateBasicRulesEvent();
                //		}
                //	});
                //}
                //else {
                //$scope.jenisKempenID = vm.newSegJenisKempenID;
                AdminSI.getAdvanceRulesDropdown(5, $scope.jenisKempenID).then(function (r) {
                    for (var key in r.data) {
                        vm[key] = r.data[key];
                    }

                    AdvanceRulesService.updateDisplaySetting(vm.advancedFilter.DisplaySetting);
                    AdvanceRulesService.setOriDisplaySetting();
                    assignDropdownOptiontoScope(r.data);
                    populateBasicRules();

                    $scope.$broadcast('AdvanceRules_DisplayColumn', 'INIT');
                });
            };
        }
        /**Save as Segmentise from Outbound Listing -END**/
    };
    //End init

    vm.toggleInteractionChannel = function (interactionChannel, isHCLEmailBlast) {
        if (interactionChannel == 5) //phone
        {
            var a = [];
            for (var i = 0; i < vm.CCCampaignOption.length; i++) {
                if (vm.CCCampaignOption[i].Code.indexOf("SMS_") < 0 && vm.CCCampaignOption[i].Code.indexOf("eMail_") < 0) // exclude SMS and email
                    a.push(vm.CCCampaignOption[i]);
            }
            vm.CCCampaignOptionFiltered = a;
        }
        if (interactionChannel == 2) //email
        {
            //var a;
            //a = $filter('filter')(vm.CCCampaignOption, { Code: "E_" }, false);
            //if (a.length > 0)
            //    vm.campaign.CCCampaignID = a[0].Value;

            var a = [];
            for (var i = 0; i < vm.CCCampaignOption.length; i++) {
                if (vm.CCCampaignOption[i].Code.indexOf("eMail_") >= 0)
                    a.push(vm.CCCampaignOption[i]);
            }

            vm.CCCampaignOptionFiltered = a;
        }
        if (interactionChannel == 6) //sms
        {
            //a = $filter('filter')(vm.CCCampaignOption, { Code: "S_" }, false);
            //if (a.length > 0)
            //    vm.campaign.CCCampaignID = a[0].Value;
            var a = [];
            for (var i = 0; i < vm.CCCampaignOption.length; i++) {
                if (vm.CCCampaignOption[i].Code.indexOf("SMS_") >= 0)
                    a.push(vm.CCCampaignOption[i]);
            }

            vm.CCCampaignOptionFiltered = a;
        }
    }

    function convertFromJson(value) {
        var convertedObj;
        if (value != '') convertedObj = angular.fromJson(decodeEntities(value));
        return convertedObj;
    }

    function getSelectableDate() {
        var dateNow = new Date();
        dateNow.setDate(dateNow.getDate() + 1);
        dateNow.setHours(0, 0, 0, 0)
        return dateNow;
    }

    function assignSegmentiseValue(r) {
        vm.seg = r.data;
        vm.disableCampaign = vm.seg.IsCampaignStarted;
        if (vm.disableCampaign) {
            //AdvanceRulesService.setAllowEdit(false);
            $scope.DisableAllRules = true; // CT
        } else {
            $scope.DisableAllRules = false;
        }
        $scope.jenisKempenID = vm.seg.JenisKempenID;

        $scope.broadcastGetDropDownEvent()
        vm.isDynamicDisplayColumn = true;
        AdvanceRulesService.setDynamicDisplayInd(true);
        setTimeout(function () {
            if (vm.isHCLEmailBlast) {
                GeneralSI.getAdvancedRulesDetails(vm.viewID, 6).then(function (r) {
                    console.log('Advance Rules Details', r.data);
                    $scope.AdvancedRulesDB = r.data.Rules; $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
                    $scope.displaySetting.DisplayColumns = r.data.DisplaySetting.DisplayColumns;
                    //if (r.data.FieldsSorting != null && r.data.FieldsSorting && r.data.FieldsSorting.len > 0) $scope.displaySetting.FieldsSorting = r.data.DisplaySetting.FieldsSorting;
                    $scope.displaySetting.FieldsSorting = AdvanceRulesService.assignFieldsSorting(r.data.DisplaySetting.FieldsSorting, r.data.DisplaySetting.DisplayColumns);
                    AdvanceRulesService.updateDisplaySetting($scope.displaySetting);
                    AdvanceRulesService.setOriDisplaySetting();

                    $scope.permissionSetting = AdvanceRulesService.getPermissionSetting();
                    $scope.permissionSetting.PermissionTypeID = r.data.PermissionType;
                    $scope.permissionUsers = r.data.PermissionUsers;
                    $scope.permissionRoles = r.data.PermissionRoles;

                    AdvanceRulesService.setPermissionType($scope.permissionSetting.PermissionTypeID);
                    AdvanceRulesService.setPermissionUser($scope.permissionUsers);
                    AdvanceRulesService.setPermissionRole($scope.permissionRoles);
                    $scope.$broadcast('AdvanceRules_Permission', 'INIT');

                    populateBasicRules();
                    vm.isFirstLoadBasicRules = false;
                });
            }
            else {
                GeneralSI.getAdvancedRulesDetails(vm.viewID, 5).then(function (r) {
                    console.log('Advance Rules Details', r.data);
                    $scope.AdvancedRulesDB = r.data.Rules; $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
                    $scope.displaySetting.DisplayColumns = r.data.DisplaySetting.DisplayColumns;
                    //if (r.data.FieldsSorting != null && r.data.FieldsSorting && r.data.FieldsSorting.len > 0) $scope.displaySetting.FieldsSorting = r.data.DisplaySetting.FieldsSorting;
                    $scope.displaySetting.FieldsSorting = AdvanceRulesService.assignFieldsSorting(r.data.DisplaySetting.FieldsSorting, r.data.DisplaySetting.DisplayColumns);
                    AdvanceRulesService.updateDisplaySetting($scope.displaySetting);
                    AdvanceRulesService.setOriDisplaySetting();
                    populateBasicRules();
                    vm.isFirstLoadBasicRules = false;

                    $scope.permissionSetting = AdvanceRulesService.getPermissionSetting();
                    $scope.permissionSetting.PermissionTypeID = r.data.PermissionType;
                    $scope.permissionUsers = r.data.PermissionUsers;
                    $scope.permissionRoles = r.data.PermissionRoles;

                    AdvanceRulesService.setPermissionType($scope.permissionSetting.PermissionTypeID);
                    AdvanceRulesService.setPermissionUser($scope.permissionUsers);
                    AdvanceRulesService.setPermissionRole($scope.permissionRoles);
                    $scope.$broadcast('AdvanceRules_Permission', 'INIT');
                });
            }
        }, 100);




        vm.campaign = r.data.Campaign

        OutboundSI.getDropdown(vm.isHCLEmailBlast).then(function (r) {
            for (var key in r.data) {
                vm[key] = r.data[key];
            }
            if (vm.seg.Campaign) {
                vm.kategori1Change(vm.campaign.Kategori1ID);
                vm.kategori2Change(vm.campaign.Kategori2ID);
                vm.kategori3Change(vm.campaign.Kategori3ID);
            }
            vm.CCTemplateOptionEmail = $filter('filter')(vm.CCTemplateOption, { CCTemplateType: "E" }, true);
            vm.CCTemplateOptionSMS = $filter('filter')(vm.CCTemplateOption, { CCTemplateType: "S" }, true);
            if (vm.campaign)
                vm.toggleInteractionChannel(vm.campaign.InteractionChannelID, vm.isHCLEmailBlast);

            //export excel record
            var m = $filter('filter')(vm.ParameterSettings, { ParameterID: 22 }, true);
            if (m && (m.length != 0)) {
                vm.maxExportRecord = m[0].ParameterValue;
            }
        });

        if (vm.seg.Campaign) {
            vm.CreateCampaignCheck = true;
            vm.dtInstanceOutboundSchedule.reloadData();
            vm.dtInstanceOutboundHistory.reloadData();
        }
        else {
            vm.CreateCampaignCheck = false;
        };

        if (vm.seg.IsBasicMode) {
            vm.isBasicMode = true;
            vm.hideBasicMode = false;
        }
        else {
            vm.isBasicMode = false;
            vm.hideBasicMode = true;
        }
    }

    function assignDropdownOptiontoScope(data, isToggleJenisKempen) {
        if (!isToggleJenisKempen)
            $scope.isSaveNewSeg = true;
        $scope.fieldMappingOptionsNewSeg = data['FieldMappingOptions'];
        $scope.fieldOperatorOptionsNewSeg = data['FieldOperatorOptions'];
        $scope.jenisKempenOptionsNewSeg = data['JenisKempenIDOptions'];
    };

    // Populate basic rules from outbound listing
    function populateBasicRulesFromOutboundListing() {
        //vm.basicFilter = angular.fromJson((vm.basicFilter).replace(/&quot;/g, '"'));

        vm.isBasicMode = true;
        vm.jenisCukai = vm.basicFilter.jenisCukai;
        vm.tahunTaksiran = vm.basicFilter.tahunTaksiran;
        vm.jenisPengenalan = vm.basicFilter.jenisPengenalan;
        vm.noPengenalan = vm.basicFilter.noPengenalan;
        vm.batchRefNo = vm.basicFilter.batchRefNo;
        vm.nama = vm.basicFilter.nama;
        vm.rujukanNo = vm.basicFilter.rujukanNo;
        vm.isExact = vm.basicFilter.isExact;
        vm.outboundStatusID = vm.basicFilter.outboundStatusID;
        if (vm.basicFilter.reMSDateFrom)
            vm.reMSDateFrom = new Date(vm.basicFilter.reMSDateFrom);//$filter('date')(new Date(vm.basicFilter.reMSDateFrom), 'dd MMM yyyy');
        if (vm.basicFilter.reMSDateTo)
            vm.reMSDateTo = new Date(vm.basicFilter.reMSDateTo);//$filter('date')(new Date(vm.basicFilter.reMSDateTo), 'dd MMM yyyy');
        if (vm.basicFilter.importedDateFrom)
            vm.importedDateFrom = new Date(vm.basicFilter.importedDateFrom);//$filter('date')(new Date(vm.basicFilter.importedDateFrom), 'dd MMM yyyy');
        if (vm.basicFilter.importedDateTo)
            vm.importedDateTo = new Date(vm.basicFilter.importedDateTo);//$filter('date')(new Date(vm.basicFilter.importedDateTo), 'dd MMM yyyy');
    };

    //Search
    vm.search = function () {
        vm.searchButtonClicked = true;
        if (validateField()) {

            if (vm.isBasicMode) {
                //GetOutboundColumns();
                //vm.dtInstanceTPSearchSavedView.reloadData();
                vm.showBasicTable = true;
                console.log('Basic Jenis Kempen ', $scope.jenisKempenID);
                loadDynamicColumns(0, $scope.jenisKempenID);
            }
            else {
                if (GeneralService.validateAdvancedRules(true)) {
                    console.log('Advance Jenis Kempen ', $scope.jenisKempenID);
                    //vm.dtInstanceTPSearchSavedView.reloadData();
                    vm.showBasicTable = true;
                    loadDynamicColumns(0, $scope.jenisKempenID);
                    console.log('Basic', vm.isBasicMode);
                    console.log(AdvanceRulesService.getList());
                }
            }
        }
    };


    vm.clear = function (segmentiseForm) {

        swal({
            title: "Adakah anda pasti untuk padamkan saringan terperinci?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: true,
            closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                //$scope.jenisKempenID = 0;
                vm.viewID = 0;
                if (!$window.viewid)
                    vm.showBasicTable = false;
                $timeout(function () {
                    clearField();
                });
                clearCheckbox();
                AdvanceRulesService.setClearEnabledOnly(true);
                $scope.broadcastClearRulesEvent();
                segmentiseForm.$dirty = true;

                //$scope.$apply();
            }
        });
    }


    function validateField() {
        vm.invalidNoPengenalan = false;
        vm.invalidJenisPengenalan = false;
        var isValid = true;
        vm.invalidNamaLength = false;
        vm.invalidRujukanNoLength = false;
        vm.invalidJenisKempen = false;
        vm.showErrReMSDate = false;
        vm.ErrMsgReMSDate = "";
        vm.showErrImportedDate = false;
        vm.ErrMsgImportedDate = "";

        if (vm.viewID == "") {
            if (!vm.seg.JenisKempenID) {
                vm.invalidJenisKempen = true;
                isValid = false;
            }
        }
        if (vm.isBasicMode > 0) {
            //else if (vm.viewID > 0) {
            // if any input
            if (vm.isHCLEmailBlast) {
                if ((vm.jenisPengenalan) && (!vm.noPengenalan)) {
                    vm.invalidNoPengenalan = true;
                    isValid = false;
                }

                else if (!vm.jenisPengenalan && (vm.noPengenalan)) {
                    vm.invalidJenisPengenalan = true;
                    isValid = false;
                }
            }

            if (vm.nama) {
                if (vm.nama.length < 6) {
                    vm.invalidNamaLength = true;
                    isValid = false;
                }
            }

            if (vm.rujukanNo) {
                if (vm.rujukanNo.length < 6) {
                    vm.invalidRujukanNoLength = true;
                    isValid = false;
                }

            }

            if (!vm.isHCLEmailBlast) {
                if (vm.reMSDateFrom || vm.reMSDateTo) {
                    var d = new Date(vm.reMSDateFrom);
                    var dt = new Date(vm.reMSDateTo);

                    if ((!vm.reMSDateFrom && vm.reMSDateTo) ||
                        (vm.reMSDateFrom && !vm.reMSDateTo)) {
                        vm.ErrMsgReMSDate = "Banjaran tarikh tidak sah.";
                        vm.showErrReMSDate = true;
                        isValid = false;
                    }

                    if (d > dt) {
                        vm.ErrMsgReMSDate = "Date To must be greater than Date From.  ";
                        vm.showErrReMSDate = true;
                        isValid = false;
                    }
                }
            }

            if (vm.importedDateFrom || vm.importedDateTo) {
                var d = new Date(vm.importedDateFrom);
                var dt = new Date(vm.importedDateTo);

                if ((!vm.importedDateFrom && vm.importedDateTo) ||
                    (vm.importedDateFrom && !vm.importedDateTo)) {
                    vm.ErrMsgImportedDate = "Banjaran tarikh tidak sah.";
                    vm.showErrImportedDate = true;
                    isValid = false;
                }

                if (d > dt) {
                    vm.ErrMsgImportedDate = "Date To must be greater than Date From.  ";
                    vm.showErrImportedDate = true;
                    isValid = false;
                }
            }
        }

        return isValid;
    };

    vm.promptConvertToAdvancedRules = function (jenisKempenForm, segmentiseTabForm, segmentiseForm) {

        swal({
            title: "Confirmation",
            text: "Do you want to convert as advanced rules? This will replace the existing advanced rules.",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: true
        },
        function (isConfirm) {
            if (isConfirm) {
                if (!vm.isSaveBasic)
                    vm.isBasicMode = false;
                segmentiseTabForm.$setPristine();
                jenisKempenForm.$setPristine();
                vm.convertToAdvance();
                $scope.$apply();
                segmentiseForm.$dirty = true;
            }
            else {
                populateJenisKempenforAdvancedRules(true);
                vm.isBasicMode = false;
                $scope.$apply();
                //form.$setPristine();
            }
        });

    }

    vm.toggleSearchMode = function (jenisKempenForm, segmentiseTabForm, segmentiseForm, searchMode) {
        if (searchMode == 'Terperinci' && vm.advancedFilter)
            return;

        if (searchMode == 'Asas' && vm.basicFilter)
            return;

        if (jenisKempenForm.$dirty || segmentiseTabForm.$dirty)
            var isDirty = true;

        //if (vm.viewID == "" || vm.viewID == null || vm.seg.IsBasicMode) {
        if (!vm.blnHasSchedule) {
            if (validateField()) {
                if (vm.isBasicMode) {
                    if (isDirty || vm.seg.IsBasicMode || vm.seg.IsBasicMode == undefined) {
                        vm.promptConvertToAdvancedRules(jenisKempenForm, segmentiseTabForm, segmentiseForm);
                        //reset form pristine, so that rules only converted when dirty
                        //segmentiseTabForm.$setPristine();
                        //jenisKempenForm.$setPristine();
                    }
                    else {
                        vm.isBasicMode = false;
                    }
                    //vm.showBasicTable = false;
                    //vm.sectionTitle = "Advance Filters";
                }
                else {
                    AdvanceRulesService.resetDisplaySetting();
                    if (vm.seg.IsBasicMode || !vm.viewID) {
                        //vm.showAdvTable = false;
                        vm.isBasicMode = true;
                    }
                    //vm.sectionTitle = "Basic Filters";
                    //vm.showBasicTable = true;
                }

                $scope.$broadcast('AdvanceRules_DisplayColumn', 'INIT');
            }
        }
    };

    vm.toggleJenisKempenOptions = function () {
        //default view
        if (vm.seg.JenisKempenID == "" || vm.seg.JenisKempenID == null) {
            $scope.jenisKempenID = 0;
        }
        else {
            console.log('Jenis Kempen ID', vm.seg.JenisKempenID);
            $scope.jenisKempenID = vm.seg.JenisKempenID;
        }
        //if (!vm.isBasicMode) {
        AdminSI.getAdvanceRulesDropdown(5, $scope.jenisKempenID).then(function (r) {
            assignDropdownOptiontoScope(r.data, true);
            populateJenisKempenforAdvancedRules();
            if (vm.advancedFilter != undefined && vm.advancedFilter != null) {
                AdvanceRulesService.updateDisplaySetting(vm.advancedFilter.DisplaySetting);
                AdvanceRulesService.setOriDisplaySetting();
            }
            assignDropdownOptiontoScope(r.data);
            setTimeout(loadDisplaySetting(), 10);
        });
        //$scope.broadcastGetDropDownEvent();
        //setTimeout(function () { populateJenisKempenforAdvancedRules(); }, 50);
        //}

        if (vm.showBasicTable)
            loadDynamicColumns(0, $scope.jenisKempenID);

    };

    vm.convertToAdvance = function () {

        //if (validateField()) {
        populateBasicRules();
        //}
        //else {
        //    form.$setPristine();
        //    vm.isBasicMode = true;
        //}
    }

    //Datatable checkBox 
    vm.selectPage = false;
    vm.selectAll = false;
    vm.DataList = {};

    vm.selectedDataList = {
        DataList: []
    };

    vm.currentItems = {};

    function clearDataList() {
        vm.DataList = {};

        vm.selectedDataList = {
            DataList: []
        };
    };

    function clearCheckbox(skipClearDataList) {
        vm.selectPage = false;
        vm.selectAll = false;

        if (!skipClearDataList) {
            clearDataList();
        }

        vm.disabledChkbox = false;
    };

    vm.assignSelected = function ($event, DataID, StatusID) {
        if ($event.currentTarget.checked) { //tick
            pushToList(DataID, StatusID);
        }
        else { //untick
            removeFromList(DataID);
            vm.selectPage = false;
        }
        vm.selectedCount = vm.selectedDataList.DataList.length;

        console.log('vm.selectedDataList', vm.selectedDataList);
    }

    function add(StatusID, DataID) {
        var queryResult = document.getElementById(DataID);

        if (vm.selectPage) { //tick
            queryResult.checked = true;
            var a = $filter('filter')(vm.selectedDataList.DataList, {
                DataID: DataID
            }, true);

            if (!a.length) {
                pushToList(DataID, StatusID);
            }
        }
        else { //untick
            queryResult.checked = false
            removeFromList(DataID);
        }

        vm.selectedCount = vm.selectedDataList.DataList.length;
    }

    function pushToList(DataID, StatusID) {
        vm.selectedDataList.DataList.push({
            DataID: DataID,
            StatusID: StatusID
        })
    }

    function removeFromList(DataID) {
        for (var i = 0; i < vm.selectedDataList.DataList.length; i++) {
            if (vm.selectedDataList.DataList[i].DataID == DataID) {
                vm.selectedDataList.DataList.splice(i, 1);
            }
        }
        //var idx = vm.selectedDataList.DataList.indexOf(DataID);
        //vm.selectedDataList.DataList.splice(idx, 1);
    }

    function manualTickSelectedData() {
        for (var i = 0, l = vm.selectedDataList.DataList.length; i < l; i++) {
            queryResult = document.getElementById(vm.selectedDataList.DataList[i].DataID);
            if (queryResult)
                queryResult.checked = true;
        }
        vm.selectedCount = vm.selectedDataList.DataList.length;
    }

    vm.selectPagefunc = function (selectPage, selectedItems) {
        for (var i = 0, l = vm.currentItems.length; i < l; i++) {
            if (vm.isHCLEmailBlast)
                add(vm.currentItems[i].EmailBlastStatusID, vm.currentItems[i].EmailDataID);
            else
                add(vm.currentItems[i].StatusID, vm.currentItems[i].DataID);
        }
        vm.selectedCount = vm.selectedDataList.DataList.length;
        console.log('vm.selectedDataList', vm.selectedDataList);
    }

    vm.selectAllfunc = function (isSelectAll) {
        var queryResult;
        vm.selectAll = !vm.selectAll;
        if (isSelectAll)
            vm.selectAll = true;
        vm.selectPage = false;
        var currItemsLen = vm.currentItems.length;

        if (!vm.selectAll) {
            while (currItemsLen--) {
                if (vm.isHCLEmailBlast)
                    queryResult = document.getElementById(vm.currentItems[currItemsLen].EmailDataID);
                else
                    queryResult = document.getElementById(vm.currentItems[currItemsLen].DataID);
                queryResult.checked = false;
            }
            vm.disabledChkbox = false;
            vm.selectedCount = 0;
        }
        else {
            vm.selectedDataList = {
                DataList: []
            };
            while (currItemsLen--) {
                if (vm.isHCLEmailBlast)
                    queryResult = document.getElementById(vm.currentItems[currItemsLen].EmailDataID);
                else
                    queryResult = document.getElementById(vm.currentItems[currItemsLen].DataID);
                queryResult.checked = true;
            }
            vm.selectPage = false;
            vm.disabledChkbox = true;
        }
    }
    // Datatable checkBox --end

    vm.verifyDataByList = function () {
        if (!vm.selectedDataList.DataList.length && !vm.selectAll) {
            swal({
                title: "Batal!",
                text: "Please select at least one record to verify.",
                type: "error",
                showConfirmButton: true
            });
            return;
        }

        swal({
            title: "Adakah anda pasti untuk sahkan semua data yang dipilih?",
            text: "Hanya untuk status = Baru.",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                var outboundFilter = assignModel();

                model = {
                    DataList: vm.selectedDataList.DataList,
                    OutboundFilter: outboundFilter,
                    IsSelectAll: vm.selectAll,
                    IsHCLEmailBlast: vm.isHCLEmailBlast,
                    JenisKempenID: $scope.jenisKempenID
                }

                OutboundSI.verifyDataByList(model).then(function (r) {
                    if (r.data) {
                        var count = r.data;
                        swal({
                            title: "Data Segmen Disahkan!",
                            text: count + " rekod telah berjaya disahkan.",
                            type: "success",
                            //timer: 2500,
                            showConfirmButton: true,
                            closeOnConfirm: true
                        });
                    }
                    else {
                        swal({
                            title: "Batal!",
                            text: "No available new data to be verified.",
                            type: "error",
                            showConfirmButton: true
                        });
                    }
                    vm.dtInstanceTPSearchSavedView.reloadData();
                    clearCheckbox();
                });
            }
            else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });
    };


    function loadDynamicColumns(viewID, jenisKempenID, skipReloadData) {
        // Assign Jenis kempen ID to Advance Rule
        $scope.jenisKempenID = jenisKempenID;
        $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
        vm.isDynamicDisplayColumn = AdvanceRulesService.getDynamicDisplayInd();
        var model = {
            ViewID: viewID,
            JenisKempenID: jenisKempenID,
            IsHCLEmailBlast: vm.isHCLEmailBlast,
            IsDynamicDisplayColumn: vm.isDynamicDisplayColumn,
            DisplayColumns: vm.isDynamicDisplayColumn ? $scope.displaySetting.DisplayColumns : null
        };
        console.log('model ', model);
        //$scope.broadcastGetDropDownEvent();
        OutboundSI.getOutboundViewColumns(model).then(function (r) {
            console.log("get columns", r.data);
            vm.dtColumnsTPSearchSavedView = [];

            var columnDataID;
            if (vm.isHCLEmailBlast) {
                columnDataID = "EmailDataID";
            }
            else {
                columnDataID = "DataID";
            }

            angular.forEach(r.data, function (item, i) {
                var dtColumn = null;
                if (i == 0) { //added RowNum column for outbound listing
                    //Temporary add check box to result
                    //if (vm.campaign && vm.campaign.InteractionChannelID == 2) {
                    //    dtColumn = DTColumnBuilder.newColumn('RowNum').withTitle(' ').renderWith(function (data) {
                    //        return '<span><input type="checkbox" value="1"></span>';
                    //    }).withOption('defaultContent', '-');
                    //    vm.dtColumnsTPSearchSavedView.push(dtColumn);
                    //};

                    var titleHtml = '<input type="checkbox" ng-disabled="segmentise.disabledChkbox || !segmentise.totalDataCount" ng-model="segmentise.selectPage" ng-click="segmentise.selectPagefunc(segmentise.selectPage, segmentise.selected)">';

                    dtColumn = DTColumnBuilder.newColumn(columnDataID).withTitle(titleHtml).notSortable().withOption('searchable', false).withOption('width', '3px').renderWith(function (data, type, row) {
                        var statusID;
                        if (vm.isHCLEmailBlast)
                            statusID = row["EmailBlastStatusID"];
                        else
                            statusID = row["StatusID"];

                        return ' <input id="' + data + '" ' +
                            'type="checkbox" ng-disabled="segmentise.disabledChkbox" ng-click="segmentise.assignSelected($event, ' + data + ',' + statusID + ')" />'

                    });
                    vm.dtColumnsTPSearchSavedView.push(dtColumn);


                    dtColumn = DTColumnBuilder.newColumn("RowNum").notSortable().withTitle("No.").withOption('width', '35px');
                    //    .renderWith(function (data, type, row) {
                    //    return '<a href="/outbound/profile/detail/' + row.JenisKempenID + '/' + row.DataID + '">' + data + '</a>'
                    //}).withOption('defaultContent', '-');
                    vm.dtColumnsTPSearchSavedView.push(dtColumn);
                }

                if (item.FieldMapping == "NamaPembayarCukai" || item.FieldMapping == "TAX_PAYER_NAME1" || item.FieldMapping == "Name") {
                    if (vm.isHCLEmailBlast) {
                        dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type, row) {
                            return '<a target="_blank" href="/Outbound/HCLEmailBlastProfile/Detail/' + row.JenisKempenID + '/' + row.EmailDataID + '">' + data + '</a>'
                        }).withOption('defaultContent', '-').withOption('width', '200px');
                    }
                    else {
                        dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type, row) {
                            return '<a target="_blank" href="/outbound/profile/detail/' + row.JenisKempenID + '/' + row.DataID + '">' + data + '</a>'
                        }).withOption('defaultContent', '-').withOption('width', '200px');
                    }
                }
                else if (item.FieldType == 'Date') {
                    dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type) {
                        return $filter('date')(data, $scope.DateTimeFormat);
                    }).withOption('defaultContent', '-');
                }
                else if (item.FieldType == 'Currency') {
                    dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).withClass('text-right').renderWith(function (data, type) {
                        return $filter('number')(data, 2);
                    }).withOption('defaultContent', '-');
                }
                else if (item.FieldMapping == "Status") {
                    dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(renderNullAsDash).withOption('width', '100px').withOption('defaultContent', '-');
                }
                else if (item.FieldMapping == "HasError") {
                    dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle("").notSortable().renderWith(function (data, type, row) {
                        var statusID;
                        if (vm.isHCLEmailBlast)
                            statusID = row["EmailBlastStatusID"];
                        else
                            statusID = row["StatusID"];

                        var input = data =="YA" && (statusID == vm.constStatusNew || statusID == vm.constStatusVerified) ? '<i class="case fa fa-exclamation-circle" style="color:red;" title="Data tidak sah"></i >' : '';
                        return input;
                    });
                }
                else if (item.FieldMapping == "NoRujukanCukai") {
                    dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type, row) {
                        return vm.isHCLEmailBlast ? (data ? row["JenisFailCukai"] + ' ' + data : '-') : data;
                    }).withOption('defaultContent', '-').withOption('width', '150px');
                }
                else {
                    dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(renderNullAsDash).withOption('defaultContent', '-');
                }
                if (item.FieldMapping == "HasError")
                    vm.dtColumnsTPSearchSavedView.splice(1, 0, dtColumn)
                else
                    if (item.FieldMapping != "JenisFailCukai")
                        vm.dtColumnsTPSearchSavedView.push(dtColumn);
            });
        });

        if (!skipReloadData)
            vm.dtInstanceTPSearchSavedView.reloadData();

    }

    function renderNullAsDash(data, type, row, meta) {
        return data ? data : '-';
    }

    //Advance Rule: Broadcast event to Advance rules child view to clear contents
    $scope.broadcastGetDropDownEvent = function () {
        $scope.$broadcast('AdvanceRules', 'GETDROPDOWN');
    };

    //Advance Rule: Broadcast event to populate Basic Rules into Advance Rules
    $scope.broadcastPopulateBasicRulesEvent = function () {
        populateBasicRules();
    };

    //Advance Rule:  Broadcast event to Advance rules child view to get latest content
    $scope.broadcastGetRulesEvent = function () {
        $scope.$broadcast('AdvanceRules', 'LATESTDATA');
    };

    //Advance Rule: Broadcast event to Advance rules child view to clear contents
    $scope.broadcastClearRulesEvent = function () {
        $scope.$broadcast('AdvanceRules', 'CLEAR');
    };

    /**Functions used to populate advanced rules when save as new segmentise from Outbound Listing**/
    vm.multiSelect = {
    };
    vm.multiSelect.selected = [];
    vm.OperatorOptions = [];
    vm.FieldType = [12];

    vm.AddNewRulesFromBasicOrDB = function () {
        // Get data from parents
        var tableType = $scope.tableType;
        var jenisKempenID = $scope.jenisKempenID;
        var i = $scope.rulesIndex;
        var d = $scope.rulesOperator;
        var fieldType = $scope.rulefieldType;
        var fieldOperator = $scope.rulefieldOperator;
        var fieldValue = $scope.rulesFieldValue;
        var fieldMapping = $scope.rulesFieldMapping;
        var rulesType = $scope.rulesType;
        var groupingOperator = $scope.groupingOperator;
        var ruleID = $scope.ruleID;
        var ruleGroupID = $scope.ruleGroupID;
        var isFromDB = $scope.isFromDB;
        var allowRemove = true;
        var ruleGroupID = $scope.ruleGroupID;
        var ruleGroupFieldsID = $scope.ruleGroupFieldsID;

        //var fieldOps = $filter('filter')($scope.AdvanceRules, function (item) {
        //    angular.forEach(item, function (ruleGroup, key) {
        //    });
        //});

        $scope.AdvanceRules = AdvanceRulesService.getList();

        var fieldOperatorOptions = $scope.fieldOperatorOptionsNewSeg ? $scope.fieldOperatorOptionsNewSeg : vm.FieldOperatorOptions;
        if ($scope.fieldOperatorOptionsNewSeg)
            vm.FieldOperatorOptions = $scope.fieldOperatorOptionsNewSeg;
        var fieldOps = $filter('filter')(fieldOperatorOptions, {
            LookupParamSysID: fieldType, OperatorCode: fieldOperator
        });
        if ($scope.fieldMappingOptionsNewSeg)
            vm.FieldMappingOptions = $scope.fieldMappingOptionsNewSeg;

        var fieldMappingOptions = $scope.fieldMappingOptionsNewSeg ? $scope.fieldMappingOptionsNewSeg : vm.FieldMappingOptions;

        var selectedField = $filter('filter')(vm.FieldMappingOptions, {
            FieldMapping: fieldMapping, FieldType: fieldType, JenisKempenID: jenisKempenID
        }, true);

        var selectedFieldMappingID;
        if (selectedField == undefined) {
            selectedFieldMappingID
        } else {
            selectedFieldMappingID = selectedField[0].FieldMappingID;
        }
        $scope.selectedFieldMappingID = selectedFieldMappingID;
        // remove initial row for the first inserted new rules
        $scope.i = i;

        //SL added ruleGroupsIndex
        // remove initial row for the first inserted new rules
        if (i == 0 && !ruleGroupsIndex) $scope.AdvanceRules = [];
        //if (i == 0) $scope.AdvanceRules = [];

        //dont allow outbound jeniskempen to be removed
        var allowEdit = true;
        if (tableType == 5) {
            if (fieldMapping == "JenisKempenID") {
                allowRemove = false;
                allowEdit = true;
            }
        }


        var childIndex = 0;
        // Bind to existing rule if exits else push as new rules (grouping scenario)
        var existingRule = $filter('filter')($scope.AdvanceRules, { ViewRuleID: ruleID }, true);
        if (existingRule != undefined && existingRule != null && existingRule.length > 0) {
            existingRule[0].RuleGroup.push({
                'ViewRuleGroupID': ruleGroupID,
                'ViewRuleID': ruleID,
                'DisplayField': selectedFieldMappingID,
                'FieldType': fieldType,
                'OperatorOptions': [],
                'ValueOptions': [],
                'FieldMapping': '',
                'TableName': '',
                'FieldOperator': fieldOps[0].DataTypeID,
                'FieldOperatorCode': fieldOperator,
                'FieldMappingRef': '0',
                'FieldMappingRefCode': '0',
                'IsInnerJoin': '0',
                'selected': [],
                'IsFromDB': isFromDB,
                'IsMultiple': false,
                'FieldEnabled': allowEdit,
                'FieldValues': [
                    //{
                    //    'FieldValue': fieldValue
                    //}
                ]
            });
            childIndex = existingRule[0].RuleGroup.length - 1;
        }
        else {
            $scope.AdvanceRules.splice(i, 0, {
                'ViewRuleID': ruleID,
                'Sequence': i + 1,
                'RuleType': rulesType,
                'RuleOperator': d,
                'GroupingOperator': groupingOperator,
                'RowSelected': false,
                'AllowRemove': allowRemove,
                'IsFromDB': isFromDB,
                RuleGroup: [
            {
                'ViewRuleGroupID': ruleGroupID,
                'ViewRuleID': ruleID,
                'DisplayField': selectedFieldMappingID,
                'FieldType': fieldType,
                'OperatorOptions': [],
                'ValueOptions': [],
                'FieldMapping': '',
                'TableName': '',
                'FieldOperator': fieldOps[0].DataTypeID,
                'FieldOperatorCode': fieldOperator,
                'FieldMappingRef': '0',
                'FieldMappingRefCode': '0',
                'IsInnerJoin': '0',
                'selected': [],
                'IsFromDB': isFromDB,
                'IsMultiple': false,
                'FieldEnabled': allowEdit,
                'FieldValues': [
                    //{
                    //    'FieldValue': fieldValue
                    //}
                ]
            }
                ]
            });
        }

        setSequence($scope.AdvanceRules, i + 1);
        console.log($scope.AdvanceRules);

        // Get dropdown options for Operators
        //vm.fieldOnChange(i, 0, selectedFieldMappingID);

        vm.fieldOnChange($scope.i, 0, $scope.selectedFieldMappingID);


        // Set field value after set Operator options based on field type
        if (fieldType == 15) { //Dropdown
            $scope.AdvanceRules[i].RuleGroup[childIndex].selected = [];//SL 0 substitute with childIndex??
            angular.forEach(fieldValue, function (obj) {
                $scope.AdvanceRules[i].RuleGroup[childIndex].selected.push([obj.ViewRuleGroupFieldsID, obj.FieldValue]);
            });
            console.log('multiSelect', $scope.AdvanceRules[i].RuleGroup[childIndex].selected);
            updateFieldValues(i, childIndex, ruleGroupID, ruleGroupFieldsID, isFromDB);//SL USE CHILDINDEX INSTEAD OF 0
            //updateFieldValues(i, 0);
        } else {// String
            //$scope.AdvanceRules[i].RuleGroup[0].FieldValues.push({ 'FieldValue': fieldValue[0].FieldValue, 'IsMultiple' : false});
            $scope.AdvanceRules[i].RuleGroup[0].FieldValues[0].FieldValue = fieldValue[0].FieldValue;
            $scope.AdvanceRules[i].RuleGroup[0].FieldValues[0].IsFromDB = fieldValue[0].IsFromDB;
            $scope.AdvanceRules[i].RuleGroup[0].FieldValues[0].ViewRuleGroupFieldsID = fieldValue[0].ViewRuleGroupFieldsID;
            $scope.AdvanceRules[i].RuleGroup[0].FieldValues[0].ViewRuleGroupID = ruleGroupID;
        }
        AdvanceRulesService.updateItem($scope.AdvanceRules);
        console.log($scope.AdvanceRules);
    };

    vm.fieldOnChange = function (parentRuleIndex, childRuleIndex, id) {

        if (id == null || id == undefined) {
            vm.OperatorOptions[childRuleIndex] = [];
            vm.FieldType[childRuleIndex] = 12;
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldEnabled = false;
            return false;
        }
        var fieldMappingOptions = $scope.fieldMappingOptionsNewSeg ? $scope.fieldMappingOptionsNewSeg : vm.FieldMappingOptions;

        // Find selected Field mapping object
        var selectedObjList = $filter('filter')(fieldMappingOptions, {
            FieldMappingID: id
        }, true);
        var selectedObj = selectedObjList[0];
        var fieldOps = $filter('filter')(vm.FieldOperatorOptions, {
            LookupParamSysID: selectedObj.FieldType
        });
        if (selectedObj.FieldType == '15') {
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues = [];
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldEnabled = false;
            vm.multiSelect.selected = [];
        }
        else
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues = [{
                'FieldValue': '', 'IsMultiple': false
            }];

        $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldType = selectedObj.FieldType;
        $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldMapping = selectedObj.FieldMapping;
        $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].IsInnerJoin = selectedObj.IsInnerJoin;

        // Assign field operators
        if (fieldOps.length != 0) {
            // Populate drop down value
            if (selectedObj.FieldType == '15' && selectedObj.FieldMappingRef != undefined) //&& selectedObj.FieldMappingRef.toLowerCase() == 'ref_lookupparam'
            {
                var optionsKey = selectedObj.FieldMappingRefCode + 'Options';
                $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].ValueOptions = vm[optionsKey];
            }
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].OperatorOptions = fieldOps;

            if (vm.OperatorOptions.length == parentRuleIndex) {
                console.log('Operator options spliced');
                vm.OperatorOptions.splice(parentRuleIndex, 0, fieldOps);
                vm.FieldType.splice(parentRuleIndex, 0, selectedObj.FieldType);
            }
            else {
                vm.OperatorOptions[parentRuleIndex] = fieldOps;
                vm.FieldType[parentRuleIndex] = selectedObj.FieldType;
            }
        }
        else {
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].OperatorOptions = [];
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].ValueOption = [];
            vm.OperatorOptions = [{
            }];
        }

        AdvanceRulesService.updateItem($scope.AdvanceRules);
        console.log('field on change', $scope.AdvanceRules);
    };


    function setSequence(obj, i) {
        if (obj.length >= i) {
            // Increment sequence
            for (var idx = i; idx < obj.length; idx++) {
                var objRule = obj[idx];
                if (objRule != undefined) {
                    objRule.Sequence = idx + 1;
                }
            }
        }
    }

    function checkOperatorIsMultiple(selectedRules) {
        var isMultipleInd = false;
        if (selectedRules.FieldType == 15) { // dropdown scenario
            if (selectedRules.FieldOperator != 0) {
                var fieldOps = $filter('filter')(vm.FieldOperatorOptions, {
                    DataTypeID: selectedRules.FieldOperator
                });
                console.log("Check Is Multiple", fieldOps);
                if (fieldOps != undefined && fieldOps.length > 0) {
                    isMultipleInd = fieldOps[0].IsMultiple;
                    console.log(isMultipleInd);
                }
            }
        }
        return isMultipleInd;
    }
    function updateFieldValues(parentRuleIndex, childRuleIndex, ruleGroupID, ruleGroupFieldsID, isFromDB) {
        var selectedRules = $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex];
        if (selectedRules != undefined) {
            var selectedFieldValues = selectedRules.FieldValues;
            // Clear array before any actions taken
            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues = [];
            var isMultipleInd = checkOperatorIsMultiple(selectedRules);
            var intFieldCount = 0;
            // Loop through item to add value
            for (var i = 0; i < $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].selected.length; i++) {//SL edited in changeset 4567
                var FieldValue = $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].selected[i];

                if (angular.isArray(FieldValue)) {
                    var dbRuleGroupFieldsID = FieldValue[0];
                    FieldValue = FieldValue[1];
                    $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].selected[i] = FieldValue;
                }
                ruleGroupFieldsID = (dbRuleGroupFieldsID != undefined && dbRuleGroupFieldsID != null) ? dbRuleGroupFieldsID : (++intFieldCount) * -1;
                isFromDB = (isFromDB != undefined && isFromDB != null) ? isFromDB : 0;
                ruleGroupID = (ruleGroupID != undefined && ruleGroupID != null) ? ruleGroupID : $scope.ruleGroupID;

                $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues
                    .push({ 'ViewRuleGroupFieldsID': ruleGroupFieldsID, 'ViewRuleGroupID': ruleGroupID, 'FieldValue': FieldValue, 'IsFromDB': isFromDB });
            };
            AdvanceRulesService.updateItem($scope.AdvanceRules);
            console.log("updateFieldValues", $scope.AdvanceRules);
        }
    }

    //function updateFieldValues(parentRuleIndex, childRuleIndex) {
    //    var selectedRules = $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex];
    //    if (selectedRules != undefined) {
    //        var selectedFieldValues = selectedRules.FieldValues;
    //        // Clear array before any actions taken
    //        $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues = [];
    //        var isMultipleInd = checkOperatorIsMultiple(selectedRules);
    //        // Loop through item to add value
    //        angular.forEach($scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].selected, function (value, key) {

    //            var ruleGroupFieldsID = $scope.ruleGroupFieldsID;
    //            var isFromDB = $scope.isFromDB;
    //            var ruleGroupID = $scope.ruleGroupID;

    //            $scope.AdvanceRules[parentRuleIndex].RuleGroup[childRuleIndex].FieldValues
    //                .push({
    //                    'ViewRuleGroupFieldsID': ruleGroupFieldsID, 'ViewRuleGroupID': ruleGroupID, 'FieldValue': value, 'IsFromDB': isFromDB
    //                });
    //        });
    //        AdvanceRulesService.updateItem($scope.AdvanceRules);
    //        console.log("updateFieldValues", $scope.AdvanceRules);
    //    }
    //}
    /**Functions used to populate advanced rules when save as new segmentise from Outbound Listing - END**/

    function populateJenisKempenforAdvancedRules(isConvertToAdvance) {
        $scope.AdvanceRules = [];
        AdvanceRulesService.updateItem($scope.AdvanceRules);

        //var advRule = AdvanceRulesService.getList();

        //if (advRule.length > 0) {
        //    if (advRule.length > 1)
        //        if ($scope.jenisKempenID == advRule[0].RuleGroup[0].FieldValues[0].FieldValue)
        //            return;
        //    if ($scope.jenisKempenID != advRule[0].RuleGroup[0].FieldValues[0].FieldValue)
        //        clearAdvRule();
        //}

        //$scope.tableType = 5;
        $scope.rulesIndex = -1;
        $scope.rulesType = 1;
        $scope.groupingOperator = '';
        $scope.IsRefreshFieldMapping = true;
        if (!vm.viewID || !vm.isFirstLoadBasicRules || vm.isSaveBasic) {
            //if ($scope.jenisKempenID && (!vm.newSegViewID && !vm.advancedFilter)) {
            AdvanceRulesService.setAllowRemove(false);
            $scope.rulesFieldMapping = "JenisKempenID";
            $scope.rulesIndex = $scope.rulesIndex + 1;
            $scope.rulesOperator = 1;
            $scope.rulefieldType = 15;
            $scope.rulefieldOperator = "IN";
            $scope.rulesFieldValue = [{
                "FieldValue": $scope.jenisKempenID
            }];
            $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            // $scope.$apply();
            //}
        }
    };

    function clearAdvRule() {
        $scope.AdvanceRules = [];
        AdvanceRulesService.updateItem($scope.AdvanceRules);
    };

    function populateBasicRules() {
        //$scope.tableType = 5;
        $scope.AdvanceRules = [];
        $scope.rulesIndex = -1;

        // Populate advance rules from saved view
        if ($scope.AdvancedRulesDB) {
            if (vm.seg.IsBasicMode) {
                console.log('Populate basic', $scope.AdvancedRulesDB);
                angular.forEach($scope.AdvancedRulesDB, function (rules, key) {

                    if (rules.RuleGroup[0].FieldMapping == 'ASSESSMENT_YEAR')
                        vm.tahunTaksiran = rules.RuleGroup[0].FieldValues[0].FieldValue;

                    if (rules.RuleGroup[0].FieldMapping == 'TAXTYPE_CODE')
                        vm.jenisCukai = rules.RuleGroup[0].FieldValues[0].FieldValue;

                    if (rules.RuleGroup[0].FieldMapping == 'TAX_PAYER_NAME1' || rules.RuleGroup[0].FieldMapping == 'Name' || rules.RuleGroup[0].FieldMapping == 'NamaPembayarCukai')
                        vm.nama = rules.RuleGroup[0].FieldValues[0].FieldValue;

                    if (rules.RuleGroup[0].FieldMapping == 'NoRujukanCukai') {
                        vm.rujukanNo = rules.RuleGroup[0].FieldValues[0].FieldValue;
                        vm.isExact = false;
                        if (rules.RuleGroup[0].FieldOperator == "=")
                            vm.isExact = true;
                    }

                    if (rules.RuleGroup[0].FieldMapping == 'TP_IDType')
                        vm.jenisPengenalan = rules.RuleGroup[0].FieldValues[0].FieldValue;

                    if (rules.RuleGroup[0].FieldMapping == 'TP_IDNumber')
                        vm.noPengenalan = rules.RuleGroup[0].FieldValues[0].FieldValue;

                    if (rules.RuleGroup[0].FieldMapping == 'EmailBatchRefNo' || rules.RuleGroup[0].FieldMapping == 'BatchRefNo')
                        vm.batchRefNo = rules.RuleGroup[0].FieldValues[0].FieldValue;

                    if (rules.RuleGroup[0].FieldMapping == 'REMS_DATE' || rules.RuleGroup[0].FieldMapping == 'REMS_DATE') {
                        if (rules.RuleGroup[0].FieldOperator == ">=") {
                            vm.reMSDateFrom = new Date(rules.RuleGroup[0].FieldValues[0].FieldValue);
                        }
                        else {
                            vm.reMSDateTo = new Date(rules.RuleGroup[0].FieldValues[0].FieldValue);
                        }
                    }

                    if (rules.RuleGroup[0].FieldMapping == 'CreatedDateTime' || rules.RuleGroup[0].FieldMapping == 'CreatedDateTime') {
                        if (rules.RuleGroup[0].FieldOperator == ">=") {
                            vm.importedDateFrom = new Date(rules.RuleGroup[0].FieldValues[0].FieldValue);
                        }
                        else {
                            vm.importedDateTo = new Date(rules.RuleGroup[0].FieldValues[0].FieldValue);
                        }
                    }

                    //if (rules.RuleGroup[0].FieldMapping == 'StatusID')
                    //    vm.outboundStatusID = rules.RuleGroup[0].FieldValues[0].FieldValue;
                });
            }

            if (!vm.seg.IsBasicMode) {
                console.log('Populate advanced', $scope.AdvancedRulesDB);
                angular.forEach($scope.AdvancedRulesDB, function (rules, key) {

                    $scope.rulesIndex = $scope.rulesIndex + 1;
                    $scope.rulesType = rules.RuleType;
                    $scope.groupingOperator = rules.GroupingOperator;
                    $scope.rulesOperator = rules.RuleOperator;
                    $scope.rulesOperator = rules.RuleOperator;

                    $scope.ruleID = rules.ViewRuleID;
                    $scope.isFromDB = rules.IsFromDB;

                    //Loop through rules group
                    angular.forEach(rules.RuleGroup, function (rulesGroupItem, key) {

                        if (rules.RuleGroup[0].FieldMapping) {
                            $scope.rulesFieldMapping = rulesGroupItem.FieldMapping;
                            if (rules.RuleGroup[0].FieldMapping == 'JenisKempenID') {
                                AdvanceRulesService.setAllowRemove(false);
                            } else {
                                AdvanceRulesService.setAllowRemove(true);
                            }
                        }
                        else {
                            $scope.rulesFieldMapping = '';
                        }
                        $scope.rulefieldType = rulesGroupItem.FieldType;
                        // TODO: To handle multiple scenario
                        $scope.rulefieldOperator = rulesGroupItem.FieldOperator;
                        //$scope.rulesFieldValue = [{
                        //    "FieldValue": rules.RuleGroup[0].FieldValues[0].FieldValue
                        //}];

                        //$scope.rulesFieldValue = [{ "FieldValue": rules.RuleGroup[0].FieldValues[0].FieldValue }];
                        $scope.rulesFieldValue = rulesGroupItem.FieldValues;

                        $scope.ruleGroupID = rulesGroupItem.ViewRuleGroupID;
                        $scope.ruleGroupFieldsID = rulesGroupItem.FieldValues[0].ViewRuleGroupFieldsID;


                        $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
                    });
                });
            }
            console.log('After Populate advanced', AdvanceRulesService.getList());
            $scope.AdvancedRulesDB = null;
            vm.dtInstanceTPSearchSavedView.reloadData();
        }

        $scope.ruleID = -1
        // Populate advance rules from outbound listing - advanced view
        if (vm.advancedFilter) {
            console.log('From New Segmentise ', vm.advancedFilter);

            AdvanceRulesService.resetDisplaySetting();
            $scope.ruleID = -1;
            AdvanceRulesService.setDynamicDisplayInd(true);
            console.log('Populate New Segmentise', vm.advancedFilter);
            angular.forEach(vm.advancedFilter.AdvancedRules, function (rules, key) {
                $scope.ruleID = rules.ViewRuleID;
                $scope.ruleGroupID = rules.RuleGroup[0].ViewRuleGroupID;
                // $scope.ruleGroupFieldsID = rules.RuleGroup[0].FieldValues[0].ViewRuleGroupFieldsID;
                $scope.isFromDB = rules.IsFromDB;

                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.rulesType = rules.RuleType;
                $scope.groupingOperator = rules.GroupingOperator;
                $scope.rulesOperator = rules.RuleOperator;

                //Loop through rules group
                angular.forEach(rules.RuleGroup, function (rulesGroupItem, key) {
                    $scope.ruleGroupsIndex = $scope.ruleGroupsIndex + 1; //sl added
                    if (rules.RuleGroup[0].FieldMapping) {
                        $scope.rulesFieldMapping = rulesGroupItem.FieldMapping;
                        if (rulesGroupItem.FieldMapping == 'JenisKempenID') {
                            AdvanceRulesService.setAllowRemove(false);
                        } else {
                            AdvanceRulesService.setAllowRemove(true);
                        }
                    }
                    else {
                        $scope.rulesFieldMapping = '';
                    }
                    $scope.rulefieldType = rulesGroupItem.FieldType;
                    // TODO: To handle multiple scenario
                    $scope.rulefieldOperator = rulesGroupItem.FieldOperatorCode;
                    //$scope.rulesFieldValue = [{
                    //    "FieldValue": rules.RuleGroup[0].FieldValues[0].FieldValue
                    //}];

                    //$scope.rulesFieldValue = [{ "FieldValue": rules.RuleGroup[0].FieldValues[0].FieldValue }];
                    $scope.rulesFieldValue = rulesGroupItem.FieldValues;

                    $scope.ruleGroupID = rulesGroupItem.ViewRuleGroupID;
                    //$scope.ruleGroupFieldsID = rulesGroupItem.FieldValues[0].ViewRuleGroupFieldsID;
                    $scope.isFromDB = rules.IsFromDB;

                    $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
                });
            });
            //angular.forEach(vm.advancedFilter.AdvancedRules, function (rules, key) {
            //    setTimeout(function () {
            //        $scope.rulesIndex = $scope.rulesIndex + 1;
            //        $scope.ruleID = -1 * $scope.rulesIndex;
            //        $scope.rulesType = rules.RuleType;
            //        $scope.groupingOperator = rules.GroupingOperator;
            //        $scope.rulesOperator = rules.RuleOperator;
            //        $scope.rulesOperator = rules.RuleOperator;
            //        if (rules.RuleGroup[0].FieldMapping) {
            //            $scope.rulesFieldMapping = rules.RuleGroup[0].FieldMapping;
            //            if (rules.RuleGroup[0].FieldMapping == 'JenisKempenID') {
            //                AdvanceRulesService.setAllowRemove(false);
            //            } else {
            //                AdvanceRulesService.setAllowRemove(true);
            //            }
            //        }
            //        else {
            //            $scope.rulesFieldMapping = '';
            //        }
            //        $scope.rulefieldType = rules.RuleGroup[0].FieldType;
            //        // TODO: To handle multiple scenario
            //        $scope.rulefieldOperator = rules.RuleGroup[0].FieldOperatorCode;
            //        //$scope.rulesFieldValue = [{
            //        //    "FieldValue": rules.RuleGroup[0].FieldValues[0].FieldValue
            //        //}];
            //        $scope.rulesFieldValue = rules.RuleGroup[0].FieldValues;

            //        //$scope.rulesFieldValue = [{ "FieldValue": rules.RuleGroup[0].FieldValues[0].FieldValue }];
            //        $scope.ruleID = rules.ViewRuleID;
            //        $scope.ruleGroupID = rules.RuleGroup[0].ViewRuleGroupID;
            //        $scope.ruleGroupFieldsID = rules.RuleGroup[0].FieldValues[0].ViewRuleGroupFieldsID;
            //        $scope.isFromDB = rules.IsFromDB;

            //        console.log('$scope.rulefieldType', $scope.rulefieldType);
            //        console.log('$scope.rulefieldOperator', $scope.rulefieldOperator);
            //        $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            //    });
            //    // vm.AddNewRulesFromBasicOrDB(); CHIN TAT
            //});
            AdvanceRulesService.updateItem($scope.AdvanceRules);
            $scope.$broadcast('AdvanceRules', 'REFRESHADVRULES');

        }

        // Populate advance rules from outbound listing - saved view basic
        if ($scope.AdvancedRulesDBNewSeg) {
            console.log('Populate new seg Saved View', $scope.AdvancedRulesDBNewSeg);
            //$scope.ruleID = -1
            angular.forEach($scope.AdvancedRulesDBNewSeg, function (rules, key) {

                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.rulesType = rules.RuleType;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.isFromDB = false;
                $scope.groupingOperator = rules.GroupingOperator;
                $scope.rulesOperator = rules.RuleOperator;
                if (rules.RuleGroup[0].FieldMapping) {
                    $scope.rulesFieldMapping = rules.RuleGroup[0].FieldMapping;
                }
                else {
                    $scope.rulesFieldMapping = '';
                }
                $scope.rulefieldType = rules.RuleGroup[0].FieldType;
                // TODO: To handle multiple scenario
                $scope.rulefieldOperator = rules.RuleGroup[0].FieldOperator;
                //$scope.rulesFieldValue = [{
                //    "FieldValue": rules.RuleGroup[0].FieldValues[0].FieldValue
                //}];
                $scope.rulesFieldValue = rules.RuleGroup[0].FieldValues;
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            });
        }

        //Convert basic to advance rules
        if (!vm.viewID || !vm.isFirstLoadBasicRules || vm.isSaveBasic) {
            $scope.rulesType = 1;
            $scope.groupingOperator = '';

            //$scope.ruleID = -1
            if ($scope.jenisKempenID && (!vm.newSegViewID && !vm.advancedFilter)) {
                //$scope.jenisKempenID = $scope.jenisKempenID;
                AdvanceRulesService.setAllowRemove(false);
                $scope.rulesFieldMapping = "JenisKempenID";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.isFromDB = false;
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 15;
                $scope.rulefieldOperator = "IN";
                $scope.rulesFieldValue = [{
                    "FieldValue": $scope.jenisKempenID
                }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }

            if (vm.tahunTaksiran) {
                $scope.rulesFieldMapping = "ASSESSMENT_YEAR";
                AdvanceRulesService.setAllowRemove(true);
                $scope.isFromDB = false;
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 44;
                $scope.rulefieldOperator = "=";
                $scope.rulesFieldValue = [{
                    "FieldValue": vm.tahunTaksiran
                }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }

            if (vm.jenisCukai) {
                AdvanceRulesService.setAllowRemove(true);
                $scope.rulesFieldMapping = "TAXTYPE_CODE";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.isFromDB = false;
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 12;
                $scope.rulefieldOperator = "=";
                $scope.rulesFieldValue = [{
                    "FieldValue": vm.jenisCukai
                }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }

            if (vm.jenisPengenalan != undefined && vm.jenisPengenalan != 0) {
                AdvanceRulesService.setAllowRemove(true);
                $scope.rulesFieldMapping = "TP_IDType";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.isFromDB = false;
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 15;
                $scope.rulefieldOperator = "IN";
                $scope.rulesFieldValue = [{
                    "FieldValue": vm.jenisPengenalan
                }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }

            if (vm.noPengenalan != undefined && vm.noPengenalan != '') {
                AdvanceRulesService.setAllowRemove(true);
                $scope.rulesFieldMapping = "TP_IDNumber";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.isFromDB = false;
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 12;
                $scope.rulefieldOperator = "=";
                $scope.rulesFieldValue = [{
                    "FieldValue": vm.noPengenalan
                }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }

            if (vm.batchRefNo != undefined && vm.batchRefNo != '') {
                AdvanceRulesService.setAllowRemove(true);
                if (vm.isHCLEmailBlast)
                    $scope.rulesFieldMapping = "EmailBatchRefNo";
                else
                    $scope.rulesFieldMapping = "BatchRefNo";

                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.isFromDB = false;
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 12;
                $scope.rulefieldOperator = "=";
                $scope.rulesFieldValue = [{
                    "FieldValue": vm.batchRefNo
                }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }

            if (vm.nama) {
                AdvanceRulesService.setAllowRemove(true);
                if (vm.isHCLEmailBlast)
                    $scope.rulesFieldMapping = "NamaPembayarCukai";
                else {
                    if ($scope.jenisKempenID == 4 || $scope.jenisKempenID == 11) //CDL,YDL
                        $scope.rulesFieldMapping = "Name";
                    else if (vm.isHCLEmailBlast) {
                        $scope.rulesFieldMapping = "NamaPembayarCukai";
                    }
                    else
                        $scope.rulesFieldMapping = "TAX_PAYER_NAME1";
                }

                $scope.isFromDB = false;
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 12;
                $scope.rulefieldOperator = "%";
                $scope.rulesFieldValue = [{
                    "FieldValue": vm.nama
                }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }

            if (vm.rujukanNo) {
                AdvanceRulesService.setAllowRemove(true);
                $scope.rulesFieldMapping = "NoRujukanCukai";

                $scope.isFromDB = false;
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = $scope.ruleID * $scope.rulesIndex;
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 12;
                if (vm.isExact)
                    $scope.rulefieldOperator = "=";
                else
                    $scope.rulefieldOperator = "%";

                $scope.rulesFieldValue = [{
                    "FieldValue": vm.rujukanNo
                }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }

            if (vm.reMSDateFrom != undefined && vm.reMSDateFrom != '') {
                AdvanceRulesService.setAllowRemove(true);
                $scope.rulesFieldMapping = "REMS_DATE";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.ruleGroupID = -1;
                $scope.ruleGroupFieldsID = -1;
                $scope.isFromDB = false;

                $scope.rulesOperator = 1;
                $scope.rulefieldType = 14;
                $scope.rulefieldOperator = ">=";
                $scope.rulesFieldValue = [{ "FieldValue": vm.reMSDateFrom }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }
            if (vm.reMSDateTo != undefined && vm.reMSDateTo != '') {
                AdvanceRulesService.setAllowRemove(true);
                $scope.rulesFieldMapping = "REMS_DATE";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.ruleGroupID = -1;
                $scope.ruleGroupFieldsID = -1;
                $scope.isFromDB = false;

                $scope.rulesOperator = 1;
                $scope.rulefieldType = 14;
                $scope.rulefieldOperator = "<=";
                $scope.rulesFieldValue = [{ "FieldValue": vm.reMSDateTo }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }
            if (vm.importedDateFrom != undefined && vm.importedDateFrom != '') {
                AdvanceRulesService.setAllowRemove(true);
                $scope.rulesFieldMapping = "CreatedDateTime";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.ruleGroupID = -1;
                $scope.ruleGroupFieldsID = -1;
                $scope.isFromDB = false;

                $scope.rulesOperator = 1;
                $scope.rulefieldType = 14;
                $scope.rulefieldOperator = ">=";
                $scope.rulesFieldValue = [{ "FieldValue": vm.importedDateFrom }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }
            if (vm.importedDateTo != undefined && vm.importedDateTo != '') {
                AdvanceRulesService.setAllowRemove(true);
                $scope.rulesFieldMapping = "CreatedDateTime";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.ruleGroupID = -1;
                $scope.ruleGroupFieldsID = -1;
                $scope.isFromDB = false;

                $scope.rulesOperator = 1;
                $scope.rulefieldType = 14;
                $scope.rulefieldOperator = "<=";
                $scope.rulesFieldValue = [{ "FieldValue": vm.importedDateTo }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }
            //if (vm.outboundStatusID) {
            //    $scope.rulesFieldMapping = "StatusID";

            //    $scope.isFromDB = false;
            //    $scope.rulesIndex = $scope.rulesIndex + 1;
            //    $scope.rulesOperator = 1;
            //    $scope.rulefieldType = 15;
            //    $scope.rulefieldOperator = "=";
            //    $scope.rulesFieldValue = [{
            //        "FieldValue": vm.outboundStatusID
            //    }];
            //    $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            //}
        }
    }

    function clearField() {
        vm.viewID = "";
        //vm.seg.JenisKempenID = "";
        vm.jenisPengenalan = "";
        vm.noPengenalan = "";
        vm.batchRefNo = "";
        vm.nama = "";
        vm.rujukanNo = "";
        vm.isExact = false;
        vm.reMSDateFrom = "";
        vm.reMSDateTo = "";
        vm.importedDateFrom = "";
        vm.importedDateTo = "";
        vm.tahunTaksiran = "";

        if (!vm.SearchAction && vm.isBasicMode) {
            vm.jenisKempenID = "";
        }


        vm.invalidNoPengenalan = false;
        vm.invalidJenisPengenalan = false;
        vm.invalidNamaLength = false;
        vm.invalidsearch = false;
        vm.invalidRujukanNoLength = false;
        $scope.clearAdvanceRules = $scope.clearAdvanceRules + 1;
        // $scope.AdvanceRulesNew = AdvanceRulesService.getDefaultList();
    };


    function initSavedViewTable() {
        var ajaxCallbackSavedView = function (data, callback, settings) {

            // Dynamic display columns
            $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
            vm.isDynamicDisplayColumn = AdvanceRulesService.getDynamicDisplayInd();
            data.IsDynamicDisplayColumn = vm.isDynamicDisplayColumn;
            data.DisplayColumns = vm.isDynamicDisplayColumn ? $scope.displaySetting.DisplayColumns : null;
            data.FieldsSorting = vm.isDynamicDisplayColumn ? $scope.displaySetting.FieldsSorting : null;
            data.ViewID = vm.viewID;
            data.CampaignID = vm.seg.Campaign ? vm.seg.Campaign.CampaignID : "";
            data.JenisPengenalanID = vm.jenisPengenalan;
            data.NoPengenalan = !vm.noPengenalan ? '' : vm.noPengenalan.replace(/\s/g, "");
            data.BatchRefNo = vm.batchRefNo;
            data.Nama = vm.nama;
            data.RujukanNo = vm.rujukanNo;
            data.IsExact = vm.isExact;
            data.JenisKempenID = vm.seg.JenisKempenID;
            data.TahunTaksiran = vm.tahunTaksiran;
            data.ReMSDateFrom = $filter('date')(vm.reMSDateFrom, $scope.DateTimeFormat);
            data.ReMSDateTo = $filter('date')(vm.reMSDateTo, $scope.DateTimeFormat);
            data.ImportedDateFrom = $filter('date')(vm.importedDateFrom, $scope.DateTimeFormat);
            data.ImportedDateTo = $filter('date')(vm.importedDateTo, $scope.DateTimeFormat);
            data.IsAdvancedRules = !vm.isBasicMode;
            data.OutboundStatusID = vm.outboundStatusID;
            data.IsFromSeg = true;
            data.JenisCukai = vm.jenisCukai;

            if (!vm.disableCampaign && !vm.blnHasSchedule) {
                if (!data.IsAdvancedRules)
                    data.SkipSavedRules = true;//not disabled field yet, skip get rules from saved rules.
                if (vm.searchButtonClicked)
                    data.ViewID = 0;
            }

            data.IsHCLEmailBlast = vm.isHCLEmailBlast;
            data.IsReturnCount = true;

            if (vm.isFirstLoadSavedView && vm.viewID) {
                loadDynamicColumns(vm.viewID, vm.seg.JenisKempenID || 0, true);
                console.log('first load');

            }

            if (!vm.isFirstLoadSavedView) {
                console.log('not first load');

                if (vm.viewID > 0) {
                    $scope.broadcastGetRulesEvent();
                }
                if (data.IsAdvancedRules) {
                    data.Rules = AdvanceRulesService.getList();
                    console.log('Search by Advance Rules');
                    console.log(data.Rules);
                    getPagedSearchOutbound(data, callback);
                }
                else {
                    if (vm.searchButtonClicked)
                        if (!vm.viewID)
                            data.ViewID = 0;
                    getPagedSearchOutbound(data, callback);
                }
            }

            vm.isFirstLoadSavedView = false;

            if (vm.isExportExcel) {
                //set selected to undefined
                var dataCopy = angular.copy(data);

                if (!dataCopy.ViewID)
                    dataCopy.ViewID = 0;

                if (!dataCopy.OutboundStatusID)
                    dataCopy.OutboundStatusID = 0;

                if (!dataCopy.CampaignID)
                    dataCopy.CampaignID = 0;

                if (!dataCopy.IsAdvancedView)
                    dataCopy.IsAdvancedView = 0;

                if (!dataCopy.IsDynamicDisplayColumn)
                    dataCopy.IsDynamicDisplayColumn = 0;

                if (dataCopy.Rules) {
                    if (dataCopy.Rules.length > 0) {
                        for (var i = 0; i < dataCopy.Rules.length; i++) {
                            if (dataCopy.Rules[i].GroupingOperator == "")
                                dataCopy.Rules[i].GroupingOperator = 0;

                            if (dataCopy.Rules[i]) {
                                if (dataCopy.Rules[i].RuleGroup.length > 0) {
                                    for (var j = 0; j < dataCopy.Rules[i].RuleGroup.length; j++)
                                        dataCopy.Rules[i].RuleGroup[j].selected = "";
                                }
                            }
                        }
                    }
                }
                angular.element('#strJSON').val(angular.toJson(dataCopy));
                angular.element('#btn-submitExport').click();
            }

            vm.isExportExcel = false;
        }

        vm.dtColumnsTPSearchSavedView = [];

        vm.dtOptionsTPSearchSavedView = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallbackSavedView)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('searching', true)
            .withOption('autoWidth', false)
            .withOption('serverSide', true)
                .withOption('createdRow', function (row, data, dataIndex) {
                    $compile(angular.element(row).contents())($scope);
                })
                .withOption('headerCallback', function (header) {
                    if (!vm.headerCompiled) {
                        // Use this headerCompiled field to only compile header once
                        vm.headerCompiled = false;
                        $compile(angular.element(header).contents())($scope);
                    }
                })
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
    };

    function getPagedSearchOutbound(data, callback) {
        OutboundSI.getPagedSearchOutbound(data).then(function (r) {
            if (r.data) {
                vm.totalDataCount = r.data.recordsTotal;
                vm.countNew = r.data.recordsNew;
                vm.countVerified = r.data.recordsVerified;
                vm.countNewVerified = r.data.recordsNew + r.data.recordsVerified;
                vm.countScheduled = r.data.recordsScheduled;

                callback(r.data);
                console.log('get result1', r.data);
                vm.showBasicTable = true;
                //vm.DataList = r.data.data;
                manualTickSelectedData();
                vm.currentItems = r.data.data;
                //vm.DataList = r.data.data;

                if (!vm.selectAll) // if select all skip clear checkbox
                    clearCheckbox(true);

                if (vm.selectAll && vm.searchButtonClicked) // if select all but search button click, clear check box
                    clearCheckbox();

                if (vm.selectAll)  // if select all but not from search action, e.g sorting
                    vm.selectAllfunc(true);

                vm.searchButtonClicked = false;
            }
        });
    }

    function assignModel() {
        var model = {
        }
        model.ViewID = vm.viewID;
        model.JenisPengenalanID = vm.jenisPengenalan;
        model.NoPengenalan = vm.noPengenalan;
        model.BatchRefNo = vm.batchRefNo;
        model.Nama = vm.nama;
        model.RujukanNo = vm.rujukanNo;
        model.IsExact = vm.isExact;
        model.JenisKempenID = vm.seg.JenisKempenID;
        model.TahunTaksiran = vm.tahunTaksiran;
        model.ReMSDateFrom = vm.reMSDateFrom;
        model.ReMSDateTo = vm.reMSDateTo;
        model.ImportedDateFrom = vm.importedDateFrom;
        model.ImportedDateTo = vm.importedDateTo;
        model.IsAdvancedRules = !vm.isBasicMode;
        model.OutboundStatusID = vm.outboundStatusID;
        model.Rules = AdvanceRulesService.getList();
        model.IsFromSeg = true;
        model.JenisCukai = vm.jenisCukai;

        if (!vm.disableCampaign && !vm.blnHasSchedule) {
            if (!model.IsAdvancedRules) {
                model.SkipSavedRules = true;//not disabled field yet, skip get rules from saved rules.
            }
            model.ViewID = 0;

        }

        return model;
    }

    //Toggle Require Verification Option
    vm.toggleRequireVerificationOption = function () {

        //vm.dtInstanceTPSearchSavedView.reloadData();
        //vm.selectAll = false;
        //vm.selectPage = false;
        //vm.disabledChkbox = false;

        if (vm.viewID && !vm.seg.IsRequireVerification) {
            swal({
                title: "Are you sure to uncheck this option? This will run campaign for both new and verified data.",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Ya",
                cancelButtonText: "Tidak",
                closeOnConfirm: false,
                closeOnCancel: false,
                showLoaderOnConfirm: true
            }, function (isConfirm) {
                if (!isConfirm)
                    angular.element('#chkboxRequireVerification').click();
                swal.close();
            });
        }
    };



    //DropDown Change
    vm.kategori1Change = function (selectedKategori1ID) {
        console.log('test'); 
        vm.SubKategoriOptions = [];
        //vm.kategori3Disabled = false;
        selectedKategori1ID = selectedKategori1ID == undefined ? null : selectedKategori1ID;
        var m = $filter('filter')(vm.MainKategoriOptions, {
            Kategori1ID: selectedKategori1ID
        }, true);
        if (m && (m.length > 0)) {
            vm.SubKategoriOptions = m[0].SubKategori;
            vm.campaign.Kategori1Name = m[0].Kategori1Name;
            vm.kategori2Disabled = m[0].SubKategori.length > 0 ? false : true;
            if (vm.kategori2Disabled) {
                vm.kategori3Disabled = true;
                vm.InnerSubKategoriOptions = {
                };
            }
        }
        else {
            vm.campaign.Kategori1Name = "";
        }

    }

    vm.kategori2Change = function (selectedKategori1ID) {
        vm.InnerSubKategoriOptions = [];

        var m = $filter('filter')(vm.SubKategoriOptions, {
            Kategori2ID: selectedKategori1ID
        }, true);
        if (m && (m.length > 0)) {
            vm.InnerSubKategoriOptions = m[0].InnerSubKategori;
            vm.campaign.Kategori2Name = m[0].Kategori2Name;
            vm.kategori3Disabled = m[0].InnerSubKategori.length > 0 ? false : true;
        }
        else {
            vm.campaign.Kategori2Name = "";
        }

    }

    vm.kategori3Change = function (selectedKategori3ID) {
        selectedKategori3ID = selectedKategori3ID == undefined ? null : selectedKategori3ID;
        var m = $filter('filter')(vm.InnerSubKategoriOptions, {
            Kategori3ID: selectedKategori3ID
        }, true);
        if (m && (m.length > 0)) {
            vm.campaign.Kategori3Name = m[0].Kategori3Name;
        }
        else {
            vm.campaign.Kategori3Name = "";
        }

    }

    //Redirect
    vm.redirectTo = function (url) {
        $window.beforeUnloadCanceled = true;
        $window.location.href = url;
    }

    //Lock/Release Segmentise Data
    vm.lockData = function (segFieldForm, jenisKempenForm) {
        //if (!checkFieldChanges(segFieldForm, jenisKempenForm)) {
        //    return;
        //}

        swal({
            title: "Are you sure you want to lock all available data to Segmentise?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                var outboundFilter = assignModel();
                var model = {
                    OutboundSchedule: vm.schedule,
                    OutboundCampaign: vm.campaign,
                    OutboundFilter: outboundFilter,
                    IsRequireVerification: vm.seg.IsRequireVerification,
                    IsHCLEmailBlast: vm.isHCLEmailBlast
                }

                OutboundSI.lockSegmentiseData(model).then(function (r) {
                    if (r.data) {
                        var count = r.data;
                        swal({
                            title: "Segmentise Data Locked!",
                            text: count + " data locked to Segmentise successfully.",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: true
                        });
                    }
                    else {
                        swal({
                            title: "Batal!",
                            text: "No available data to be locked to this Segmentise.",
                            type: "error",
                            showConfirmButton: true
                        });
                    }
                    vm.dtInstanceTPSearchSavedView.reloadData();
                    tabAction("01");

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

    vm.releaseData = function (segFieldForm, jenisKempenForm) {
        //if (!checkFieldChanges(segFieldForm, jenisKempenForm)) {
        //    return;
        //}
        swal({
            title: "Are you sure you want to release all data from Segmentise?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                var outboundFilter = assignModel();
                var model = {
                    OutboundSchedule: vm.schedule,
                    OutboundCampaign: vm.campaign,
                    OutboundFilter: outboundFilter,
                    IsHCLEmailBlast: vm.isHCLEmailBlast
                }

                OutboundSI.releaseSegmentiseData(model).then(function (r) {
                    if (r.data) {
                        var count = r.data;
                        swal({
                            title: "Segmentise Data Released!",
                            text: count + " data released from Segmentise successfully.",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: true
                        });
                    }
                    else {
                        swal({
                            title: "Batal!",
                            text: "No data to be released from this Segmentise.",
                            type: "error",
                            timer: 2500,
                            showConfirmButton: true
                        });
                    }
                    vm.dtInstanceTPSearchSavedView.reloadData();
                    tabAction("01");

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

    //Save & Update Segmentise
    vm.saveSegmentise = function (segmentiseForm, isCreateSchedule) {

        var result = null;
        //console.log(segmentiseForm);
        var isDirty = segmentiseForm.$dirty;
        if (segmentiseForm.$valid && validateField()) {
            if (isDirty || vm.CampaignDirty) {

                if (!vm.CreateCampaignCheck) {
                    vm.campaign = null;
                }

                if (isCreateSchedule)
                    result = UpdateOutboundSegmentise(segmentiseForm, true);
                else
                    result = UpdateOutboundSegmentise(segmentiseForm, false);
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
                result = returnResultPromise();
            }

        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
            result = returnResultPromise();
        }

        return result == null ? returnResultPromise() : result;

    }

    vm.duplicateSegmentise = function ($event) {
        vm.jsonStringBasic = undefined;
        vm.jSonStringAdvanced = undefined;

        if (vm.isBasicMode) {
            vm.jsonStringBasic = {
                //jenisKempenID: vm.jenisKempenID,
                jenisCukai: vm.jenisCukai,
                tahunTaksiran: vm.tahunTaksiran,
                jenisPengenalan: vm.jenisPengenalan,
                noPengenalan: vm.noPengenalan,
                batchRefNo: vm.batchRefNo,
                nama: vm.nama,
                rujukanNo: vm.rujukanNo,
                isExact: vm.isExact,
                reMSDateFrom: vm.reMSDateFrom,
                reMSDateTo: vm.reMSDateTo,
                importedDateFrom: vm.importedDateFrom,
                importedDateTo: vm.importedDateTo,
                outboundStatusID: vm.outboundStatusID
            };
        }

        vm.IsAdvancedRules = !vm.isBasicMode;

        if (vm.IsAdvancedRules) {
            $scope.broadcastGetRulesEvent();
            vm.jSonStringAdvanced = { AdvancedRules: [], DisplaySetting: {} }
            vm.jSonStringAdvanced.AdvancedRules = AdvanceRulesService.getList();
            vm.jSonStringAdvanced.DisplaySetting = AdvanceRulesService.getDisplaySetting();
        }

        vm.jsonStringBasic = angular.toJson(vm.jsonStringBasic);
        vm.jSonStringAdvanced = angular.toJson(vm.jSonStringAdvanced);


        angular.element('#newSegViewID').val(vm.viewID);
        angular.element('#newSegJenisKempenID').val($scope.jenisKempenID);
        angular.element('#jSonStringBasic').val(vm.jsonStringBasic)
        angular.element('#jSonStringAdvanced').val(vm.jSonStringAdvanced)

        //Chew 2019-12-04 --to include kempen duplication
        if (vm.CreateCampaignCheck == true) {
            angular.element('#newSegCCCampaignID').val(vm.campaign.CCCampaignID);
            angular.element('#newSegCampaignName').val(vm.campaign.CampaignName);
            angular.element('#newSegInteractionChannelID').val(vm.campaign.InteractionChannelID);
            angular.element('#newSegKategori1ID').val(vm.campaign.Kategori1ID);
            angular.element('#newSegKategori2ID').val(vm.campaign.Kategori2ID);
            angular.element('#newSegKategori3ID').val(vm.campaign.Kategori3ID);
            angular.element('#newSegEmailTemplateID').val(vm.campaign.EmailTemplateID);
            angular.element('#newSegCCFromID').val(vm.campaign.CCFromID);
            vm.CheckCampaignIsOut = 'Yes';
            angular.element('#CheckCampaignExist').val(vm.CheckCampaignIsOut);
        }


        console.log('Save new seg kempen ID', vm.newSegJenisKempenID);

        $event.preventDefault();

        angular.element('#btn-submitnewseg').click();
    }



    vm.deleteSegmentise = function () {
        if (vm.seg.Campaign != null) {
            swal("Gagal!", "Unable to delete this Segmentise because it is tied to a campaign.", "error");
        }
        else {
            swal({
                title: "Adakah anda pasti untuk hapuskan segmen kempen ini?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Ya",
                cancelButtonText: "Tidak",
                closeOnConfirm: false,
                closeOnCancel: false,
                showLoaderOnConfirm: true
            }, function (isConfirm) {
                if (isConfirm) {
                    model = {
                        ViewID: vm.viewID,
                        ChangeStamp: vm.seg.ChangeStamp
                    }
                    if (vm.isHCLEmailBlast) {
                        OutboundSI.deleteEmailBlastSegmentise(model).then(function (r) {
                            if (r.data) {
                                swal({
                                    title: "Segmen Dihapuskan!",
                                    text: "Segmen anda telah berjaya dihapuskan.",
                                    type: "success",
                                    timer: 2500,
                                    showConfirmButton: true
                                }, function () {
                                    vm.redirectTo('/');
                                });
                            } else {
                                swal("Gagal!", "Tindakan untuk hapus segmen tidak dapat dilakukan.", "error");
                            }
                        });
                    }
                    else {
                        OutboundSI.deleteSegmentise(model).then(function (r) {
                            if (r.data) {
                                swal({
                                    title: "Segmen Dihapuskan!",
                                    text: "Segmen anda telah berjaya dihapuskan.",
                                    type: "success",
                                    timer: 2500,
                                    showConfirmButton: true
                                }, function () {
                                    vm.redirectTo('/');
                                });
                            } else {
                                swal("Gagal!", "Tindakan untuk hapus segmen tidak dapat dilakukan.", "error");
                            }
                        });
                    }
                } else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        }

    }


    vm.deleteCampaign = function () {

        //Chew 2019-12-04 --to include kempen duplication
        vm.CheckCampaignIsOut = 'No';
        angular.element('#CheckCampaignExist').val(vm.CheckCampaignIsOut);

        if (vm.seg.Campaign != null) {
            if (vm.seg.IsCampaignStarted) {
                swal("Gagal!", "Tindakan untuk hapus tidak dapat dilakukan kerana kempen telah dijalankan.", "error");
            }
            else if (vm.blnHasSchedule) {
                swal("Gagal!", "Unable to delete because this Campaign is tied to at least one schedule ", "error");
            }
            else {
                swal({
                    title: "Adakah anda pasti untuk hapus kempen ini?",
                    text: "",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonText: "Ya",
                    cancelButtonText: "Tidak",
                    closeOnConfirm: false,
                    closeOnCancel: false,
                    showLoaderOnConfirm: true
                }, function (isConfirm) {
                    if (isConfirm) {
                        model = {
                            ViewID: vm.viewID,
                            ChangeStamp: vm.seg.Campaign.ChangeStamp
                        }
                        if (vm.isHCLEmailBlast) {
                            OutboundSI.deleteEmailBlastCampaign(model).then(function (r) {
                                if (r.data) {
                                    swal({
                                        title: "Kempen Dihapuskan!",
                                        text: "Kempen anda telah berjaya dihapuskan.",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: true
                                    }, function () {
                                        vm.redirectTo('/Outbound/HCLEmailBlastSegmentise/Detail/' + vm.viewID);
                                    });
                                } else {
                                    swal("Gagal!", "Tindakan untuk hapus kempen tidak dapat dilakukan.", "error");
                                }
                            });
                        }
                        else {
                            OutboundSI.deleteCampaign(model).then(function (r) {
                                if (r.data) {
                                    swal({
                                        title: "Kempen Dihapuskan!",
                                        text: "Kempen anda telah berjaya dihapuskan.",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: true
                                    }, function () {
                                        vm.redirectTo('/Outbound/Segmentise/Detail/' + vm.viewID + '?t=' + TabID);
                                    });
                                } else {
                                    swal("Gagal!", "Tindakan untuk hapus kempen tidak dapat dilakukan.", "error");
                                }
                            });
                        }
                    } else {
                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                    }
                });
            }

        }
        else {
            vm.CreateCampaignCheck = false;
            tabAction("01");
        }

    }

    vm.deleteSchedule = function (scheduleid, changestamp) {
        swal({
            title: "Are you sure you want to delete this Schedule?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                model = {
                    ScheduleID: scheduleid,
                    ChangeStamp: changestamp,
                    JenisKempenID: vm.seg.JenisKempenID
                }
                if (vm.isHCLEmailBlast) {
                    OutboundSI.deleteEmailBlastSchedule(model).then(function (r) {
                        if (r.data) {
                            swal({
                                title: "Schedule Deleted!",
                                text: "Your Schedule is deleted successfully.",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: true
                            }, function () {
                                vm.redirectTo('/Outbound/HCLEmailBlastSegmentise/Detail/' + vm.viewID + '?t=' + TabID);
                            });
                        } else {
                            swal("Gagal!", "Tindakan untuk hapus tidak dapat dilakukan kerana kempen telah dijalankan.", "error");
                        }
                    });
                } else {
                    OutboundSI.deleteSchedule(model).then(function (r) {
                        if (r.data) {
                            swal({
                                title: "Schedule Deleted!",
                                text: "Your Schedule is deleted successfully.",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: true
                            }, function () {
                                //vm.dtInstanceOutboundSchedule.reloadData();
                                vm.redirectTo('/Outbound/Segmentise/Detail/' + vm.viewID + '?t=' + TabID);
                            });
                        } else {
                            swal("Gagal!", "Tindakan untuk hapus tidak dapat dilakukan kerana kempen telah dijalankan.", "error");
                        }
                    });
                }
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });

    }


    function UpdateOutboundSegmentise(form, isCreateSchedule) {
        modelAdvRules = {
        };

        if (vm.isBasicMode) {
            vm.isSaveBasic = true;
            vm.convertToAdvance(form);
        }

        modelAdvRules.Rules = AdvanceRulesService.getList();
        //if (modelAdvRules.Rules != undefined && modelAdvRules.Rules != null) {
        //    modelAdvRules.Rules.AdvancedRules.IsDynamicDisplayColumn = AdvanceRulesService.getDynamicDisplayInd()
        //}
        //if (AdvanceRulesService.getDynamicDisplayInd())
        modelAdvRules.DisplaySetting = AdvanceRulesService.getDisplaySetting();
        console.log('Display setting : ', modelAdvRules.DisplaySetting);
        modelAdvRules.PermissionUsers = AdvanceRulesService.getPermissionUser();
        modelAdvRules.PermissionRoles = AdvanceRulesService.getPermissionRole();
        vm.seg.PermissionType = AdvanceRulesService.getPermissionType();
        vm.seg.IsBasicMode = vm.isBasicMode;

        var model = {
            OutboundSegmentise: vm.seg,
            OutboundCampaign: vm.campaign,
            AdvancedRules: modelAdvRules,
            IsHCLEmailBlast: vm.isHCLEmailBlast
        }
        //console.log('Before update :',model);
        //var data = OutboundSI.updateOutboundSegmentise(model);
        //console.log('After update :', model);
        var result = null;
        var deferred = $q.defer();
        deferred.reject('');
        result = deferred.promise;
        OutboundSI.updateOutboundSegmentise(model).then(function (r) {
            deferred.resolve('');
            result = deferred.promise;
            //vm.viewID = r.data.ViewID;
            var newCampaignID = r.data.CampaignID;
            if (isCreateSchedule)
                AddNewSchedule(true, newCampaignID);
            swal({
                //title: GeneralService.SaveMessage.Title,
                //text: GeneralService.SaveMessage.Text,
                title: "Segmen Kempen Dikemaskini!",
                text: "Tindakan mengemaskini Segmen kempen anda telah berjaya.",
                type: "success",
                timer: 2500,
                showConfirmButton: true,
            }, function () {
                if (vm.isHCLEmailBlast)
                    vm.redirectTo('/Outbound/HCLEmailBlastSegmentise/Detail/' + r.data.ViewID + '?t=' + TabID);
                else
                    vm.redirectTo('/Outbound/Segmentise/Detail/' + r.data.ViewID + '?t=' + TabID);
            });

        });
        console.log('After update :', model);
        return result;
    };

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

            if (vm.seg.Campaign)
                data.CampaignID = vm.seg.Campaign.CampaignID;
            //data.CampaignID = 2;

            if (vm.isHCLEmailBlast) {
                OutboundSI.getPagedAllEmailBlastSchedule(data).then(function (r) {
                    callback(r.data);
                    if (r.data.data.length > 0) {
                        vm.blnHasSchedule = true;
                        //AdvanceRulesService.setAllowEdit(false);
                        $scope.DisableAllRules = true; // CT Added
                    }

                    if (vm.viewID && vm.seg.IsBasicMode && vm.blnHasSchedule)
                        vm.hideAdvMode = true;

                });
            } else {
                OutboundSI.getPagedAllOutboundSchedule(data).then(function (r) {
                    callback(r.data);
                    if (r.data.data.length > 0) {
                        vm.blnHasSchedule = true;
                        //AdvanceRulesService.setAllowEdit(false);
                        $scope.DisableAllRules = true; // CT Added
                    }

                    if (vm.viewID && vm.seg.IsBasicMode && vm.blnHasSchedule)
                        vm.hideAdvMode = true;
                });
            }
        }

        //Bind table - start 
        vm.dtColumnsOutboundSchedule = [
                //DTColumnBuilder.newColumn('ID').withTitle('ID'),
        DTColumnBuilder.newColumn('ScheduleID').withTitle('ID Jadual').withOption('width', '10%'),
		DTColumnBuilder.newColumn('ScheduleStartDate').withTitle('Tarikh Mula').renderWith(renderStartDateTime).withOption('width', '25%'),
		DTColumnBuilder.newColumn('ScheduleExpiryDate').withTitle('Tarikh Tamat').renderWith(renderExpiryDateTime).withOption('width', '25%'),
		DTColumnBuilder.newColumn('ScheduleType').withTitle('Jenis').renderWith(function (data, type) {
		    var input = data == 'M' ? 'Manual' : 'Auto';
		    return input;
		}).withOption('width', '10%'),
		DTColumnBuilder.newColumn('IsActive').withTitle('Status').renderWith(function (data, type) {
		    var input = data == 1 ? 'Enabled' : 'Disabled';
		    return input;
		}).withOption('width', '20%'),
		DTColumnBuilder.newColumn('ScheduleID').notSortable().withTitle('').renderWith(function (data) {
		    return '<span ng-if="(segmentise.isManageOutboundCampaignRole && !segmentise.isHCLEmailBlast)|| (segmentise.isManageHCLCampaignRole && segmentise.isHCLEmailBlast)" ><i class="fa fa-pencil" style="cursor:pointer;" title="Kemaskini" ng-click="segmentise.editSchedule(' + data + ',$event)"></i></span>';
		}).withOption('width', '5%'),
		//DTColumnBuilder.newColumn('ScheduleID').withTitle('').renderWith(function (data) {
		//	return '<span><i class="fa fa-trash" style="cursor:pointer;" title="delete" ng-click="segmentise.deleteSchedule(' + data + ')"></i></span>';
			//}).withOption('width', '10%')
		DTColumnBuilder.newColumn('ScheduleID').notSortable().withTitle('').renderWith(renderDeleteFunction).withOption('width', '5%'),
        ];

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

        function renderStartDateTime(data, type, row, meta) {
            return $filter('date')(row.ScheduleStartDate, $scope.DateFormat)
        };

        function renderExpiryDateTime(data, type, row, meta) {
            return $filter('date')(row.ScheduleExpiryDate, $scope.DateFormat)
        };



        function renderDeleteFunction(data, type, row, meta) {
            //var startDate = $filter('date')(row.ScheduleStartDate, 'dd MMM yyyy') + ' ' + moment(row.ScheduleStartTime, 'hh:mm:ss').format('h:mm a');
            return '<span ng-if="(segmentise.isManageOutboundCampaignRole && !segmentise.isHCLEmailBlast)|| (segmentise.isManageHCLCampaignRole && segmentise.isHCLEmailBlast)"><i class="fa fa-trash" style="cursor:pointer;" title="Hapus" clickAndDisable ng-click="segmentise.deleteSchedule(' + row.ScheduleID + ',\'' + row.ChangeStamp + '\')"></i></span>';
            //return '<span><i class="fa fa-trash" style="cursor:pointer;" title="delete" clickAndDisable ng-click="segmentise.deleteSchedule(' + row.ScheduleID + ')"></i></span>';
        }
    };


    vm.editSchedule = function (scheduleid, $event) {
        if (scheduleid > 0) {
            angular.element("#EditAddScheduleButton").text("Kemaskini");
            vm.openDialog($event, '#scheduleModal');

            if (vm.isHCLEmailBlast) {
                OutboundSI.getEmailBlastScheduleByID(scheduleid).then(function (r) {
                    assignScheduleValue(r);
                });
            } else {
                OutboundSI.getOutboundScheduleByID(scheduleid).then(function (r) {
                    assignScheduleValue(r);
                });
            }
        }
        else {
            vm.blndisabledSchedule = false;
            var d = new Date();
            d.setDate(d.getDate() + 1);
            angular.element("#EditAddScheduleButton").text("Tambah");
            vm.schedule = {
            };
            vm.schedule.ScheduleType = 'A';
            vm.schedule.ScheduleStartDate = d;//$filter('date')(d, $scope.DateTimeFormat);
            vm.schedule.IsActive = true;
            vm.schedule.ScheduleExpiryDate = d;// $filter('date')(d, $scope.DateTimeFormat);

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

    };

    function assignScheduleValue(r) {
        vm.schedule = r.data;
        vm.schedule.ScheduleStartDate = new Date(vm.schedule.ScheduleStartDate);//$filter('date')(vm.schedule.ScheduleStartDate, $scope.DateFormat);
        vm.schedule.ScheduleExpiryDate = new Date(vm.schedule.ScheduleExpiryDate); //$filter('date')(vm.schedule.ScheduleExpiryDate, $scope.DateFormat); //moment(vm.schedule.ScheduleExpiryDate, 'DD MMM YYYY').toDate();

        //Validation
        vm.blndisabledSchedule = false;
        //var d = new Date(vm.schedule.ScheduleStartDate + ' ' + vm.schedule.ScheduleStartTime);
        //var dt = new Date();

        if (vm.schedule.HasRun) {

            vm.blndisabledSchedule = true;
        }

    }

    vm.addSchedule = function (segmentiseForm, segFieldForm, jenisKempenForm) {
        //if (!checkFieldChanges(segFieldForm, jenisKempenForm)) {
        //    return;
        //}
        var result = null;

        if (vm.validateSchedule) {
            //if (!vm.viewID || !vm.seg.Campaign) {
            //    swal({
            //        title: "Create Campaign Schedule requires to save segmentise. Are you sure you want to save this segmentise?",
            //        text: "",
            //        type: "warning",
            //        showCancelButton: true,
            //        confirmButtonText: "Ya",
            //        cancelButtonText: "Tidak",
            //        closeOnConfirm: false,
            //        closeOnCancel: false,
            //        //showLoaderOnConfirm: true
            //    }, function (isConfirm) {
            //        if (isConfirm) {
            //            vm.close();
            //            result = vm.saveSegmentise(segmentiseForm, true);
            //            //UpdateOutboundSegmentise(form, true);

            //        } else {
            //            vm.close();
            //            swal("Batal!", "Permohonan telah dibatalkan.", "error");
            //            result = returnResultPromise();
            //        }
            //    });

            //}
            //else {
            result = AddNewSchedule(false, 0);
            //}
        }
        return result == null ? returnResultPromise() : result;

    };

    vm.validateSchedule = function () {
        vm.invalidScheduleType = false;
        vm.invalidExpiryDateTime = false;
        vm.invalidStartDateTime = false;

        if (!vm.schedule.ScheduleType) {
            vm.invalidScheduleType = true;
            return false;
        }

        if (!vm.schedule.ScheduleStartDate) {
            vm.invalidStartDateTime = true;
            return false;
        }

        if (!vm.schedule.ScheduleExpiryDate) {
            vm.invalidExpiryDateTime = true;
            return false;
        }



        return true;
    };


    function checkFieldChanges(segFieldForm, jenisKempenForm, segmentiseForm, isTestingEmail) {
        var result = true;
        if (vm.viewID) {
            var isDirty = false;
            if (!isTestingEmail) {
                if (segFieldForm.IsRequireVerification) {
                    if (segFieldForm.IsRequireVerification.$dirty)
                        isDirty = true;
                }

                if (segmentiseForm.Campaign) {
                    if (segmentiseForm.Campaign.$dirty)
                        isDirty = true;
                }
            }

            if (segmentiseForm.InteractionChannelID) {
                if (segmentiseForm.InteractionChannelID.$dirty)
                    isDirty = true;
            }


            if (segmentiseForm.EmailTemplateID) {
                if (segmentiseForm.EmailTemplateID.$dirty)
                    isDirty = true;
            }

            if (segmentiseForm.CCFromID) {
                if (segmentiseForm.CCFromID.$dirty)
                    isDirty = true;
            }

            if (isDirty) {
                if (isTestingEmail) {
                    swal({
                        title: "Batal!",
                        text: "Perubahan telah dibuat pada kempen. Sila simpan segmen ini sebelum membuat email testing.",
                        type: "error",
                        showConfirmButton: true
                    });
                }
                else {
                    swal({
                        title: "Batal!",
                        text: "Perubahan telah dibuat pada kempen. Sila simpan segmen ini sebelum menjalankan kempen serta merta.",
                        type: "error",
                        showConfirmButton: true
                    });
                }
                result = false;
            }
        }
        return result;
    }


    //run now -> once clicked will update get rems data and insert into outbound, rems data will be updated to schedule
    vm.runNow = function (runNowType, segFieldForm, jenisKempenForm, segmentiseForm) {
        if (!checkFieldChanges(segFieldForm, jenisKempenForm, segmentiseForm)) {
            return;
        }

        //console.log(vm.seg.Campaign.CampaignID);
        swal({
            title: "Adakah anda pasti untuk menjalankan kempen serta merta?",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {

                vm.schedule = {
                };
                var starttime = new Date;
                var endtime = moment().endOf('day');
                vm.schedule.ScheduleStartDate = moment(starttime, 'EEE MMM dd yyyy HH:mm:ss').format('DD MMM YYYY');
                vm.schedule.ScheduleStartTime = moment(starttime, 'EEE MMM dd yyyy HH:mm:ss').format('HH:mm:ss');
                vm.schedule.ScheduleExpiryDate = moment(endtime, 'EEE MMM dd yyyy HH:mm:ss').format('DD MMM YYYY');
                vm.schedule.ScheduleExpiryTime = moment(endtime, 'EEE MMM dd yyyy HH:mm:ss').format('HH:mm:ss');
                vm.schedule.IsActive = true;
                vm.schedule.ScheduleType = runNowType
                vm.schedule.IsRunNow = true;
                //vm.schedule.ScheduleID = 0;
                vm.schedule.CampaignID = vm.seg.Campaign.CampaignID;

                var outboundFilter = assignModel();
                var model = {
                    OutboundSchedule: vm.schedule,
                    OutboundCampaign: vm.campaign,
                    OutboundFilter: outboundFilter,
                    IsRequireVerification: vm.seg.IsRequireVerification,
                    IsHCLEmailBlast: vm.isHCLEmailBlast
                }

                OutboundSI.updateOutboundSchedule(model).then(function (r) {
                    vm.close();

                    swal({
                        title: "Kempen Berjaya Dijalankan!",
                        text: "Please come back later to check campaign status.",
                        type: "success",
                        timer: 2500,
                        showConfirmButton: true
                    }, function () {
                        swal.close();
                        $mdDialog.hide();
                        //vm.dtInstanceOutboundSchedule.reloadData();
                        //vm.dtInstanceTPSearchSavedView.reloadData();
                        if (vm.isHCLEmailBlast)
                            vm.redirectTo('/Outbound/HCLEmailBlastSegmentise/Detail/' + vm.viewID + '?t=' + TabID);
                        else
                            vm.redirectTo('/Outbound/Segmentise/Detail/' + vm.viewID + '?t=' + TabID);
                    });


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


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

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

    function AddNewSchedule(isNewSegmentise, newCampaignID) {
        if (!vm.schedule.IsActive) {
            vm.schedule.IsActive = false;
        };

        //var starttime = vm.startHour + ':' + vm.startMinutes + ' ' + vm.startAmPm
        //vm.schedule.ScheduleStartTime = moment(starttime, 'h:mm a').format('HH:mm:ss');
        //var expirytime = vm.expiryHour + ':' + vm.expiryMinutes + ' ' + vm.expiryAmPm
        //vm.schedule.ScheduleExpiryTime = moment(expirytime, 'h:mm a').format('HH:mm:ss');

        if (newCampaignID && newCampaignID > 0)
            vm.schedule.CampaignID = newCampaignID
        else {
            vm.schedule.CampaignID = vm.seg.Campaign.CampaignID;

        }
        //console.log('schedule', vm.schedule);
        var outboundFilter = assignModel();
        var modelSchedule = angular.copy(vm.schedule);
        modelSchedule.ScheduleStartDate = $filter('date')(modelSchedule.ScheduleStartDate, $scope.DateTimeFormat);
        modelSchedule.ScheduleExpiryDate = $filter('date')(modelSchedule.ScheduleExpiryDate, $scope.DateTimeFormat);

        var model = {
            OutboundSchedule: modelSchedule,
            OutboundCampaign: vm.campaign,
            OutboundFilter: outboundFilter,
            IsRequireVerification: vm.seg.IsRequireVerification,
            IsHCLEmailBlast: vm.isHCLEmailBlast,
        }

        //Validation
        vm.blnValid = true;
        vm.showErrStartDate = false;
        vm.ErrMsgStartDate = "";

        if (vm.schedule.ScheduleStartDate || vm.schedule.ScheduleExpiryDate) {
            var d = new Date(vm.schedule.ScheduleStartDate);
            var dt = new Date(vm.schedule.ScheduleExpiryDate);

            if ((!vm.schedule.ScheduleStartDate && vm.schedule.ScheduleExpiryDate) ||
                (vm.schedule.ScheduleStartDate && !vm.schedule.ScheduleExpiryDate)) {
                vm.ErrMsgStartDate = "Banjaran tarikh tidak sah.";
                vm.showErrStartDate = true;
                vm.blnValid = false;
            }

            if (d > dt) {
                vm.ErrMsgStartDate = "Schedule end date must be greater than start date.  ";
                vm.showErrStartDate = true;
                vm.blnValid = false;
            }
        }

        if (vm.blnValid) {
            var data = OutboundSI.updateOutboundSchedule(model);
            data.then(function (r) {
                vm.close();
                if (!isNewSegmentise || (!newCampaignID || newCampaignID == 0)) {
                    if (vm.schedule.ScheduleID > 0) {
                        swal({
                            title: "Penjadualan Kempen berjaya dikemaskini!",
                            //text: "Penjadualan Kempen berjaya dikemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: true
                        }, function () {
                            swal.close();
                            $mdDialog.hide();
                            vm.dtInstanceOutboundSchedule.reloadData();
                            vm.dtInstanceTPSearchSavedView.reloadData();
                        });
                    }
                    else {
                        swal({
                            title: "Penjadualan Kempen berjaya ditambah!",
                            //text: "Your Schedule is created successfully!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: true
                        }, function () {
                            swal.close();
                            $mdDialog.hide();
                            vm.dtInstanceOutboundSchedule.reloadData();
                            vm.dtInstanceTPSearchSavedView.reloadData();
                        });
                    }
                }
            });
            return data;
        }

    };

    //History
    function getOutboundHistoryListByID() {
        var ajaxCallback = function (data, callback, settings) {
            vm.LoadingHistoryData = true;
            if (vm.seg.Campaign)
                data.CampaignID = vm.seg.Campaign.CampaignID;

            if (vm.isHCLEmailBlast) {
                OutboundSI.getPagedEmailBlastHistoryListByID(data).then(function (r) {
                    if (r.data.data.length > 0) {
                        vm.blnHasSchedule = true;
                        //AdvanceRulesService.setAllowEdit(false);
                        $scope.DisableAllRules = true; // CT Added
                    }
                    callback(r.data);
                    vm.LoadingHistoryData = false;
                });
            }
            else {
                OutboundSI.getPagedOutboundHistoryListByID(data).then(function (r) {
                    if (r.data.data.length > 0) {
                        vm.blnHasSchedule = true;
                        //AdvanceRulesService.setAllowEdit(false);
                        $scope.DisableAllRules = true; // CT Added
                    }
                    callback(r.data);
                    vm.LoadingHistoryData = false;
                });
            }
        }

        //Bind table - start             
        if (vm.isHCLEmailBlast) {
            vm.dtColumnsOutboundHistory = [
                DTColumnBuilder.newColumn('ID').withTitle('No.').notSortable(),
                DTColumnBuilder.newColumn('EmailHisID').withTitle('History Batch ID'),
                DTColumnBuilder.newColumn('ScheduleID').withTitle('ID Jadual').renderWith(renderHistoryLink),
                DTColumnBuilder.newColumn('RunDateTime').withTitle('Tarikh Dijalankan').renderWith(renderDate),
                DTColumnBuilder.newColumn('RunDateTime').withTitle('Masa Dijalankan').renderWith(renderTime),
                DTColumnBuilder.newColumn('TotalRecords').withTitle('Jumlah Rekod'),
		        DTColumnBuilder.newColumn('ScheduleType').withTitle('Jenis').renderWith(function (data, type) {
		            var input = data == 'M' ? 'Manual' : 'Auto';
		            return input;
		        }),
                DTColumnBuilder.newColumn('IsRunNow').withTitle('Dijadualkan/Dijalankan Serta merta').renderWith(function (data, type) {
                    var input = data ? 'Dijalankan Serta merta' : 'Dijadualkan';
                    return input;
                }),
		        DTColumnBuilder.newColumn('IsTestingEmail').withTitle('Testing Email?').renderWith(function (data, type) {
		            var input = data ? 'Ya' : 'Tidak';
		            return input;
		        }),
		        DTColumnBuilder.newColumn('EmailHisID').notSortable().withTitle('').renderWith(function (data, type, row) {
		            var todayDate = new Date(moment().format('MM/DD/YYYY'));
		            todayDate.setDate(todayDate.getDate() - 1);
		            if (new Date($filter('date')(row.RunDateTime, 'MM/dd/yyyy')) >= todayDate)
		                return '<span ng-if="segmentise.isManageHCLCampaignRole && segmentise.isHCLEmailBlast"><i class="fa fa-stop" style="color:orangered;cursor:pointer;" title="Cancel Campaign by Batch" ng-click="segmentise.cancelCampaign(' + data + ',$event)"></i></span>';
		            else
		                return null;
		        }).withOption('width', '5%')
                //DTColumnBuilder.newColumn('EmailHisID').notSortable().withTitle('').renderWith(renderHistoryLink),
            ];
        }
        else {
            vm.dtColumnsOutboundHistory = [
                DTColumnBuilder.newColumn('ID').withTitle('No.').notSortable(),
                DTColumnBuilder.newColumn('OutboundHisID').withTitle('History Batch ID'),
                DTColumnBuilder.newColumn('ScheduleID').withTitle('ID Jadual').renderWith(renderHistoryLink),
                DTColumnBuilder.newColumn('RunDateTime').withTitle('Tarikh Dijalankan').renderWith(renderDate),
                DTColumnBuilder.newColumn('RunDateTime').withTitle('Masa Dijalankan').renderWith(renderTime),
                DTColumnBuilder.newColumn('TotalRecords').withTitle('Jumlah Rekod'),
		        DTColumnBuilder.newColumn('ScheduleType').withTitle('Jenis').renderWith(function (data, type) {
		            var input = data == 'M' ? 'Manual' : 'Auto';
		            return input;
		        }),
                DTColumnBuilder.newColumn('IsRunNow').withTitle('Dijadualkan/Dijalankan Serta merta').renderWith(function (data, type) {
                    var input = data ? 'Dijalankan Serta merta' : 'Dijadualkan';
                    return input;
                }),
		        DTColumnBuilder.newColumn('IsTestingEmail').withTitle('Testing Email?').renderWith(function (data, type) {
		            var input = data ? 'Ya' : 'Tidak';
		            return input;
		        }),
		        DTColumnBuilder.newColumn('OutboundHisID').notSortable().withTitle('').renderWith(function (data, type, row) {
		            var todayDate = new Date(moment().format('MM/DD/YYYY'));
		            todayDate.setDate(todayDate.getDate() - 1);
		            if (new Date($filter('date')(row.RunDateTime, 'MM/dd/yyyy')) >= todayDate)
		                return '<span ng-if="segmentise.isManageOutboundCampaignRole && !segmentise.isHCLEmailBlast"><i class="fa fa-stop" style="color:orangered;cursor:pointer;" title="Cancel Campaign by Batch" ng-click="segmentise.cancelCampaign(' + data + ',$event)"></i></span>';
		            else
		                return null;
		        }).withOption('width', '5%')
                //DTColumnBuilder.newColumn('OutboundHisID').notSortable().withTitle('').renderWith(renderHistoryLink),
            //DTColumnBuilder.newColumn('OutboundHisID').withTitle('').renderWith(function (data) {
                    //    return '<span><i class="fa fa-eye text-blue" style="cursor:pointer;" title="View History"></i></span>';
                    //})"
            ];
        }
        vm.dtOptionsOutboundHistory = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallback)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('searching', true)
            .withOption('serverSide', true)
            .withOption('autoWidth', false)
                        .withOption('createdRow', function (row, data, dataIndex) {
                            $compile(angular.element(row).contents())($scope);
                        })
                .withPaginationType('full_numbers')
            .withDisplayLength(10);
        //Bind Table - end

        function renderDate(data, type, row, meta) {
            return $filter('date')(row.RunDateTime, 'dd MMM yyyy');
        };

        function renderTime(data, type, row, meta) {
            //return row.RunDateTime;
            return moment(row.RunDateTime).format('h:mm a');
        };

        function renderHistoryLink(data, type, row, meta) {
            if (vm.isHCLEmailBlast) {
                return '<a target="_blank" href="/Outbound/HCLEmailBlastHistory/Detail/' + row.EmailHisID + '" target="_blank"><span>' + data + '</span></a>';
            }
            else {
                return '<a target="_blank" href="/Outbound/History/Detail/' + row.OutboundHisID + '" target="_blank"><span>' + data + '</span></a>';
            }
        };


    };

    vm.cancelCampaign = function (outboundHisID, $event) {
        swal({
            title: "Are you sure you want to cancel campaign by batch?",
            text: "Only applicable for status = In Queue and not Testing Email.",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                model = {
                    HisID: outboundHisID,
                    CampaignID: vm.seg.Campaign.CampaignID,
                    JenisKempenID: vm.seg.JenisKempenID,
                    IsHCLEmailBlast: vm.isHCLEmailBlast
                }
                OutboundSI.cancelCampaignByID(model).then(function (r) {
                    if (r.data) {
                        swal({
                            title: "Campaign Cancelled Successfully!",
                            text: r.data + " record(s) cancelled from campaign.",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: true
                        });
                        vm.dtInstanceTPSearchSavedView.reloadData();
                    }
                    else {
                        swal({
                            title: "Batal!",
                            text: "No available records to be cancelled.",
                            type: "error",
                            showConfirmButton: true
                        });
                    }
                });
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });
    };

    //Tab action
    vm.tabAction = tabAction;
    function tabAction(cls) {
        TabID = cls;
        reset();
        switch (cls) {
            case '01':
                tabProfile01Click();
                break;
            case '02':
                tabProfile02Click();
                break;
            case '03':
                tabProfile03Click();
                break;
        }
    }

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

    //Profile Tab 01
    vm.tabProfile01Click = tabProfile01Click;
    function tabProfile01Click() {
        vm.tabProfile01Active = true;
        //$("html, body").animate({
        //    scrollTop: 0
        //}, 400);
    }

    //Profile Tab 02
    vm.tabProfile02Click = tabProfile02Click;
    function tabProfile02Click() {
        vm.tabProfile02Active = true;
        //$("html, body").animate({
        //    scrollTop: 0
        //}, 400);
    }

    //Profile Tab 03
    vm.tabProfile03Click = tabProfile03Click;
    function tabProfile03Click() {
        vm.tabProfile03Active = true;
        //$("html, body").animate({
        //    scrollTop: 0
        //}, 400);
    }

    vm.sendTestingEmail = function (segFieldForm, jenisKempenForm, segmentiseForm) {
        if (!checkFieldChanges(segFieldForm, jenisKempenForm, segmentiseForm, true)) {
            return;
        }

        //if (!vm.selectedDataList.DataList.length && !vm.selectAll) {
        //    swal({
        //        title: "Batal!",
        //        text: "Please select at least one record for email testing.",
        //        type: "error",
        //        showConfirmButton: true
        //    });
        //    return;
        //}

        swal({
            title: "Are you sure to you want to send testing email for selected record(s)?",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                var outboundFilter = assignModel();

                vm.schedule = {
                };
                var starttime = new Date;
                var endtime = moment().endOf('day');
                vm.schedule.ScheduleStartDate = moment(starttime, 'EEE MMM dd yyyy HH:mm:ss').format('DD MMM YYYY');
                vm.schedule.ScheduleStartTime = moment(starttime, 'EEE MMM dd yyyy HH:mm:ss').format('HH:mm:ss');
                vm.schedule.ScheduleExpiryDate = moment(endtime, 'EEE MMM dd yyyy HH:mm:ss').format('DD MMM YYYY');
                vm.schedule.ScheduleExpiryTime = moment(endtime, 'EEE MMM dd yyyy HH:mm:ss').format('HH:mm:ss');
                vm.schedule.IsActive = true;
                vm.schedule.ScheduleType = 'A'
                vm.schedule.IsRunNow = true;
                vm.schedule.CampaignID = vm.seg.Campaign.CampaignID;
                vm.schedule.IsTestingEmail = true;

                model = {
                    DataList: vm.selectedDataList.DataList,
                    IsSelectAll: vm.selectAll,
                    OutboundFilter: outboundFilter,
                    JenisKempenID: $scope.jenisKempenID,
                    CampaignID: vm.campaign.CampaignID,
                    EmailTemplateID: vm.campaign.EmailTemplateID,
                    InteractionChannelID: vm.campaign.InteractionChannelID,
                    Kategori1ID: vm.campaign.Kategori1ID,
                    Kategori2ID: vm.campaign.Kategori2ID,
                    Kategori3ID: vm.campaign.Kategori3ID,
                    Schedule: vm.schedule,
                    ViewID: vm.viewID,
                    IsHCLEmailBlast: vm.isHCLEmailBlast
                }

                OutboundSI.sendTestingEmail(model).then(function (r) {
                    if (r.data) {
                        var email = r.data;
                        swal({
                            title: "Testing Email Sent Successfully To " + email + "!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: true
                        }, function () {
                            if (vm.isHCLEmailBlast)
                                vm.redirectTo('/Outbound/HCLEmailBlastSegmentise/Detail/' + vm.viewID + '?t=' + TabID);
                            else
                                vm.redirectTo('/Outbound/Segmentise/Detail/' + vm.viewID + '?t=' + TabID);
                        });
                    }
                });
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });
    }

    // date picker
    vm.clearDateFrom = function () {
        vm.reMSDateFrom = '';
        vm.reMSDateFrom.$dirty = true;
        vm.reMSDateFrom.$pristine = false;
    };
    vm.clearDateTo = function () {
        vm.reMSDateTo = '';
        vm.reMSDateTo.$dirty = true;
        vm.reMSDateTo.$pristine = false;
    };

    vm.clearImportedDateFrom = function () {
        vm.importedDateFrom = '';
        vm.importedDateFrom.$dirty = true;
        vm.importedDateFrom.$pristine = false;
    };
    vm.clearImportedDateTo = function () {
        vm.importedDateTo = '';
        vm.importedDateTo.$dirty = true;
        vm.importedDateTo.$pristine = false;
    };

    vm.clearScheduleStartDate = function () {
        vm.schedule.ScheduleStartDate = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["SKIM_DATE"].$pristine = false;
        $scope.makReMSForm["SKIM_DATE"].$dirty = true;
    };

    vm.clearScheduleExpiryDate = function () {
        vm.schedule.ScheduleExpiryDate = '';
        $scope.segFieldForm.$dirty = true;
        $scope.segFieldForm["TarikhKenaBayar"].$pristine = false;
        $scope.segFieldForm["TarikhKenaBayar"].$dirty = true;
    };

    function returnResultPromise() {
        var result = null;
        var deferred = $q.defer();
        deferred.reject('');
        result = deferred.promise;
        return result;
    }
    function decodeEntities(encodedString) {
        var textArea = document.createElement('textarea');
        textArea.innerHTML = encodedString;
        return textArea.value;
    }

    function loadDisplaySetting() {
        var viewID = 0;
        var jenisKempenID = 0;
        var tableType = 0;
        if (vm.viewID) viewID = vm.viewID;
        if ($scope.jenisKempenID)
            jenisKempenID = $scope.jenisKempenID;
        else if (vm.seg.JenisKempenID)
            jenisKempenID = vm.seg.JenisKempenID;

        if (vm.isHCLEmailBlast || (jenisKempenID != undefined && jenisKempenID != null && jenisKempenID != 0)) {

            tableType = $scope.tableType;
            GeneralSI.getDisplaySetting(tableType, viewID, jenisKempenID).then(function (r) {
                if (r.status == 200) {
                    $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
                    $scope.displaySetting.DisplayColumns = r.data.DisplayColumns;
                    //if (r.data.FieldsSorting != null && r.data.FieldsSorting && r.data.FieldsSorting.len > 0) $scope.displaySetting.FieldsSorting = r.data.FieldsSorting;
                    $scope.displaySetting.FieldsSorting = AdvanceRulesService.assignFieldsSorting(r.data.FieldsSorting, r.data.DisplayColumns);
                    if ($scope.fieldMappingOptionsNewSeg)
                        vm.FieldMappingOptions = $scope.fieldMappingOptionsNewSeg;
                    $scope.displaySetting.FieldMappings = vm.FieldMappingOptions;
                    AdvanceRulesService.updateDisplaySetting($scope.displaySetting);
                    AdvanceRulesService.setOriDisplaySetting();
                    $scope.$broadcast('AdvanceRules_DisplayColumn', 'INIT');

                }
            });
        }
    }

    vm.exportExcel = function () {
        vm.isExportExcel = true;
        vm.search();
    }
}


