crmApp.controller("SearchTPController", SearchTPController);

function SearchTPController($scope, $window, $compile, SearchSI, GeneralSI, AntiForgeryService, DTColumnBuilder, DTOptionsBuilder, $filter, AdvanceRulesService, GeneralService, $timeout) {
    var vm = this;

    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;
    ////Advance Rule: Broadcast event to Advance rules child view to populate dropdown
    //$scope.broadcastGetDropDownEvent = function () {
    //    $scope.$broadcast('AdvanceRules', 'GETDROPDOWN');
    //};
    vm.isFirstLoadBasic = true;
    vm.isFirstLoadAdv = true;
    vm.isFirstLoadSavedView = true;
    //vm.IsSearchClick = false;
    vm.SearchAction = true;
    vm.isBasicMode = true;
    vm.showBasicTable = false;
    vm.showAdvTable = false;
    vm.noPengenalan = $window.nopengenalan;
    vm.isLinkfromDashboard = $window.isLinkfromDashboard;
    var constIDTypeNRIC = {};
    var constNRIC = 28;
    vm.dtInstanceTPSearchBasic = {};
    $scope.SearchData = {};
    $scope.IsSearchClick = false;

    vm.isExact = false;

    vm.init = function () {
        vm.isSavedViewMode = false;
        vm.ShowTPResult = false;
        vm.NoTPResultFound = false;
        $scope.clearAdvanceRules = 0;
        vm.sectionTitle = "Saringan Asas";
        SearchSI.getSearchDropdown($window.tabletype).then(function (r) {
            for (var key in r.data) {
                vm[key] = r.data[key];
            }

            if (vm.isLinkfromDashboard) {
                var m = $filter('filter')(vm.JenisPengenalanOptions, { IsDefault: true }, true);
                if (m && (m.length > 0)) {
                    constIDTypeNRIC = m[0];
                    vm.jenisPengenalan = constIDTypeNRIC.Value;
                }
                var id = 0;
                loadDynamicColumns(id);
                vm.showBasicTable = true;
            }

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

        vm.ShowFilter = true;
        initBasicTable();
    };

    vm.JenisPengenalanOnChange = function () {
        vm.isLinkfromDashboard = false;
        vm.clearNoPengenalan();
    };

    vm.SearchActionOnChanged = function (form) {
        form.$setPristine();
        vm.clear();
        //vm.isSavedViewMode = !vm.isSavedViewMode;
    };

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

                    vm.showBasicTable = false;
                    $timeout(function() {
                      clearField();
                     });
                    
                }
            });
        }
        else {
            if (vm.isSavedViewMode)
                vm.isSavedViewMode = false;

            vm.showBasicTable = false;

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

    vm.search = function () {
        //console.log('search');
        //vm.isSavedViewMode = false;
        if (vm.isBasicMode) {
            console.log('basic');
            if ((!vm.SearchAction && (vm.viewID != undefined && vm.viewID != null && vm.viewID != "")) || validateField()) {
                var id = 0;
                if (!vm.SearchAction)
                    id = vm.viewID;
                vm.IsSearchClick = true;
                loadDynamicColumns(id);
                //vm.dtInstanceTPSearchBasic.reloadData();
                vm.showBasicTable = true;
            }
        }
        else {

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

        }
    };

    //Advance Rule:  Validation
    function validateRules() {
        var isValid = true;
        var errMessage = "Please fill in all mandatory fields";

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

    vm.toggleSearchMode = function (searchForm) {
        var isDirty = searchForm.$dirty;
        vm.isSavedViewMode = false;
        if (vm.isBasicMode) {
            //vm.showBasicTable = false;
            vm.sectionTitle = "Saringan Terperinci";
            angular.element("#SearchModeButton").text("Use Basic Search");
            if (isDirty) {
                vm.promptConvertToAdvancedRules(searchForm);
                //reset form to pristine, so that rules only converted when dirty
                searchForm.$setPristine();
            } else {
                vm.isBasicMode = false;
                $scope.IsAdvancedView = !vm.isBasicMode;
            }
            loadDisplaySetting();
        }
        else {
            vm.showAdvTable = false;
            vm.isBasicMode = true;
            $scope.IsAdvancedView = !vm.isBasicMode;
            vm.showBasicTable = false;
            vm.sectionTitle = "Saringan Asas";
            angular.element("#SearchModeButton").text("Use Advanced Search");
        }
    };

    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, 1).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);
                    AdvanceRulesService.setOriDisplaySetting();
                    $scope.$broadcast('AdvanceRules_DisplayColumn', 'INIT');
                    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();
                    }

                }
            });

        }
    };

    function loadDisplaySetting() {
        var viewID = 0;
        if (vm.viewID) viewID = vm.viewID;
        GeneralSI.getDisplaySetting(1, viewID, 0).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');

            }
        });
    }

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

        vm.IsSearchClick = true;
        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.dtColumnsTPSearchBasic = [];
                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') {
                            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.dtColumnsTPSearchBasic.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.dtColumnsTPSearchBasic.push(dtColumn);
                //vm.dtInstanceTPSearchBasic.reloadData();
                setTimeout(function () {
                    $scope.$apply(function () {
                        vm.dtInstanceTPSearchBasic.reloadData();
                    });
                }, 1);
            }
        });

    }

    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 = !vm.noPengenalan ? '' : vm.noPengenalan.replace(/\s/g, "");
            data.Nama = !vm.nama ? '' : vm.nama;
            data.RujukanNo = !vm.rujukanNo ? '' : vm.rujukanNo.replace(/\s/g, "").replace(/[^A-Z0-9]/ig, "");
            data.IsExact = !vm.isExact ? false : vm.isExact;
            data.ViewID = vm.viewID;
            data.isSavedView = vm.isSavedViewMode;
            data.IsLinkfromDashboard = vm.LinkfromDashboard
       
        //}
        //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;

        if (!$scope.IsSearchClick) $scope.SearchData =  $.extend(true, [],data);

        console.log(data.IsAdvancedView);
        //if (!vm.isFirstLoadBasic) {
        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 {
                    if ((vm.jenisPengenalan != undefined && vm.jenisPengenalan != 0)
                        && (vm.noPengenalan != undefined && vm.noPengenalan != '')) {
                        vm.ShowTPResult = false;
                        vm.NoTPResultFound = true;
                        var idType = $filter('filter')(vm.JenisPengenalanOptions, { Value: vm.jenisPengenalan }, true);
                        vm.OrphanTPIdType = vm.jenisPengenalan;
                        vm.OrphanTPIdTypeDesc = idType[0] != undefined ? idType[0].Text : "";
                        vm.OrphanTPIdNo = vm.noPengenalan;
                    }
                    else {
                        vm.NoTPResultFound = false;
                        vm.ShowTPResult = true;
                    }

                }
            }
            vm.isFirstLoadBasic = false;

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

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

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

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

            if (!dataCopy.isSavedView)
                dataCopy.isSavedView = 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.promptConvertToAdvancedRules = function (form) {
        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: "Yes",
            closeOnConfirm: true
        },
            function (isConfirm) {
                if (isConfirm) {
                    vm.convertToAdvance(form);
                    $scope.$apply();
                }
                else {
                    if (vm.isBasicMode) vm.isBasicMode = true;
                    $scope.$apply();
                    form.$setPristine();
                }
            });

    }

    vm.convertToAdvance = function (form) {

        if ((vm.SearchAction && validateField()) || !vm.SearchAction) {
            vm.isBasicMode = false;

            $scope.broadcastPopulateBasicRulesEvent();
        }
        else {
            form.$setPristine();
            vm.isBasicMode = true;
        }

        $scope.IsAdvancedView = !vm.isBasicMode;
    }

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

    //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');
    };

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

    function populateBasicRules() {
        $scope.tableType = 1;
        $scope.AdvanceRules = [];
        AdvanceRulesService.updateItem($scope.AdvanceRules);
        $scope.rulesIndex = -1;
        $scope.ruleGroupsIndex = -1;
        // Populate advance rules from saved view
        if (!vm.SearchAction) {
            console.log('Populate ', $scope.AdvancedRulesDB);
             
            angular.forEach($scope.AdvancedRulesDB, function (rules, key) {

                $scope.ruleID = rules.ViewRuleID; 
                $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');
                });

            });
        } else {

            $scope.rulesType = 1;
            $scope.groupingOperator = '';

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

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

            if (vm.nama != undefined && vm.nama != '') {
                $scope.rulesFieldMapping = "TPName";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.isFromDB = false;
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 12;
                $scope.rulefieldOperator = "=";
                $scope.rulesFieldValue = [{ "FieldValue": vm.nama }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }

            if (vm.rujukanNo != undefined && vm.rujukanNo != '') {
                $scope.rulesFieldMapping = "NoRujukanCukai";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.isFromDB = false;
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 12;
                if (vm.isExact)
                    $scope.rulefieldOperator = "=";
                else
                    $scope.rulefieldOperator = "%";

                $scope.rulesFieldValue = [{ "FieldValue": vm.rujukanNo }];
                $scope.$broadcast('AdvanceRules', 'POPULATEBASICRULES');
            }
        }
        // Clear content if nothing is populated
        if ($scope.rulesIndex < 0)
            $scope.broadcastClearRulesEvent();
    }

    function validateField() {
        vm.invalidNoPengenalan = false;
        vm.invalidJenisPengenalan = false;
        vm.invalidNamaLength = false;
        vm.invalidsearch = false;
        vm.invalidRujukanNoLength = false;
        var isValid = true;
        var hasOtherFiltering = false;
        //no input
        if (!vm.jenisPengenalan && !vm.noPengenalan && !vm.nama && !vm.rujukanNo) {
            //vm.invalidNoPengenalan = true;
            //vm.invalidJenisPengenalan = true;
            vm.invalidsearch = true;
            isValid = false;
        }
        else {//any input

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

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

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

        return isValid;
    };

    vm.clearNoPengenalan = function () {
        if (!vm.JenisPengenalan) {
            vm.noPengenalan = "";
        }
    };

    function initBasicTable() {
        vm.dtColumnsTPSearchBasic = [];
        //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.dtOptionsTPSearchBasic = 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('deferLoading', true);
    };

    vm.onAddActClick = function (tpid) {
        angular.element('#hdn-TPID').val(tpid);
        var btn = angular.element('#btn-submitAddAct');
        btn.click();
    };

    vm.CreateOrphanTPActivity = function ($event) {
        angular.element('#hdn_IDNo').val(vm.OrphanTPIdNo);
        angular.element('#hdn_IDType').val(vm.OrphanTPIdType);
        angular.element('#hdn_IDTypeDesc').val(vm.OrphanTPIdTypeDesc);
        var btn = angular.element('#btn-submitOrphanTPAct');
        btn.click();
    }

    vm.selectTPForAct = function () {
        angular.element('#IDNo').val(vm.noPengenalan);
        angular.element('#IDType').val(vm.jenisPengenalan);
        var form = angular.element('#btn-submitAddAct');;
        form.submit();
    };

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