crmApp.controller("SearchCaseController", SearchCaseController);

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

    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;
    vm.caseStatusId = $window.casestatusid;
    vm.statusID = $window.casestatusid;
    vm.LinkfromDashboard = $window.isLinkfromDashboard;
    vm.IsTodayCase = $window.istodaycase;

    vm.isFirstLoadBasic = true;
    vm.isFirstLoadAdv = true;
    vm.isFirstLoadSavedView = true;

    vm.SearchAction = true;
    vm.isBasicMode = true;
    vm.isSavedViewMode = false;
    vm.showBasicTable = false;
    vm.showAdvTable = false;

    vm.dtInstanceCaseSearchBasic = {};

    vm.kategori1ID = {};
    vm.kategori1ID.selected = [];
    vm.isExact = false;

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

        SearchSI.getSearchDropdown($window.tabletype).then(function (r) {
            for (var key in r.data) {
                vm[key] = r.data[key];

            }

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

        initBasicTable();
        if (vm.statusID) {
            if ($window.casestatusid == 2) {
                vm.statusID = 2;
            }
            else {
                vm.statusID = 1;
            }

            loadDynamicColumns(0);
            vm.showBasicTable = true;

            vm.ShowFilter = false;

        }
        else {
            vm.ShowFilter = true;
        }


    };

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

    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 () {
        if (vm.isBasicMode) {
            if ((!vm.SearchAction && (vm.viewID != undefined && vm.viewID != null && vm.viewID != "")) || validateField()) {
                var id = 0;
                if (!vm.SearchAction)
                    id = vm.viewID;
                loadDynamicColumns(id);
                vm.showBasicTable = true;
            }
        }

        else {
            if (validateRules()) {
                loadDynamicColumns(vm.viewID);
                vm.showBasicTable = true;
            }
        }
    };

    vm.toggleSearchMode = function (searchForm) {
        var isDirty = searchForm.$dirty;
        vm.isSavedViewMode = false;
        if (vm.isBasicMode) {
            vm.isBasicMode = 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.isBasicMode = true;
            $scope.IsAdvancedView = !vm.isBasicMode;
            vm.showBasicTable = false;
            AdvanceRulesService.setDynamicDisplayInd(false);
            vm.sectionTitle = "Saringan Asas";
            angular.element("#SearchModeButton").text("Use Advanced Search");
        }
        $scope.IsAdvancedView = !vm.isBasicMode;
    };

    vm.toggleSavedViewOptions = function () {
        if (vm.viewID == null)
            vm.isSavedViewMode = false;
        else {
            clearField(true);
            $scope.ViewID = vm.viewID;
            vm.isSavedViewMode = true;
            vm.showBasicTable = false;

            GeneralSI.getAdvancedRulesDetails(vm.viewID, 2).then(function (r) {
                if (r.status == 200) {
                    $scope.AdvancedRulesDB = r.data.Rules;
                    //$scope.AdvancedRulesDisplayColumns = r.data.DisplayColumns;
                    $scope.displaySetting = AdvanceRulesService.getDisplaySetting();
                    $scope.displaySetting.DisplayColumns = r.data.DisplaySetting.DisplayColumns;
                    $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);

                    }

                }
            });

        }
    };

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

            }
        });
    }

    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.dtColumnsCaseSearchBasic = [];
                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.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.dtColumnsCaseSearchBasic.push(dtColumn);
                });

                setTimeout(function () {
                    $scope.$apply(function () {
                        vm.dtInstanceCaseSearchBasic.reloadData();
                    });
                }, 1); 
            }
        });

    }

    function clearField(isSavedView) {
        if (!isSavedView)
            vm.viewID = "";

        vm.jenisPengenalan = "";
        vm.noPengenalan = "";
        vm.nama = "";
        vm.rujukanNo = "";
        vm.isExact = false;
        vm.caseNo = "";
        vm.statusID = "";
        vm.IsOprhan = "";
        vm.kategori1ID.selected = [];

        vm.invalidNoPengenalan = false;
        vm.invalidJenisPengenalan = false;
        vm.invalidNamaLength = false;
        vm.invalidsearch = false;
        vm.invalidRujukanNoLength = false;

        $scope.broadcastClearRulesEvent();

    };

    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;

    }

    //Advance Rule:  Validation
    function validateRules() {
        var isValid = true;

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

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

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

    function populateBasicRules() {
        $scope.tableType = 1;
        $scope.AdvanceRules = [];
        AdvanceRulesService.updateItem($scope.AdvanceRules);
        $scope.rulesIndex = -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');
            }

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

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


            if (vm.kategori1ID.selected.length != 0) {
                $scope.rulesFieldMapping = "Kategori1ID";
                $scope.rulesIndex = $scope.rulesIndex + 1;
                $scope.isFromDB = false;
                $scope.rulesOperator = 1;
                $scope.rulefieldType = 15;
                $scope.rulefieldOperator = "IN";
                $scope.rulesFieldValue = [];
                angular.forEach(vm.kategori1ID.selected, function (value, key) {
                    $scope.rulesFieldValue.push({
                        "FieldValue": value
                    });
                });

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

        //no input
        if (!vm.noPengenalan && !vm.nama && !vm.rujukanNo &&
            !vm.caseNo && !vm.statusID && !vm.IsOprhan && vm.kategori1ID.selected.length == 0) {
            //vm.invalidNoPengenalan = true;
            //vm.invalidJenisPengenalan = true;

            if ((vm.jenisPengenalan) && (!vm.noPengenalan)) {
                vm.invalidNoPengenalan = true;
                isValid = false;
            } else {
                vm.invalidsearch = true;
                isValid = false;
            }
        }
        else {//any input
            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;
                }

            }
        }

        return isValid;
    };

    function initBasicTable() {
        var ajaxCallback = function (data, callback, settings) {
            $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.JenisPengenalanID = !vm.jenisPengenalan ? '' : vm.jenisPengenalan;
            data.NoPengenalan = !vm.noPengenalan ? '' : vm.noPengenalan.replace(/\s/g, "");;
            //data.NoPengenalan = !vm.noPengenalan ? '' : vm.noPengenalan;
            data.Nama = !vm.nama ? '' : vm.nama;
            data.RujukanNo = !vm.rujukanNo ? '' : vm.rujukanNo.replace(/\s/g, "");
            data.IsExact = !vm.isExact ? false : vm.isExact;
            data.IsFirstLoad = vm.isFirstLoadBasic;
            data.CaseRefNo = !vm.caseNo ? '' : vm.caseNo;
            data.Status1ID = !vm.statusID ? '' : vm.statusID;
            data.IsOprhan = !vm.IsOprhan ? '' : vm.IsOprhan;
            data.Kategori1ID = !vm.kategori1ID ? '' : (vm.kategori1ID.selected.length == 0 ? '' : "'" + vm.kategori1ID.selected.join("','") + "'"); //vm.kategori1ID; //vm.EntityIDType == null ? '' : 
            data.IsLinkfromDashboard = vm.LinkfromDashboard
            data.IsCaseToday = vm.IsTodayCase;
             data.isSavedView = vm.isSavedViewMode;
            data.ViewID = vm.viewID;
            if ($scope.IsAdvancedView) {
                $scope.broadcastGetRulesEvent();
                data.Rules = AdvanceRulesService.getList();
                console.log('Search by Advance Rules');
            }
            console.log(data.Rules);
            data.IsAdvancedView = $scope.IsAdvancedView;

            SearchSI.getPagedSearchCase(data).then(function (r) {
                if (r.status == 200 && (r.data)) {
                    callback(r.data);
                    //console.log('basic', r.data);
                }
                vm.isFirstLoadBasic = 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.Status1ID)
                    dataCopy.Status1ID = 0;

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

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

                if (!dataCopy.IsCaseToday)
                    dataCopy.IsCaseToday = 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.dtColumnsCaseSearchBasic = [
			DTColumnBuilder.newColumn('CaseStatusLevel1ID').withTitle(' ').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%'),
            DTColumnBuilder.newColumn('CaseRefNo').withTitle('No. Kes').renderWith(renderCaselink).withOption('width', '13%'),
            DTColumnBuilder.newColumn('TPNoCukai').withTitle('No Rujukan Cukai').renderWith(function (data, type, row) {
                if (row.TPID == null) {
                    return '-';
                }
                else {
                    return '<a href="/TaxPayer/Profile/Detail/' + row.TPID + '" target="_blank">' + data + '</a>'
                }

                //  return '<a href="/TaxPayer/Profile/Detail/' + row.TPID + '" target="_blank">' + data + '</a>'
            }).withOption('width', '13%'),
            DTColumnBuilder.newColumn('TPName').withTitle('Nama').withOption('width', '20%'),
			DTColumnBuilder.newColumn('Aliran').withTitle('Aliran').renderWith(function (data, type) {
			    var input = data == 'Masuk' ? '<span><i style="transform:rotate(-45deg)" class="arrow fa fa-arrow-down"  title="Masuk"></i> </span>'
			    	: '<span> <i style = "transform:rotate(-45deg)" class="arrow fa fa-arrow-up outboundArrow" title="Keluar"></i></span >';
			    return input;
			}).withOption('width', '5%'),
            DTColumnBuilder.newColumn('Kategori1Name').withTitle('Kategori').renderWith(renderKategori).withOption('width', '32%'),
            DTColumnBuilder.newColumn('JenisKempenName').withTitle('Jenis Kempen').withOption('width', '15%')
        ];

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

    function renderCaselink(data, type, row, meta) {

        var link = '<a href="/Case/Profile/detail/' + row.CaseID + '" target="_blank">' + row.CaseRefNo + '</a>';
        if (row.CaseRefNo == undefined || row.CaseRefNo == '0')
            link = '-';
        return link
    }

    function renderKategori(data, type, row, meta) {
        var kategoriDesc = '';
        if (row.Kategori1Name != '' && row.Kategori1Name != undefined)
            kategoriDesc += '<ul class="list-inline"><li><b>' + row.Kategori1Name + ' </b></li>';
        if (row.Kategori2Name != '' && row.Kategori2Name != undefined)
            kategoriDesc += '<li class="arrow-separator" style="font-size:0.785em;"><b> ' + row.Kategori2Name + ' </b></li>';
        if (row.Kategori3Name != '' && row.Kategori3Name != undefined)
            kategoriDesc += '<li class="arrow-separator" style="font-size:0.785em;"><span> ' + row.Kategori3Name + '</span></li>';

        if (kategoriDesc != '')
            kategoriDesc = kategoriDesc + '</ul >';

        var label = '<span>' + kategoriDesc + '</span>';

        return label
    }

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