crmApp.controller("AdminSearchViewConfigController", AdminSearchViewConfigController);

function AdminSearchViewConfigController($scope, $window, $compile, AntiForgeryService, AdminSI, SearchSI, GeneralSI, DTColumnBuilder, DTOptionsBuilder, $filter, AdvanceRulesService, GeneralService, $q, $timeout) {
    var vm = this;
    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;


    vm.isFirstLoadAdv = true;

    vm.isSavedViewMode = false;
    vm.ShowTPResult = false;
    vm.NoTPResultFound = false;
    vm.dtInstanceTPSearchAdv = {};
    vm.tabProfile01Active = true;

    vm.viewID = $window.viewid;
    vm.tabletype = $window.tabletype;
  //  vm.advancedFilter = convertFromJson($window.jSonStringAdvanced); 
    vm.newViewID = $window.newViewID;

    console.log(vm.tabletype);
    isHasInitDataTable = false;
    $scope.permissionSetting = [];


    vm.init = function () {

        $scope.clearAdvanceRules = 0;
        vm.sectionTitle = "Saringan Terperinci";
        AdvanceRulesService.setDynamicDisplayInd(true);
        $scope.IsAdvancedView = true;
        initAdvanceTable();
        //if (vm.advancedFilter != undefined && vm.advancedFilter.AdvancedRules != null)
        //    AdvanceRulesService.updateItem(vm.advancedFilter.AdvancedRules);

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

        if (vm.viewID > 0) {
            vm.isSavedViewMode = true;
        }

       
        
        $scope.isSaveNewSeg = true;
        vm.ShowFilter = true;
        $scope.$on('AdvanceRules', function (event, data) {
            if (data == 'ADVInitializeComplete') {
                if (vm.newViewID > 0) {
                    loadAdvanceRules(vm.newViewID);
                }
                else{ 
                    loadAdvanceRules(vm.viewID);
                } 
            }

        });

    };

    vm.duplicateViewConfig = function ($event) {
        vm.jsonStringBasic = undefined;
        vm.jSonStringAdvanced = undefined;
         
        $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('#tableType').val(vm.tabletype);
        angular.element('#newViewID').val(vm.viewID);

        angular.element('#jSonStringAdvanced').val(vm.jSonStringAdvanced)

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

        $event.preventDefault();

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

    vm.deleteViewConfig = function(viewID,TableType)
    {
        vm.showAdvTable = false;
        swal({
            title: "Adakah anda pasti untuk hapus paparan carian ini?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                //var model = {
                //    ViewID: viewID
                //};
                GeneralSI.deleteViewConfig(viewID, TableType).then(function (r) {
                    if (r.status === 200) {
                            swal({
                                title: "Paparan Carian dihapuskan!",
                                text: "Paparan Carian anda telah berjaya dihapuskan.",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: true
                            }, function () {
                                if (TableType == 3)
                                {
                                    vm.redirectTo('/Admin/SearchView/');
                                }
                                else if (TableType == 2)
                                {
                                    vm.redirectTo('/Admin/SearchView#/Case');
                                }
                                else
                                {
                                   
                                    vm.redirectTo('/Admin/SearchView#/Taxpayer');
                                }
                               
                            });
                     
                    }
                    else {
                        swal("Gagal!", r.data, "error");
                        return returnResultPromise();
                    }
                });
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
                vm.showAdvTable = false;
               return returnResultPromise();
            }
        });

        vm.showAdvTable = false;
    }

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


    function decodeEntities(encodedString) {
        var textArea = document.createElement('textarea');
        textArea.innerHTML = encodedString;
        console.log(textArea.value);
        return textArea.value;
    }


    vm.clear = function () {
        //if (vm.isSavedViewMode)
        //    vm.isSavedViewMode = false;
        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) {
                vm.showAdvTable = false;

                $timeout(function () {
                clearField();
                });

                $scope.tpSearchForm.$dirty = true; 
            }
        });
    };

    vm.search = function () {
        //console.log('search');
        //vm.isSavedViewMode = false;

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


    };

    //Advance Rule:  Validation
    function validateRules() {
        var isValid = true;
        var errMessage = "Sila pilih sekurang-kurangnya satu kriteria";

        isValid = GeneralService.validateAdvancedRules(false);
       
        return isValid;
    }

    function initAdvanceTable() {
        vm.dtColumnsTPSearchAdv = [];
        //vm.dtColumnsTPSearchBasic = [
        //    DTColumnBuilder.newColumn('NoRujukanCukai').withTitle('No Rujukan Cukai').renderWith(function (data, type, row) {
        //        return '<a href="/TaxPayer/Profile/Detail/' + row.TPID + '" target="_blank">' + data + '</a>'
        //    }).withOption('width', '11%'),
        //    DTColumnBuilder.newColumn('FileType').withTitle('File Type').withOption('width', '5%'),
        //    DTColumnBuilder.newColumn('JenisPengenalan').withTitle('Jenis Pengenalan').withOption('width', '8%'),
        //    DTColumnBuilder.newColumn('IdentityNo').withTitle('No Pengenalan').withOption('width', '10%'),
        //    DTColumnBuilder.newColumn('TPName').withTitle('Nama').withOption('width', '30%'),
        //    DTColumnBuilder.newColumn('TPID').withTitle('').renderWith(function (data, type, row) {
        //        var link;
        //        link = '<button type="button" class="btn-link" ng-click="search.onAddActClick(' + row.TPID + ')" ><span class="fa fa-plus"></span> Add Activity</button>';
        //        return link;
        //    }).withOption('width', '7%')
        //];

        vm.dtOptionsTPSearchAdv = 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)
            // .withOption('deferRender', true)
            .withOption('deferLoading', true);
    };


    //.withOption('deferLoading', [10,10]);

    vm.toggleSavedViewOptions = function () {
        //default view
        if (vm.viewID == null) {
            clearField(true);
            vm.showBasicTable = false;
            vm.isSavedViewMode = false;
            angular.element("#DropdownDefaultOption").text("Sila pilih satu");
        }
        else {
            clearField(true);
            console.log("Saved VIew", vm.viewID);
            $scope.ViewID = vm.viewID;
            vm.isSavedViewMode = true;
            //vm.showBasicTable = true;

            GeneralSI.getAdvancedRulesDetails(vm.viewID, vm.tabletype).then(function (r) {
                if (r.status == 200) {
                    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);

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

                    if (vm.isBasicMode) {
                        //vm.showBasicTable = vm.isBasicMode;
                        //loadDynamicColumns(vm.viewID);
                        //vm.showBasicTable = true;
                    }
                    else {
                        // $scope.broadcastGetDropDownEvent();
                        //setTimeout(function () {
                        //    loadDynamicColumns(vm.viewID);
                        //    vm.convertToAdvance();
                        //}, 200);
                        loadDynamicColumns(vm.viewID);
                        vm.convertToAdvance();
                    }
                    $scope.$broadcast('AdvanceRules_Permission', 'INIT');
                }
            });

        }
    };


    function clearField(isSavedView) {
        //if (isSavedView) {
        //    angular.element("#DropdownDefaultOption").text("");
        //}
        //else {
        //    vm.viewID = "";
        //    angular.element("#DropdownDefaultOption").text("Sila pilih satu");
        //}

        //vm.jenisPengenalan = "";
        //vm.noPengenalan = "";
        //vm.nama = "";
        //vm.rujukanNo = "";
        //vm.isExact = false;
        vm.NoTPResultFound = false;
        //vm.isLinkfromDashboard = false;
        //vm.invalidNoPengenalan = false;
        //vm.invalidJenisPengenalan = false;
        //vm.invalidNamaLength = false;
        vm.invalidsearch = false;
        //vm.invalidRujukanNoLength = false;
        // $scope.clearAdvanceRules = $scope.clearAdvanceRules + 1;
        //AdvanceRulesService.clearList();
        //AdvanceRulesService.addItem($scope.AdvanceRules);

        $scope.broadcastClearRulesEvent();
        // $scope.AdvanceRulesNew = AdvanceRulesService.getDefaultList();
        //bindTPSearchProfileOnSuccess();
        //vm.jenisPengenalan = null;
        //var m = $filter('filter')(vm.JenisPengenalanOptions, { IsDefault: true }, true);
        //if (m && (m.length > 0)) {
        //    constIDTypeNRIC = m[0];
        //    vm.jenisPengenalan = constIDTypeNRIC.Value;
        //}
    };

    function loadAdvanceRules(viewID) {

        //clearField(true);
        $scope.ViewID = vm.viewID;
        $scope.IsAdvancedView = true;
        GeneralSI.getAdvancedRulesDetails(viewID, vm.tabletype).then(function (r) {
            if (r.status == 200) {
                console.log('Advance Rules Details');

                console.log(r.data);
                vm.ViewName = r.data.ViewName;
                //vm.sectionTitle =vm.ViewName? vm.ViewName + ' ' + vm.sectionTitle : vm.sectionTitle;
                vm.IsDashboardOption = r.data.IsDashboardOption;
                vm.IsSystemView = r.data.IsSystemView;
                console.log('vm.IsDasboardOption');
                console.log(vm.IsDashboardOption);

                vm.IsDynamicDisplayColumn = r.data.IsDynamicDisplayColumn;
                vm.IsActive = r.data.IsActive;
                if (!vm.viewID && !vm.newViewID)
                    vm.IsActive = true;
                vm.ChangeStamp = r.data.ChangeStamp;
                console.log('vm.IsActive');
                console.log(vm.IsActive);
                $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.broadcastPopulateAdvRulesEvent();
                $scope.$broadcast('AdvanceRules_Permission', 'INIT');
            }
        });

    }

    vm.redirectTo = function (url) {

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

    vm.saveView = function () {

        if (!$scope.tpSearchForm.$valid) {
            vm.showValidationMsgPopup = true;
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            return returnResultPromise();
        }

        if (validateRules()) {

            var AdvancedRules = AdvanceRulesService.getList();
            var displaySetting = AdvanceRulesService.getDisplaySetting();

            //todo-carerose
            var permissionUsers = AdvanceRulesService.getPermissionUser();
            var permissionRoles = AdvanceRulesService.getPermissionRole();
            var permissionType = AdvanceRulesService.getPermissionType();


            console.log("adv rules");
            console.log(AdvancedRules);
            console.log("display");
            console.log(displaySetting);
            var model = {
                    ViewID: vm.viewID,
                    ViewName: vm.ViewName,
                    IsDashboardOption: vm.IsDashboardOption,
                    IsSystemView: vm.IsSystemView,
                    IsDynamicDisplayColumn: vm.IsDynamicDisplayColumn,
                    TableType: vm.tabletype,
                    IsActive: vm.IsActive,
                    PermissionType: permissionType,
                    ChangeStamp: vm.ChangeStamp,
                    DisplaySetting: displaySetting,
                    Rules: AdvancedRules,
                    PermissionUsers: permissionUsers,
                    PermissionRoles: permissionRoles
        };

            var data = AdminSI.updateAdvRulesView(model)

            data.then(function (r) {

                vm.viewID = r.data.ViewID;
                console.log(vm.viewID);

                swal({
                        title: GeneralService.SaveMessage.Title,
                        text: GeneralService.SaveMessage.Text,
                        type: "success",
                        timer: 2500,
                        showConfirmButton: true
                }, function () {

                    vm.redirectTo('/Admin/SearchView/ConfigureView?ViewID=' + vm.viewID + '&TableType=' + vm.tabletype);
                    return returnResultPromise();
                });
                return returnResultPromise();
            });
        }
        else {
            return returnResultPromise();
        }

    }

    function returnResultPromise() {
        var result = null;
        var deferred = $q.defer();
        deferred.reject('');
        result = deferred.promise;
        //$scope.$apply();
        return result;
    }

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

    function populateAdvanceRules() {
        $scope.tableType = vm.tabletype;
        $scope.AdvanceRules = [];
        AdvanceRulesService.updateItem($scope.AdvanceRules);
        $scope.rulesIndex = -1;
        $scope.ruleGroupsIndex = -1;
        // Populate advance rules from saved view
        if (vm.isSavedViewMode || vm.newViewID>0) {
            console.log('Populate ', $scope.AdvancedRulesDB);
            angular.forEach($scope.AdvancedRulesDB, function (rules, key) {

                $scope.ruleID = rules.ViewRuleID; /*SL added*/
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.rulesType = rules.RuleType;
                $scope.groupingOperator = rules.GroupingOperator;
                $scope.rulesOperator = rules.RuleOperator;
                $scope.isFromDB = rules.IsFromDB;
  
                //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');
                });
                 
            });
        }


        console.log('After Populate advanced', AdvanceRulesService.getList());
        // Clear content if nothing is populated
        if ($scope.rulesIndex < 0)
            $scope.broadcastClearRulesEvent();
    }

    function loadDynamicColumns(viewID) {
        $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
        vm.isDynamicDisplayColumn = AdvanceRulesService.getDynamicDisplayInd();

        var model = {
            ViewID: viewID,
            TableType: $window.tabletype,
            IsDynamicDisplayColumn: vm.isDynamicDisplayColumn,
            DisplayColumns: vm.isDynamicDisplayColumn ? $scope.displaySetting.DisplayColumns : null
        };

        SearchSI.getSavedViewColumns(model).then(function (r) {
            if (r.status == 200) {
                vm.dtColumnsTPSearchAdv = [];
                if (vm.tabletype == 1) { 
                    angular.forEach(r.data, function (item, i) {
                        var dtColumn = null;
                        if (item.FieldMapping == 'NoRujukanCukai') {
                            dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type, row) {
                                return '<a href="/TaxPayer/Profile/Detail/' + row.ID + '" target="_blank">' + data + '</a>'
                            }).withOption('defaultContent', '-');
                        }
                        else
                            if (item.FieldType == 'Date' || item.FieldType == 'Date(SystemGenerated)') {
                                dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type) {
                                    return $filter('date')(data, 'dd MMM yyyy');
                                }).withOption('defaultContent', '-');
                            } else if (item.FieldType.toLowerCase() == 'currency') {
                                dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).withClass('text-right').renderWith(function (data, type) {
                                    return $filter('number')(data, 2);
                                }).withOption('defaultContent', '-');
                            }
                            else {
                                dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).withOption('defaultContent', '-');
                            }
                        vm.dtColumnsTPSearchAdv.push(dtColumn);
                    });
              
                    // Insert for last column
                    dtColumn = DTColumnBuilder.newColumn('ID').notSortable().withTitle('').renderWith(function (data, type, row) {
                        var link;
                        link = '<button type="button" class="btn-link" ng-click="search.onAddActClick(' + row.ID + ')" ><span class="fa fa-plus"></span> Tambah Aktiviti</button>';
                        return link;
                    }).withOption('width', '10%');
                    vm.dtColumnsTPSearchAdv.push(dtColumn);
                }
                else if (vm.tabletype == 2) {
                    angular.forEach(r.data, function (item, i) {
                        var dtColumn = null;
                        if (item.FieldMapping == 'CaseStatusLevel1ID') {
                            dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).notSortable().withTitle(item.DisplayName).renderWith(function (data, type) {
                                var input = data == '2' ? '<i class="case fa fa-exclamation-circle" style="color:red;" title="Belum Selesai"></i>' : '';
                                return input;
                            }).withOption('width', '2%');
                        }
                        else if (item.FieldMapping == 'TPNoCukai') {
                            dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type, row) {
                                if (!data) {
                                    retValue = '-';
                                } else if (row.TPID == null) {
                                    retValue = data;
                                }
                                else {
                                    return '<a href="/TaxPayer/Profile/Detail/' + row.TPID + '" target="_blank">' + data + '</a>'
                                }

                            }).withOption('defaultContent', '-');
                        }
                        else if (item.FieldMapping == 'CaseRefNo') {
                            dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type, row) {
                                return '<a href="/Case/Profile/Detail/' + row.ID + '" target="_blank">' + data + '</a>'
                            }).withOption('defaultContent', '-');
                        }
                        else if (item.FieldMapping == 'PromisedToPay') {
                            dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type) {
                                return $filter('date')(data, $scope.DateTFormat);
                            }).withOption('defaultContent', '-');
                        }
                        else {
                            if (item.FieldType == 'Date' || item.FieldType == 'Date(SystemGenerated)') {
                                dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type) {
                                    return $filter('date')(data, $scope.DateTimeFormat);
                                }).withOption('defaultContent', '-');
                            } else if (item.FieldType.toLowerCase() == 'currency') {
                                dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).withClass('text-right').renderWith(function (data, type) {
                                    return $filter('number')(data, 2);
                                }).withOption('defaultContent', '-');
                            }
                            else {
                                dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).withOption('defaultContent', '-');
                            }
                        }
                        vm.dtColumnsTPSearchAdv.push(dtColumn);
                    });
                }
                else if (vm.tabletype == 3) {
                    angular.forEach(r.data, function (item, i) {
                        var dtColumn = null;
                        if (item.FieldMapping == 'ActStatusID') {
                            dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).notSortable().withTitle(item.DisplayName).renderWith(function (data, type) {
                                var input = data == '261' ? '<i class="case fa fa-exclamation-circle" style="color:red;" title="Belum Selesai"></i>' : '';
                                return input;
                            }).withOption('width', '2%');
                        }
                        else if (item.FieldMapping == 'TPNoCukai') {
                            dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type, row) {
                                var retValue;
                                if (!data) {
                                    retValue = '-';
                                } else if (row.TPID == null) {
                                    retValue = data;
                                }
                                else { retValue = '<a href="/TaxPayer/Profile/Detail/' + row.TPID + '" target="_blank">' + data + '</a>'; }
                                return retValue;
                            }).withOption('defaultContent', '-');
                        }
                        else if (item.FieldMapping == 'CaseRefNo') {
                            dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type, row) {
                                return data == null ? '-' : '<a href="/Case/Profile/Detail/' + row.CaseID + '" target="_blank">' + data + '</a>'
                            }).withOption('defaultContent', '-');
                        } else if (item.FieldMapping == 'PromiseToPayDate') {
                            dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type) {
                                return $filter('date')(data, $scope.DateFormat);
                            }).withOption('defaultContent', '-');
                        }
                        else if (item.FieldType == 'Date' || item.FieldType == 'Date(SystemGenerated)') {
                            dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type) {
                                return $filter('date')(data, $scope.DateTimeFormat);
                            }).withOption('defaultContent', '-');
                        } else if (item.FieldType.toLowerCase() == '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 == 'ActRefNo') {
                            dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).renderWith(function (data, type, row) {
                                return '<a href="/Activity/Profile/Detail/' + row.ID + '" target="_blank">' + data + '</a>'
                            }).withOption('defaultContent', '-');
                        }
                        else {
                            dtColumn = DTColumnBuilder.newColumn(item.FieldMapping).withTitle(item.DisplayName).withOption('defaultContent', '-');
                        }
                        vm.dtColumnsTPSearchAdv.push(dtColumn);
                    });
                }
                setTimeout(function () {
                    $scope.$apply(function () {
                        vm.dtInstanceTPSearchAdv.reloadData();
                    });
                }, 1);
                //vm.dtInstanceTPSearchAdv.changeData(ajaxCallback);
            }
        });

    }

    var ajaxCallback = function (data, callback, settings) {
        //if (vm.isBasicMode) {
        //if (vm.isLinkfromDashboard) { data.JenisPengenalanID = constNRIC; }
        //else { data.JenisPengenalanID = !vm.jenisPengenalan ? '' : vm.jenisPengenalan; }

        //data.NoPengenalan = !vm.noPengenalan ? '' : vm.noPengenalan.replace(/\s/g, "");
        //data.NoPengenalan = !vm.noPengenalan ? '' : vm.noPengenalan.replace(/[^A-Z0-9]/ig, "");
        $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.NoPengenalan = '';
        data.Nama = '';
        data.RujukanNo = '';
        data.IsExact = false;

        data.ViewID = vm.viewID;
        data.isSavedView = vm.isSavedViewMode;
        //data.IsLinkfromDashboard = vm.LinkfromDashboard
        console.log("Is saved view ", data.isSavedView);
        //}
        //else {
        //console.log('Advance');
        //data.Rules = AdvanceRulesService.getList();
        //}
        if ($scope.IsAdvancedView) {
            $scope.broadcastGetRulesEvent();
            data.Rules = AdvanceRulesService.getList();
            console.log('Search by Advance Rules');
        }
        console.log(data.Rules);
        data.IsAdvancedView = $scope.IsAdvancedView;

        console.log(data.IsAdvancedView);
        //if (!vm.isFirstLoadBasic) {

        if (vm.tabletype == 1) {
            SearchSI.getPagedSearchTP(data).then(function (r) {
                if (r.status == 200 && (r.data)) {
                    callback(r.data);
                    vm.lstTP = r.data;
                    console.log('Results : ', r.data);
                    vm.NoTPResultFound = false;
                    if (vm.lstTP.data != undefined && vm.lstTP.data.length != 0) {
                        vm.ShowTPResult = true;
                        vm.NoTPResultFound = false;
                    }
                    else {

                        vm.NoTPResultFound = false;
                        vm.ShowTPResult = true;


                    }
                    vm.isFirstLoadBasic = false;

                }

            });
        }
        else if (vm.tabletype == 2) {
            SearchSI.getPagedSearchCase(data).then(function (r) {
                if (r.status == 200 && (r.data)) {
                    callback(r.data);
                    vm.lstTP = r.data;
                    console.log('Results : ', r.data);
                    vm.NoTPResultFound = false;
                    if (vm.lstTP.data != undefined && vm.lstTP.data.length != 0) {
                        vm.ShowTPResult = true;
                        vm.NoTPResultFound = false;
                    }
                    else {

                        vm.NoTPResultFound = false;
                        vm.ShowTPResult = true;


                    }
                }
                vm.isFirstLoadBasic = false;
            });

        }

        else if (vm.tabletype == 3) {

            SearchSI.getPagedSearchAct(data).then(function (r) {
                if (r.status == 200 && (r.data)) {
                    callback(r.data);
                    vm.lstTP = r.data;
                    console.log('Results : ', r.data);
                    vm.NoTPResultFound = false;
                    if (vm.lstTP.data != undefined && vm.lstTP.data.length != 0) {
                        vm.ShowTPResult = true;
                        vm.NoTPResultFound = false;
                    }
                    else {

                        vm.NoTPResultFound = false;
                        vm.ShowTPResult = true;


                    }
                }
                vm.isFirstLoadBasic = false;
            });
        }
        // }

    }

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

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

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

