crmApp.controller('OutboundListingController', function ($scope, $mdDialog, $window, AntiForgeryService, $compile, $q, $http, $location, $filter
    , DTOptionsBuilder, DTColumnBuilder, OutboundSI, GeneralSI, AdvanceRulesService, GeneralService, AdminSI, Upload, $timeout) {
    var vm = this;
    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;

    //vm.isFirstLoadBasic = true;
    vm.isFirstLoadReMSBatch = true;
    vm.isFirstLoadSavedView = true;
    vm.furtherFilter = false;

    vm.isBasicMode = true;
    vm.dtInstanceTPSearchSavedView = {};
    vm.dtInstanceSegmentiseList = {};
    vm.dtInstanceReMSBatchList = {};

    vm.isExact = false;
    vm.showBasicTable = false;
    vm.IsShowReMSBatchTab = $window.isShowReMSBatchTab;
    vm.isShowSegTab = $window.isShowSegTab;
    vm.isHCLEmailBlast = $window.isHCLEmailBlast;

    /**Constants**/
    vm.constJenisKempenCDL = 4;
    vm.constJenisKempenYDL = 11;

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

    vm.constAttachmentSizeID = 14;
    /**Constants End **/

    vm.init = function () {

        vm.SearchAction = true;
        if (vm.IsShowReMSBatchTab) {
            tabAction("03");
        }
        else if (vm.isShowSegTab) {
            tabAction("02");
        }
        else {
            tabAction("01", true);
        }
        initDatepicker();
        vm.viewID = 0;
        vm.ShowFilter = true;
        vm.isDynamicDisplayColumn = false;
        if (!vm.isHCLEmailBlast) {
            $scope.tableType = 5;
            vm.isHCLEmailBlast = false;
        } else {

            $scope.tableType = 6;
            loadDisplaySetting();
        }
        $scope.DisablePartialFieldMapping = false;

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

            var m = $filter('filter')(vm.ParameterSettings, { ParameterID: vm.constAttachmentSizeID }, true);
            if (m && (m.length != 0)) {
                vm.constAttachmentSize = m[0].ParameterValue;
            }

            vm.JenisKempenOptionsEmailBlast = angular.copy(vm.JenisKempenOptions);

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

    };

    function initDatepicker() {
        // 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.clear = function () {
        vm.isFromSeg = false;
        //$scope.jenisKempenID = 0;
        vm.showBasicTable = false;
        clearField();
        if (!vm.SearchAction && vm.isBasicMode) {
            vm.viewID = 0;
            vm.jenisKempenID = '';
        }
        else {
            clearCheckbox();
            AdvanceRulesService.setClearEnabledOnly(true);
            $scope.broadcastClearRulesEvent();
        }
        //if (vm.SearchAction && !vm.isBasicMode) {
        //    $scope.broadcastClearRulesEvent();
        //    if (!vm.isBasicMode) {
        //        if (vm.SearchAction) {
        //            vm.furtherFilter = false;
        //        } else {
        //            vm.furtherFilter = true;
        //        }
        //        vm.jenisKempenID = '';
        //    }
        //} else if (!vm.SearchAction && !vm.isBasicMode) {
        //    AdvanceRulesService.setClearEnabledOnly(true);
        //    $scope.broadcastClearRulesEvent();
        //}
    }

    vm.search = function () {
        vm.searchButtonClicked = true;

        if (validateField()) {
            if (vm.isBasicMode) {
                //if (validateField()) {
                //vm.dtInstanceTPSearchSavedView.reloadData();
                vm.showBasicTable = true;
                //$scope.jenisKempenID = vm.jenisKempenID;
                console.log('Basic Jenis Kempen ', $scope.jenisKempenID);
                if (vm.SearchAction)
                    loadDynamicColumns(vm.viewID, $scope.jenisKempenID);
                else
                    loadDynamicColumns(0, $scope.jenisKempenID);
                //}
            }
            else {
                if (vm.SearchAction) {
                    if (GeneralService.validateAdvancedRules(true)) {
                        console.log('Advance Jenis Kempen ', vm.jenisKempenID);
                        vm.showBasicTable = true;
                        loadDynamicColumns(vm.viewID, $scope.jenisKempenID);
                        console.log('Basic', vm.isBasicMode);
                        console.log(AdvanceRulesService.getList());
                    }
                }
                else {
                    {
                        var tableType = $scope.tableType;
                        // Chin Tat
                        //if (vm.isHCLEmailBlast)
                        //    tableType = 6;
                        //else
                        //    tableType = 5;
                        GeneralSI.getAdvancedRulesDetails(vm.viewID, tableType).then(function (r) {
                            console.log('Advance Rules Details', r.data);
                            if (!r.data.IsSystemView)
                                vm.isFromSeg = true;

                            $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);

                            if (vm.isBasicMode) {
                                vm.showBasicTable = vm.isBasicMode;
                                loadDynamicColumns(vm.viewID, $scope.jenisKempenID);
                                //form.$setPristine();
                            }
                            else {
                                if (GeneralService.validateAdvancedRules(true)) {
                                    vm.furtherFilter = true;

                                    $scope.broadcastGetDropDownEvent();
                                    setTimeout(function () {
                                        loadDynamicColumns(vm.viewID, $scope.jenisKempenID);
                                        //Chin Tat : commented code below as it will re populate value from basic filters into advanced rules
                                        //vm.convertToAdvance();
                                    }, 200);
                                }
                                ////vm.promptConvertToAdvancedRules(form);
                            }
                        });
                    }
                }
            }
        }
    }
    //vm.search = function () {
    //    console.log('search');
    //    vm.isSavedViewMode = false;
    //    if (vm.isBasicMode) {
    //        console.log('basic');
    //        if (!vm.SearchAction || validateField()) {
    //            var id = 0;
    //            if (!vm.SearchAction)
    //                id = vm.viewID;

    //            loadDynamicColumns(id);
    //            //vm.dtInstanceTPSearchBasic.reloadData();
    //            vm.showBasicTable = true;
    //        }
    //    }
    //    else {

    //        console.log('advance');
    //        if (validateRules()) {
    //            loadDynamicColumns(vm.viewID);
    //            //vm.isSavedViewMode = false;
    //            //vm.dtInstanceTPSearchBasic.reloadData();
    //            vm.showBasicTable = true;
    //        }

    //    }
    //};



    vm.SearchActionOnChanged = function (form) {
        //form.$setPristine();
        vm.clear();
        vm.isBasicMode = true;

        if (vm.SearchAction) {
            vm.furtherFilter = false;
        } else {
            vm.furtherFilter = true;
        }
        vm.jenisKempenID = '';
    };

    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.jenisKempenID) {
                if (!(vm.isHCLEmailBlast && !vm.SearchAction)) { //email blast, jenis kempen not mandatory in basic search
                    vm.invalidJenisKempen = true;
                    isValid = false;
                }
            }

        }
        //else if (vm.viewID > 0) {
        if (vm.isBasicMode) {
            // 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;
                }

            }

            isValid = validateDateRangeControl(isValid);
        }

        return isValid;
    };

    function validateDateRangeControl(isValid) {

        if (!vm.isHCLEmailBlast) {
            if ((vm.reMSDateFrom && vm.reMSDateFrom != undefined && vm.reMSDateFrom != '') || (vm.reMSDateTo && vm.reMSDateTo != undefined && 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.importedDateFrom != undefined && vm.importedDateFrom != '') || (vm.importedDateTo && vm.importedDateTo != undefined && 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 (form) {
        if (validateDateRangeControl(true)) {
            swal({
                title: "Confirmation",
                text: "Do you want to convert basic filters into advanced rules? This may replace the existing advanced rules.",
                type: "warning",
                showCancelButton: true,
                confirmButtonClass: "btn-danger",
                confirmButtonText: "Ya",
                cancelButtonText: "Tidak",
                closeOnConfirm: true
            },
                function (isConfirm) {
                    vm.furtherFilter = true;
                    vm.isBasicMode = false;
                    setAdvancedFilterTitle();
                    if (isConfirm) {
                        vm.convertToAdvance();
                        form.$setPristine();
                        $scope.$apply();
                    }
                    else {
                        //if (vm.isBasicMode) vm.isBasicMode = true;
                        populateJenisKempenforAdvancedRules();
                        $scope.$apply();
                        //form.$setPristine();
                    }

                });
        }
    }

    vm.toggleSearchMode = function (outboundListForm) {
        var isDirty = outboundListForm.$dirty;
        if (validateField()) {
            if (vm.isBasicMode) {
                if (isDirty) {
                    vm.promptConvertToAdvancedRules(outboundListForm);
                    //reset form pristine, so that rules only converted when dirty
                    //outboundListForm.$setPristine();
                } else {
                    vm.isBasicMode = false;
                    setAdvancedFilterTitle();
                }
                //vm.furtherFilter = true;

                loadDisplaySetting();
            }
            else {
                AdvanceRulesService.resetDisplaySetting();

                setBasicFilterTitle();
                vm.isBasicMode = true;
                if (vm.SearchAction) {
                    if (!vm.furtherFilter)
                        vm.furtherFilter = false;
                } else {
                    vm.furtherFilter = true;
                }
            }

        };
    }

    function setBasicFilterTitle() {
        vm.sectionTitle = "Saringan Asas";
    }

    function setAdvancedFilterTitle() {
        vm.sectionTitle = "Saringan Terperinci";
    }

    vm.toggleSavedViewOptions = function (form) {
        $scope.jenisKempenID = 0;
        //clearField();
        $scope.AdvancedRulesDB = [];

        vm.isFromSeg = false;

        var a = $filter('filter')(vm.OutboundViewOptions, { ViewID: vm.viewID }, true);
        if (a.length != 0) {
            if (a[0].ViewType == "Segmented View")
                vm.isFromSeg = true;
        }

        console.log(vm.viewID);
        console.log(vm.OutboundViewOptions);
        var selectedSavedView = $filter('filter')(vm.OutboundViewOptions, { ViewID: vm.viewID }, true);
        if (selectedSavedView != undefined) {
            $scope.jenisKempenID = selectedSavedView[0].JenisKempenID;
            vm.jenisKempenID = $scope.jenisKempenID;
        }
        console.log('Jenis Kempen ID', $scope.jenisKempenID);

        if (vm.SearchAction) {
            vm.toggleJenisKempenOptions();
        }

        //default view
        if (vm.viewID == "" || vm.viewID == null) {
            vm.viewID = "";
            vm.showBasicTable = false;
            //vm.isBasicMode = true;

            $scope.broadcastGetDropDownEvent();
            $scope.broadcastClearRulesEvent();
        }
        else {
            var tableType = $scope.tableType;
            //if (vm.isHCLEmailBlast)
            //    tableType = 6;
            //else
            //    tableType = 5;
            GeneralSI.getAdvancedRulesDetails(vm.viewID, tableType).then(function (r) {
                console.log('Advance Rules Details', r.data);
                if (!r.data.IsSystemView)
                    vm.IsFromSeg = true;

                $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.$broadcast('AdvanceRules_DisplayColumn', 'INIT');

                //$scope.AdvancedRulesDisplayColumns = r.data.DisplayColumns;

                if (vm.isBasicMode) {
                    //vm.showBasicTable = vm.isBasicMode;
                    //loadDynamicColumns(vm.viewID, $scope.jenisKempenID);
                    //form.$setPristine();
                }
                else {
                    vm.furtherFilter = true;

                    $scope.broadcastGetDropDownEvent();
                    setTimeout(function () {
                        //loadDynamicColumns(vm.viewID, $scope.jenisKempenID);
                        vm.convertToAdvance();
                    }, 200);

                    //vm.promptConvertToAdvancedRules(form);
                }
            });

        }
    };

    vm.toggleJenisKempenOptions = function () {
        //default view

        if (vm.jenisKempenID == "" || vm.jenisKempenID == null) {
            vm.jenisKempenID = 0;

            $scope.jenisKempenID = vm.jenisKempenID;
            $scope.broadcastClearRulesEvent();
        }
        else {
            $scope.jenisKempenID = vm.jenisKempenID;
            console.log('Toggle Jenis Kempen ID', vm.jenisKempenID);
        }
        //Chin Tat
        // $scope.broadcastGetDropDownEvent();
        if (!vm.isBasicMode) {
            populateJenisKempenforAdvancedRules();
            //populateJenisKempenforAdvancedRules();
            //setTimeout(function () { populateJenisKempenforAdvancedRules(); }, 50);

        }
    };

    vm.convertToAdvance = function () {
        //if (validateField()) {
        $scope.IsRefreshFieldMapping = true;
        $scope.broadcastPopulateBasicRulesEvent();
        //}
        //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 = {
                    ViewID: vm.viewID,
                    JenisPengenalanID: vm.jenisPengenalan,
                    NoPengenalan: vm.noPengenalan,
                    BatchRefNo: vm.batchRefNo,
                    Nama: vm.nama,
                    RujukanNo: vm.rujukanNo,
                    IsExact: vm.isExact,
                    JenisKempenID: vm.jenisKempenID,
                    TahunTaksiran: vm.tahunTaksiran,
                    ReMSDateFrom: vm.reMSDateFrom,
                    ReMSDateTo: vm.reMSDateTo,
                    BatchRefNo: vm.batchRefNo,
                    ImportedDateFrom: vm.importedDateFrom,
                    ImportedDateTo: vm.importedDateTo,
                    IsAdvancedRules: !vm.isBasicMode,
                    JenisCukai: vm.jenisCukai,
                    OutboundStatusID: vm.outboundStatusID,
                    IsHCLEmailBlast: vm.isHCLEmailBlast,
                    IsFromListingSeg: vm.isFromSeg
                }

                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) {
        // 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
            //FieldsSorting: vm.isDynamicDisplayColumn? $scope.displaySetting.FieldsSorting : null
        };

        if (vm.isHCLEmailBlast && !vm.SearchAction) { //email blast, not saved view search, jenis kempen not mandatory, default a jenis kempen id 
            if (!jenisKempenID) {
                model = {
                    ViewID: viewID,
                    JenisKempenID: 12,
                    IsHCLEmailBlast: vm.isHCLEmailBlast
                };
            }
        }

        console.log('model ', model);
        //Chin Tat
        // $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
                    var titleHtml = '<input type="checkbox" ng-disabled="outbound.disabledChkbox || !outbound.totalDataCount" ng-model="outbound.selectPage" ng-click="outbound.selectPagefunc(outbound.selectPage, outbound.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="outbound.disabledChkbox" ng-click="outbound.assignSelected($event, ' + data + ',' + statusID + ')" />'

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

                    dtColumn = DTColumnBuilder.newColumn("RowNum").notSortable().withTitle("No.").withOption('width', '3px');
                    //.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 == "StatusID") {
                    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;" ></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);
            });
            vm.dtInstanceTPSearchSavedView.reloadData();
        });


    }

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



    //Advance Rule: Broadcast event to Advance rules child view to populate dropdown
    $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');
    };

    function populateJenisKempenforAdvancedRules() {
        $scope.AdvanceRules = [];
        AdvanceRulesService.updateItem($scope.AdvanceRules);
        //chin tat $scope.tableType = 5;
        $scope.rulesIndex = -1;
        $scope.rulesType = 1;
        $scope.groupingOperator = '';

        $scope.IsRefreshFieldMapping = true;
        if (vm.jenisKempenID != undefined && vm.jenisKempenID != 0) {
            AdvanceRulesService.setAllowRemove(false);
            $scope.jenisKempenID = vm.jenisKempenID;
            $scope.rulesFieldMapping = "JenisKempenID";
            $scope.rulesIndex = $scope.rulesIndex + 1;
            $scope.rulesOperator = 1;
            $scope.rulefieldType = 15;
            $scope.rulefieldOperator = "IN";
            $scope.rulesFieldValue = [{ "FieldValue": vm.jenisKempenID }];
            $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            console.log('Jenis Kempen Populated');
            // CHIN TAT $scope.$apply();
        }
    }

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

        //if (vm.SearchAction)
        //    $scope.DisableDataFromDB = true;
        //else
        //    $scope.DisableDataFromDB = false;

        // Populate advance rules from saved view
        if (vm.viewID > 0) {
            vm.jenisKempenID = 0;
            //if (vm.SearchAction)
            $scope.DisableDataFromDB = true;
            //else
            //    $scope.DisableDataFromDB = false;

            console.log('Populate ', $scope.AdvancedRulesDB);
            angular.forEach($scope.AdvancedRulesDB, 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;
                    }
                    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');
                });
                ////Loop through rules group
                //angular.forEach(rules.RuleGroup, function (rulesGroupItem, key) {
                //    $scope.ruleGroupFieldsID = rulesGroupItem.FieldValues[0].ViewRuleGroupFieldsID;
                //    $scope.isFromDB = rules.IsFromDB;
                //    if (rules.RuleGroup[0].FieldMapping) {
                //        $scope.rulesFieldMapping = rulesGroupItem.FieldMapping;
                //    }
                //    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 = rulesGroupItem.FieldValues;
                //    $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
                //});
            });
        }

        $scope.rulesType = 1;
        $scope.ruleID = -1
        $scope.groupingOperator = '';
        setTimeout(function () {
            if (vm.jenisKempenID != undefined && vm.jenisKempenID != 0) {
                AdvanceRulesService.setAllowRemove(false);
                $scope.jenisKempenID = vm.jenisKempenID;
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.ruleGroupID = -1;
                $scope.ruleGroupFieldsID = -1;
                $scope.isFromDB = false;

                $scope.rulesFieldMapping = "JenisKempenID";
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 15;
                $scope.rulefieldOperator = "IN";
                $scope.rulesFieldValue = [{ "FieldValue": vm.jenisKempenID }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }
        }, 10);
        setTimeout(function () {
            if (vm.tahunTaksiran != undefined && vm.tahunTaksiran != '') {
                AdvanceRulesService.setAllowRemove(true);
                $scope.rulesFieldMapping = "ASSESSMENT_YEAR";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.ruleGroupID = -1;
                $scope.ruleGroupFieldsID = -1;
                $scope.isFromDB = false;

                $scope.rulesOperator = 1;
                $scope.rulefieldType = 44;
                $scope.rulefieldOperator = "=";
                $scope.rulesFieldValue = [{ "FieldValue": vm.tahunTaksiran }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }
        }, 10);
        setTimeout(function () {
            if (vm.jenisCukai != undefined && vm.jenisCukai != '') {
                AdvanceRulesService.setAllowRemove(true);
                $scope.rulesFieldMapping = "TAXTYPE_CODE";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.ruleGroupID = -1;
                $scope.ruleGroupFieldsID = -1;
                $scope.isFromDB = false;

                $scope.rulesOperator = 1;
                $scope.rulefieldType = 12;
                $scope.rulefieldOperator = "=";
                $scope.rulesFieldValue = [{ "FieldValue": vm.jenisCukai }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }
        }, 10);
        setTimeout(function () {
            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.ruleGroupID = -1;
                $scope.ruleGroupFieldsID = -1;
                $scope.isFromDB = false;

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

                $scope.rulesOperator = 1;
                $scope.rulefieldType = 12;
                $scope.rulefieldOperator = "=";
                $scope.rulesFieldValue = [{ "FieldValue": vm.noPengenalan }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }
        }, 10);
        setTimeout(function () {
            // Tarikh Rems Date range
            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');
            }
        }, 10);
        setTimeout(function () {
            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');
            }
        }, 10);
        setTimeout(function () {
            // Tarikh Dimuat naik
            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');
            }
        }, 10);
        setTimeout(function () {
            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');
            }
        }, 10);
        setTimeout(function () {
            //if (vm.isHCLEmailBlast) {
            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.ruleGroupID = -1;
                $scope.ruleGroupFieldsID = -1;
                $scope.isFromDB = false;

                $scope.rulesOperator = 1;
                $scope.rulefieldType = 12;
                $scope.rulefieldOperator = "=";
                $scope.rulesFieldValue = [{ "FieldValue": vm.batchRefNo }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }
            //}
        }, 10);
        setTimeout(function () {
            if (vm.nama != undefined && vm.nama != '') {
                AdvanceRulesService.setAllowRemove(true);
                //$scope.rulesFieldMapping = "TPName";
                if ($scope.jenisKempenID == vm.constJenisKempenCDL || $scope.jenisKempenID == vm.constJenisKempenYDL)
                    $scope.rulesFieldMapping = "Name";
                else if (vm.isHCLEmailBlast) {
                    $scope.rulesFieldMapping = "NamaPembayarCukai";
                }
                else
                    $scope.rulesFieldMapping = "TAX_PAYER_NAME1";

                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.ruleGroupID = -1;
                $scope.ruleGroupFieldsID = -1;
                $scope.isFromDB = false;

                $scope.rulesOperator = 1;
                $scope.rulefieldType = 12;
                $scope.rulefieldOperator = "%";
                $scope.rulesFieldValue = [{ "FieldValue": vm.nama }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }
        }, 10);
        setTimeout(function () {
            if (vm.rujukanNo != undefined && vm.rujukanNo != '') {
                AdvanceRulesService.setAllowRemove(true);
                $scope.rulesFieldMapping = "NoRujukanCukai";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 12;
                if (vm.isExact)
                    $scope.rulefieldOperator = "=";
                else
                    $scope.rulefieldOperator = "%";
                $scope.ruleID = -1 * $scope.rulesIndex;
                $scope.ruleGroupID = -1;
                $scope.ruleGroupFieldsID = -1;
                $scope.isFromDB = false;

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

        // Clear content if nothing is populated
        if ($scope.rulesIndex < 0)
            $scope.broadcastClearRulesEvent();
    }

    function clearField() {

        vm.jenisCukai = "";
        vm.tahunTaksiran = "";
        vm.jenisPengenalan = "";
        vm.noPengenalan = "";
        vm.batchRefNo = "";
        vm.nama = "";
        vm.rujukanNo = "";
        vm.isExact = false;

        vm.reMSDateFrom = "";
        vm.reMSDateTo = "";
        vm.importedDateFrom = "";
        vm.importedDateTo = "";
        vm.outboundStatusID = "";

        // Carian 
        if (!vm.SearchAction && vm.isBasicMode) {
            vm.jenisKempenID = "";
            $scope.JenisKempenID = 0;
            vm.viewID = 0;
        }
        else if (vm.SearchAction && !vm.isBasicMode && !AdvanceRulesService.checkIsContainDisabledRules()) { //SavedView
            vm.furtherFilter = false;
        }
        else if (vm.SearchAction && vm.isBasicMode) {
            vm.furtherFilter = false;
            vm.jenisKempenID = "";
            $scope.JenisKempenID = 0;
            vm.viewID = 0;
        }

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

    function initSegmentiseList() {

        var ajaxCallbackSegmentiseList = function (data, callback, settings) {
            data.JenisKempenID = vm.jenisKempenSeg == '' ? 0 : vm.jenisKempenSeg;
            if (vm.isHCLEmailBlast) {
                OutboundSI.getAllEmailBlastSegmentiseList(data).then(function (r) {
                    callback(r.data);
                });
            }
            else {
                OutboundSI.getAllSegmentiseList(data).then(function (r) {
                    callback(r.data);
                });
            }
        }
        //Bind table - start 

        if (vm.isHCLEmailBlast) {
            vm.dtColumnsSegmentiseList = [
                DTColumnBuilder.newColumn('ViewName').withTitle('Nama Segmen').renderWith(function (data, type, row) {
                    var link = '<a target="_blank" href="/Outbound/HCLEmailBlastSegmentise/Detail/' + row.ViewID + '">' + row.ViewName + '</a>';
                    return link;
                }),
                DTColumnBuilder.newColumn('JenisKempenName').withTitle('Jenis Kempen'),
                DTColumnBuilder.newColumn('CampaignName').withTitle('Nama Kempen').renderWith(renderFlag),
                DTColumnBuilder.newColumn('CampaignEndDate').withTitle('Tarikh Tamat Kempen').renderWith(function (data, type) {
                    return ($filter('date')(data, 'dd MMM yyyy') || '-');
                }),
                //DTColumnBuilder.newColumn('ActChannelName').withTitle('Interaction Channel').renderWith(function (data) {
                //    return data || '-';
                //}),
                DTColumnBuilder.newColumn('CreatedDateTime').withTitle('Tarikh Dihasilkan').renderWith(function (data, type) {
                    return $filter('date')(data, $scope.DateTimeFormat);
                }),
            ];
        }
        else {
            vm.dtColumnsSegmentiseList = [
                DTColumnBuilder.newColumn('ViewName').withTitle('Nama Segmen').renderWith(function (data, type, row) {
                    var link = '<a target="_blank" href="/Outbound/Segmentise/Detail/' + row.ViewID + '">' + row.ViewName + '</a>';
                    return link;
                }),
                DTColumnBuilder.newColumn('JenisKempenName').withTitle('Jenis Kempen'),
                DTColumnBuilder.newColumn('CampaignName').withTitle('Nama Kempen').renderWith(renderFlag),
                //	.renderWith(function (data, type, row) {
                //	var a = row.Flag == 1 ? '<i class="fas fa-circle" style="color:lime"></i> '
                //    	: '<i class="fas fa-circle" style="color:grey"></i> ';
                //	return a + (data || '-');
                //}),
                DTColumnBuilder.newColumn('CampaignEndDate').withTitle('Tarikh Tamat Kempen').renderWith(function (data, type) {
                    return ($filter('date')(data, 'dd MMM yyyy') || '-');
                }),
                DTColumnBuilder.newColumn('ActChannelName').withTitle('Saluran Interaksi').renderWith(function (data) {
                    return data || '-';
                }),
                DTColumnBuilder.newColumn('CreatedDateTime').withTitle('Tarikh Dihasilkan').renderWith(function (data, type) {
                    return $filter('date')(data, $scope.DateTimeFormat);
                }),
                //DTColumnBuilder.newColumn('ViewID').withTitle('').renderWith(function (data, type) {
                //    var link = '<a target="_blank" href="/outbound/segmentise/detail/' + data + '"><span><i class="fa fa-pencil text-blue" style="cursor:pointer;" title="Edit"></i></span></a>';
                //    return link;
                //})
            ];
        }

        vm.dtOptionsSegmentiseList = DTOptionsBuilder.newOptions()
        .withOption('ajax', ajaxCallbackSegmentiseList)
        .withDataProp('data')
        .withOption('processing', true)
        .withOption('searching', true)
        .withOption('serverSide', true)
        .withOption('autoWidth', false)
        .withPaginationType('full_numbers')
        .withDisplayLength(10);


        function renderFlag(data, type, row, meta) {
            if (row.Flag == 'Green') {
                var a = '<i class="fas fa-circle" style="color:lime; font-size:6px; vertical-align:middle" title="Sedang Dijalankan"></i> '
            }
            else if (row.Flag == 'Orange') {
                var a = '<i class="fas fa-circle" style="color:orange; font-size:6px; vertical-align:middle" title="Belum Dijalankan"></i> '
            }
            else if (row.Flag == 'Grey') {
                var a = '<i class="fas fa-circle" style="color:grey; font-size:6px; vertical-align:middle" title="Tiada Jadual/Selesai"></i> '
            }
            if (row.CampaignName)
                return a + (data || '-');
            else
                return '-';

        };

    };

    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.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.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.JenisCukai = vm.jenisCukai;
            data.OutboundStatusID = vm.outboundStatusID;
            data.IsHCLEmailBlast = vm.isHCLEmailBlast;
            data.IsFromListingSeg = vm.isFromSeg; //for saved view = seg
            data.IsExportExcel = vm.isExportExcel;

            if (!vm.viewID)
                data.IsFromListingSeg = false;

            if (data.IsAdvancedRules) {
                $scope.broadcastGetRulesEvent();
                data.Rules = AdvanceRulesService.getList();
                console.log('Search by Advance Rules');
                console.log(data.Rules);
            }

            if (vm.isHCLEmailBlast && !vm.SearchAction)  //email blast, not saved view search, jenis kempen not mandatory, default a jenis kempen id 
                data.IsFromListingBasicSearch = true;

            if (!vm.isFirstLoadSavedView) {
                OutboundSI.getPagedSearchOutbound(data).then(function (r) {
                    if (r.data) {
                        vm.totalDataCount = r.data.recordsTotal;
                        callback(r.data);
                        console.log('get result', r.data);
                        vm.showBasicTable = true;

                        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.searchAction = false;
                        vm.searchButtonClicked = false;
                    }
                    vm.isFirstLoadSavedView = false;

                });
            }
            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('serverSide', true)
            .withOption('autoWidth', false)
                .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);
                    }
                })
            .withOption('defaultContent', '-')
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
        //.withButtons([
        //    {
        //        extend: 'excelHtml5',
        //        className: 'btn-export-dtbl',
        //        exportOptions: {
        //            columns: ':visible'
        //        },
        //        text: '<i class="fa fa-file-text-o"></i> Eksport Semua ke Excel',
        //        titleAttr: 'Eksport Semua ke Excel',
        //        autoFilter: true
        //    },
        //])
    };

    function postExport(url, data) {
        var form = $("<form action=\"" + url + "\" method=\"post\"></form>");

        var inp = $('<input type="hidden" name="strFileName" value="">');
        inp.val(data);
        form.append(inp);

        $('body').append(form);
        form.submit();
        form.remove();
    }

    vm.tabAction = tabAction;
    function tabAction(cls, init) {
        reset();
        if (init) { getLatestTab(); }
        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;
    }

    function getLatestTab() {
        $("li[class^='Services_']").each(function () {
            var myClassName = this.className;
            if (myClassName.indexOf("Services_01") >= 0) {
                vm.tabProfile01Click();
                return false;
            }
            else if (myClassName.indexOf("Services_02") >= 0) {
                vm.tabProfile02Click();
                return false;
            }
            else if (myClassName.indexOf("Services_03") >= 0) {
                vm.tabProfile03Click();
                return 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.redirectToSeg = function () {
        if (vm.isHCLEmailBlast)
            window.open('\\Outbound/HCLEmailBlastSegmentise/Detail/' + vm.viewID, '_blank');
        else
            window.open('\\Outbound/Segmentise/Detail/' + vm.viewID, '_blank');
    };
    /////////////////////// Segmentise List Tab /////////////////////////////
    vm.segJenisKempenClicked = function () {
        vm.showSegTable = true;
        vm.dtInstanceSegmentiseList.reloadData();
    };

    vm.clearSeg = function () {
        vm.jenisKempenSeg = "";
        vm.showSegTable = false;
    };

    /////////////////////// ReMS/Email Blast Batch Tab /////////////////////////////
    function initBatchList() {

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

            data.JenisKempenID = vm.jenisKempenReMS;
            data.DateFrom = $filter('date')(vm.importedDateFromReMS, $scope.DateTimeFormat);
            data.DateTo = $filter('date')(vm.importedDateToReMS, $scope.DateTimeFormat);
            data.BatchRefNo = vm.batchRefNoReMS;
            data.UploadedByName = vm.uploadedByNameReMS;

            if (vm.isHCLEmailBlast) {
                OutboundSI.getAllEmailBlastBatchList(data).then(function (r) {
                    if (r.data) {
                        callback(r.data);
                    }
                });
            }
            else {
                OutboundSI.getAllReMSBatchList(data).then(function (r) {
                    if (r.data) {
                        callback(r.data);
                    }
                });
            }
        }

        if (vm.isHCLEmailBlast) {
            vm.dtColumnsReMSBatchList = [
                DTColumnBuilder.newColumn('BatchHasError').notSortable().withTitle(' ').renderWith(function (data, type) {
                    return data == true ? '<i class="case fa fa-exclamation-circle" title="Mengandungi data tidak sah" style="color:red;" ></i >' : '';
                }).withOption('width', '10px'),
                //DTColumnBuilder.newColumn('RowNum').withOption('bSortable', false).withTitle('No.'),
                DTColumnBuilder.newColumn('JenisKempenName').withTitle('Jenis Kempen'),
                DTColumnBuilder.newColumn('EmailBatchRefNo').withTitle('No. Rujukan Kelompok').renderWith(function (data, type, row) {
                    return '<a><span ng-click="outbound.viewBatchClicked(' + row.EmailBatchID + ',' + row.JenisKempenID + ')">' + data + '</span></a>';

                }),
                DTColumnBuilder.newColumn('TotalRecords').withTitle('Jumlah Rekod'),
                DTColumnBuilder.newColumn('UploadedByName').withTitle('Dimuat Naik Oleh'),
                DTColumnBuilder.newColumn('UploadedDateTime').withTitle('Tarikh Dimuat Naik').renderWith(function (data, type) {
                    return $filter('date')(data, $scope.DateTimeFormat);
                }),
                //DTColumnBuilder.newColumn('UploadedDateTime').withTitle('Uploaded Time').renderWith(function (data, type) {
                //    return moment(data).format('h:mm a');
                //}),
                DTColumnBuilder.newColumn('StatusName').withTitle('Status Kelompok'),
                //DTColumnBuilder.newColumn('EmailBatchID').notSortable().withTitle('').renderWith(function (data, type, row) {
                //    return '<a><span><i class="fa fa-eye text-blue" style="cursor:pointer;" title="View" ng-click="outbound.viewBatchClicked(' + data + ',' + row.JenisKempenID + ')"></i></span></a>';
                //})
            ];
        }
        else {
            vm.dtColumnsReMSBatchList = [
                //DTColumnBuilder.newColumn('ReturnedByName').withTitle('').withOption('width', '50px').renderWith(function (data, type) {
                //    var link = '';
                //    if (data)
                //        link += '<div class="tooltip bg-gray margin-r-5" style="border-radius: 10px;width: 20px;height: 20px;line-height:20px;text-align:center;margin-left:5px;"><span class="fa fa-reply"></span><span class="tooltiptext">Returned</span></div>';
                //    return link;
                //}),
                DTColumnBuilder.newColumn('BatchHasError').notSortable().withTitle(' ').renderWith(function (data, type) {
                    return data == true ? '<i class="case fa fa-exclamation-circle" style="color:red;" title="Mengandungi data tidak sah"></i >' : '';
                }).withOption('width', '10px'),
                DTColumnBuilder.newColumn('RowNum').withOption('bSortable', false).withTitle('No.'),
                DTColumnBuilder.newColumn('JenisKempenName').withTitle('Jenis Kempen'),
                DTColumnBuilder.newColumn('BatchRefNo').withTitle('No. Rujukan Kelompok').renderWith(function (data, type, row) {
                    return '<a><span ng-click="outbound.viewBatchClicked(' + row.BatchID + ',' + row.JenisKempenID + ')">' + data + '</span></a>';

                }),
                DTColumnBuilder.newColumn('TotalRecords').withTitle('Jumlah Rekod'),
                //DTColumnBuilder.newColumn('ImportedByName').withTitle('Imported By'),
                DTColumnBuilder.newColumn('ImportedDateTime').withTitle('Tarikh Dimuat Naik').renderWith(function (data, type) {
                    return $filter('date')(data, $scope.DateTimeFormat);
                }),
                //DTColumnBuilder.newColumn('BatchID').notSortable().withTitle('').renderWith(function (data, type, row) {
                //    return '<a><span><i class="fa fa-eye text-blue" style="cursor:pointer;" title="View" ng-click="outbound.viewBatchClicked(' + data + ',' + row.JenisKempenID + ')"></i></span></a>';
                //})
            ];
        }

        vm.dtOptionsReMSBatchList = DTOptionsBuilder.newOptions()
          .withOption('ajax', ajaxCallbackReMSBatchList)
          .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);
    };

    vm.clearReMS = function () {
        vm.jenisKempenReMS = "";
        vm.importedDateFromReMS = "";
        vm.importedDateToReMS = "";
        vm.batchRefNoReMS = "";
        vm.uploadedByNameReMS = "";

        vm.showReMSBatchTable = false;
        //vm.dtInstanceReMSBatchList.reloadData();
    };

    vm.searchReMS = function () {
        vm.showErrImportedDateReMS = false;
        vm.LoadingUploadHCLData = true;
        vm.ErrMsgImportedDateReMS = "";

        if (vm.importedDateFromReMS || vm.importedDateToReMS) {
            var d = new Date(vm.importedDateFromReMS);
            var dt = new Date(vm.importedDateToReMS);

            if ((!vm.importedDateFromReMS && vm.importedDateToReMS) ||
                (vm.importedDateFromReMS && !vm.importedDateToReMS)) {
                vm.ErrMsgImportedDateReMS = "Banjaran tarikh tidak sah.";
                vm.showErrImportedDateReMS = true;
                return;
            }

            if (d > dt) {
                vm.ErrMsgImportedDateReMS = "Date To must be greater than Date From.  ";
                vm.showErrImportedDateReMS = true;
                return;
            }
        }

        vm.invalidUploadedByName = false
        if (vm.uploadedByNameReMS) {
            if (vm.uploadedByNameReMS.length < 6) {
                vm.invalidUploadedByName = true;
                return;
            }
        }
        vm.showReMSBatchTable = true;
        vm.dtInstanceReMSBatchList.reloadData();
        vm.LoadingUploadHCLData = false;
    };

    vm.viewBatchClicked = function (batchID, jenisKempenID) {
        if (vm.isHCLEmailBlast)
            $window.open('/Outbound/HCLEmailBlastBatch/Detail/' + jenisKempenID + '/' + batchID, '_blank');
        else
            $window.open('/Outbound/Batch/Detail/' + jenisKempenID + '/' + batchID, '_blank');

    };

    /////////////////////// Upload Email Blast Excel /////////////////////////////
    vm.showUploadExcelDialog = function (e) {
        vm.openDialog(e, '#myUploadExcelModal');
    }

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

    }

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

    vm.writeFileToFolder = function () {
        vm.invalidJenisKempenEmailBlast = false;
        model = {
            JenisKempenID: vm.jenisKempenEmailBlast,
            AttachmentList: vm.excelList
        }

        if (!vm.jenisKempenEmailBlast) {
            vm.invalidJenisKempenEmailBlast = true;
            return;
        }

        if (!vm.excelList) {
            angular.element("#fileUpload").click();
            return;
        }

        if (vm.excelList.length > 0) {
            vm.isUploading = true;
            OutboundSI.writeFileToFolder(model).then(function (r) {
                $mdDialog.hide();
                swal({
                    title: "Fail Berjaya Dimuatnaik!",
                    text: "No. Rujukan Kelompok:  " + r.data,
                    type: "success",
                    //timer: 2500,
                    showConfirmButton: true,
                    closeOnConfirm: true
                }, function () {
                    vm.jenisKempenEmailBlast = "";
                    vm.excelList = [];
                    angular.element("#fileUpload")[0].value = "";
                    swal.close();
                });
                vm.isUploading = false;
                vm.showReMSBatchTable = true;
                vm.dtInstanceReMSBatchList.reloadData();

            });
        }
        else
            angular.element("#fileUpload").click();

    };

    vm.uploadFiles = function (file, errFiles) {
        vm.excelList = [];

        vm.f = file;
        //vm.errFile = errFiles && errFiles[0];
        //file = 'a'; TODO Error Response not caught 
        var isUploaded = false;
        if (file) {
            file.upload = Upload.upload(OutboundSI.uploadAttachment(file));

            file.upload.then(function (r) {
                if (r.data) {
                    $timeout(function () {
                        //vm.Files.push({ TempAttachID: r.data, Name: file.name });
                        r.data.AttachmentID = null;
                        isUploaded = true;

                        vm.excelList.push(r.data);

                        vm.errorMsg = null;
                        vm.f = null;
                        //vm.errFile = null;
                    });
                }
                else {
                    swal("Batal!", "Jenis fail tidak diterima. Format fail yang dibenarkan untuk dimuat naik adalah .xls,.xlsx.", "error");
                    isUploaded = true;
                }
            }, function (r) {
                if (r.status > 0) {
                    vm.errFile = true;
                    vm.excelList = [];
                }
                //vm.errorMsg = r.status + ': ' + r.data;
            }, function (evt) {
                var progress = Math.min(100, parseInt(100.0 *
                    evt.loaded / evt.total)).toFixed(2);
                if (isUploaded == false)
                    progress = progress * 0.5;
                else progress = 100;
                file.progress = progress;
            });
        }
        if (errFiles.length > 0) {
            if (errFiles[0].$error = "maxSize") {
                var strErrorMsg = errFiles[0].name + " fail saiz " + (parseInt(errFiles[0].size / 1000000) || "0").toString() + "MB melebihi saiz muat naik maksimum(" + errFiles[0].$errorParam + ") yang dibenarkan.";
                swal("Gagal", strErrorMsg, "error");
            }
        }
    }

    vm.deleteAttachment = function (AttachID, objfile) {
        if (vm.excelList) {
            var index = vm.excelList.indexOf(objfile);
            if (index != -1) {
                vm.excelList.splice(index, 1);
            }
        }
        angular.element("#fileUpload").click();
    }

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

    vm.saveAsNewSegmentise = function ($event) {
        vm.search();

        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;
        var rulesContainsStatus = false;
        if (vm.IsAdvancedRules) {
            $scope.broadcastGetRulesEvent();
            vm.jSonStringAdvanced = { AdvancedRules: [], DisplaySetting: {} }
            var temp = AdvanceRulesService.getList();
            var saveAsSegRules = angular.copy(temp);
            // Remove status from advanced rules       
            angular.forEach(saveAsSegRules, function (rules, i) {
                var removeCurrentRules = false;
                angular.forEach(rules.RuleGroup, function (item, j) {
                    if (item.FieldMapping == 'StatusID') {
                        rulesContainsStatus = true;
                        var i = rules.RuleGroup.indexOf(item);
                        if (i != -1) {
                            if (rules.RuleGroup.length > 1)
                                rules.RuleGroup.splice(i, 1);
                            else
                                removeCurrentRules = true;
                        }
                    }
                });
                if (removeCurrentRules) saveAsSegRules.splice(saveAsSegRules.indexOf(rules), 1);
            });


            vm.jSonStringAdvanced.AdvancedRules = saveAsSegRules;
            vm.jSonStringAdvanced.DisplaySetting = AdvanceRulesService.getDisplaySetting();
        }

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

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

        $event.preventDefault();
        //Prompt alert if advanced rules contains status
        if (rulesContainsStatus) {
            swal({
                title: "Saringan Status",
                text: "Saringan Status tidak akan disimpan sebagai segmen.",
                type: "warning",
                confirmButtonClass: "btn-danger",
                confirmButtonText: "Ya",
                closeOnConfirm: true
            },
            function (isConfirm) {
                confirmSaveAsSegmen();
            });
        }
        else {
            confirmSaveAsSegmen();
        }
    }

    function confirmSaveAsSegmen() {
        if (vm.isHCLEmailBlast) {
            angular.element('#emailBlast_NewSegViewID').val(vm.viewID);
            //angular.element('#emailBlast_NewSegJenisKempenID').val($scope.jenisKempenID);
            angular.element('#emailBlast_NewSegJenisKempenID').val(vm.jenisKempenID);
            angular.element('#emailBlast_JSonStringBasic').val(vm.jsonStringBasic);
            angular.element('#emailBlast_JSonStringAdvanced').val(vm.jSonStringAdvanced);
            angular.element('#btn-submitnewemailblastseg').click();
        }
        else {
            angular.element('#newSegViewID').val(vm.viewID);
            //angular.element('#newSegJenisKempenID').val($scope.jenisKempenID);
            angular.element('#newSegJenisKempenID').val(vm.jenisKempenID);
            angular.element('#jSonStringBasic').val(vm.jsonStringBasic);
            angular.element('#jSonStringAdvanced').val(vm.jSonStringAdvanced);
            angular.element('#btn-submitnewseg').click();
        }
    }

    // date picker

    vm.clearImportedDateFromReMS = function () {
        vm.clearImportedDateFromReMS = '';
        vm.clearImportedDateFromReMS.$dirty = true;
        vm.clearImportedDateFromReMS.$pristine = false;
    };
    vm.clearImportedDateToReMS = function () {
        vm.clearImportedDateToReMS = '';
        vm.clearImportedDateToReMS.$dirty = true;
        vm.clearImportedDateToReMS.$pristine = false;
    };
    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.clearImportedDateFromReMS = function () {
        vm.importedDateFromReMS = '';
        vm.importedDateFromReMS.$dirty = true;
        vm.importedDateFromReMS.$pristine = false;
    };
    vm.clearImportedDateToReMS = function () {
        vm.importedDateToReMS = '';
        vm.importedDateToReMS.$dirty = true;
        vm.importedDateToReMS.$pristine = false;
    };

    function loadDisplaySetting() {
        var viewID = 0;
        var jenisKempenID = 0;
        var tableType = 0;
        if (vm.viewID) viewID = vm.viewID;
        if (vm.jenisKempenID) jenisKempenID = vm.jenisKempenID;
        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);
                AdvanceRulesService.updateDisplaySetting($scope.displaySetting);
                AdvanceRulesService.setOriDisplaySetting();
                $scope.$broadcast('AdvanceRules_DisplayColumn', 'INIT');

            }
        });
    }

    vm.exportExcel = function () {
        swal({
            title: "Adakah anda pasti untuk eksport rekod ke Excel?",
            text: "Maksimum rekod export =" + vm.maxExportRecord,
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                swal.close();
                vm.isExportExcel = true;
                vm.search();
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });
    }

});