crmApp.controller("TaxPayerController", TaxPayerController);

function TaxPayerController($scope, $window, $compile, $q, $http, $location, $filter, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, TaxPayerSI, TaxPayerService, GeneralService, ActivitySI, AntiForgeryService, CaseSI) {
    var vm = this;
    vm.TaxPayerId = $window.taxpayerid;
    vm.hdrTempl = 'loading';
    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;

    //Disable the Search TP edit button on header 
    TaxPayerService.TP.AllowEdit = false;

    // reference to validation format
    vm.emailValidation = GeneralService.Validation.Email;
    vm.phoneValidation = GeneralService.Validation.Phone;

    vm.phoneValidationMsg = GeneralService.Validation.PhoneMsg;
    vm.emailValidationMsg = GeneralService.Validation.EmailMsg;

    vm.ChangesHistory = [];
    vm.parseInt = parseInt;
    var ajaxCallback = function (data, callback, settings) {
        data.TPID = $window.taxpayerid;
        TaxPayerSI.getPagedTPAgentList(data).then(function (r) {
            if (r.status == 200) {
                callback(r.data);
            }
        });
    }
    var ajaxCallbackOL = function (data, callback, settings) {

        data.TPID = $window.taxpayerid;
        data.JenisKempenID = vm.JenisKempenID;
        data.CampaignName = vm.JenisCampaignName;
        data.TahunTaksiran = vm.TahunTaksiran;
        data.JenisCukai = vm.JenisOCLCukai;
        data.OutboundStatusID = vm.OutboundStatusID;
        TaxPayerSI.getOutboundListByTaxPayer(data).then(function (r) {
            if (r.status == 200) {
                callback(r.data);
                //console.log(r.data);
            }
        });
    }


    var count = 0;

    vm.init = function () {

        tabAction("01", "Profile");

        // datepicker
        vm.dateFromMinDate = null;
        vm.dateFromMaxDate = null;
        vm.buttonBarObj = $scope.ButtonBar;
        console.log(vm.buttonBarObj);
        vm.dateFromOptions = {
            minDate: null, // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            dateDisabled: false,
            startingDay: 1 
        };

        vm.dateToMinDate = null;
        vm.dateToMaxDate = null;
        vm.dateToOptions = {
            minDate: null, // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            dateDisabled: false,
            startingDay: 1,
            closed: function (args) {
                vm.closedArgs = args;
                alert('datepicker closed');
            }
        };

        // Load Taxpayer data
        TaxPayerSI.getTaxPayer(vm.TaxPayerId).then(function (r) {
            if (r.status == 200) {
                $scope.tp = r.data;
                vm.tp = r.data;
                vm.tp.SpouseDetails = r.data.SpouseDetails;
                vm.tp.TPPemilikanSyarikat = r.data.PemilikanSyarikat;
                vm.tp.TPSekatanPjn75A = r.data.SktPerjalanan75A;
                vm.tp.TPShareholderDetails = r.data.ShareholderDetail;
                console.log(vm.tp.TPShareholderDetails);
                vm.tp.TPMajikanCukai = r.data.CukaiMajikanDetail;
                vm.tp.TPAgents = r.data.EjenCukaiDetail;
                vm.tp.TPFailPenduaDetails = r.data.FailPenduaDetail;
                vm.tp.TPStatusBayarBalik = r.data.StatusBayaranBalik;

                TaxPayerService.TP.TPID = vm.TaxPayerId;
                TaxPayerService.TP.Name = vm.tp.TPName;
                TaxPayerService.TP.TPType = vm.tp.JenisPengenalan;
                TaxPayerService.TP.IDNo = vm.tp.IdentityNo;
                TaxPayerService.TP.FileType = vm.tp.FileType;
                TaxPayerService.TP.TaxNo = vm.tp.NoCukai;
                TaxPayerService.TP.NoCukaiCode = vm.tp.NoCukaiCode;
                TaxPayerService.TP.StatusFail = vm.tp.StatusFail;
                TaxPayerService.TP.StatusFailPendua = vm.tp.StatusFailPendua;
                TaxPayerService.TP.GelaranName = vm.tp.GelaranName;
                TaxPayerService.TP.HonorificName = vm.tp.HonorificName;

                TaxPayerService.CWNG.PungutanCP = vm.tp.CWPungutanCP;
                TaxPayerService.CWNG.PungutanCKHT = vm.tp.CWPungutanCKHT;
                TaxPayerService.CWNG.PenaksiranCP = vm.tp.CWPenaksiranCP;
                TaxPayerService.CWNG.PenaksiranCKHT = vm.tp.CWPenaksiranCKHT;
                TaxPayerService.CWNG.GuamanSivil = vm.tp.CWGuamanSivil;

                vm.hdrTempl = 'tp.profile.header';
            }
        });

        vm.dtColumnDefsEjenCukai = [
            DTColumnDefBuilder.newColumnDef(0),
            DTColumnDefBuilder.newColumnDef(1),
            DTColumnDefBuilder.newColumnDef(2),
            DTColumnDefBuilder.newColumnDef(3),
            DTColumnDefBuilder.newColumnDef(4),
            DTColumnDefBuilder.newColumnDef(5),
            DTColumnDefBuilder.newColumnDef(6),
        ];

        vm.dtOptionsEjenCukai = DTOptionsBuilder.newOptions()
            .withPaginationType('full_numbers')
            .withDisplayLength(10);

        //Bind table - start
        vm.dtColumnsEjenCukai2 = [
            DTColumnBuilder.newColumn('AgentNo').withTitle('No Ejen'),
            DTColumnBuilder.newColumn('AgentName').withTitle('Nama'),
            DTColumnBuilder.newColumn('Firma').withTitle('Firma'),
            DTColumnBuilder.newColumn('ROC').withTitle('ROC'),
            DTColumnBuilder.newColumn('Phone').withTitle('No Telefon'),
            DTColumnBuilder.newColumn('City').withTitle('Bandar'),
            DTColumnBuilder.newColumn('Email').withTitle('Emel'),
        ];

        vm.dtOptionsEjenCukai2 = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallback)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('serverSide', true)
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
        //Bind Table - end



        vm.dtColumnsOCL = [

            DTColumnBuilder.newColumn('StatusID').withTitle(' ').renderWith(function (data, type) {
                if (data != '27' && data != '29' && data != '30' && data != '39') {
                    return '';
                }
                else {
                    return '<i class="case fa fa-exclamation-circle" style="color:red;" title="Belum Selesai"></i >';

                }
            }),
            DTColumnBuilder.newColumn('JenisKempen').withTitle('Jenis Kempen').renderWith(function (data, type, full) {
                if (data == '-') {
                    return data
                }
                else {
                    return '<a target="_blank" href="/Outbound/profile/detail/' + full.JenisKempenID + '/' + full.ReMSDataID + '">' + data + '</a>';
                }

            }).withOption('width', '20%'),
            DTColumnBuilder.newColumn('CampaignName').withTitle('Nama Kempen'),
            //DTColumnBuilder.newColumn('ActRefNo').withTitle('Activity No.').renderWith(function (data) {
            //    var colValue = '';
            //    if (data == '' || data == '-') {
            //        colValue = '-';
            //    }
            //    else {
            //        colValue = '<a href="/Activity/Profile/detail/1" target="_blank">' + data + '</a>';
            //    }
            //    return colValue;
            //}),
            //DTColumnBuilder.newColumn('CaseRefNo').withTitle('Case No.').renderWith(function (data) {
            //    var colValue = '';
            //    if (data == '' || data == '-') {
            //        colValue = '-';
            //    }
            //    else {
            //        colValue = '<a href="/Case/Profile/detail/17" target="_blank">' + data + '</a>';
            //    }
            //    return colValue;
            //}),  
            DTColumnBuilder.newColumn('JenisCukai').withTitle('Jenis Cukai'),
            DTColumnBuilder.newColumn('TarikhJanjiBayar').withTitle('Tarikh Janji Bayar').renderWith(function (data, type) {
                if (data == null)
                    return '-'
                return $filter('date')(data, 'dd MMM yyyy');
            }),
            DTColumnBuilder.newColumn('TahunTaksiran').withTitle('Tahun Taksiran'),
            DTColumnBuilder.newColumn('TarikhREMSHantar').withTitle('Tarikh REMS Hantar').renderWith(function (data, type) {
                if (data == null)
                    return '-'

                return $filter('date')(data, 'dd MMM yyyy');
            }),
            DTColumnBuilder.newColumn('REMSDate').withTitle('Tarikh ReMS').renderWith(function (data, type) {
                if (data == null)
                    return '-'

                return $filter('date')(data, 'dd MMM yyyy');
            }),
            DTColumnBuilder.newColumn('OutboundStatus').withTitle('Status'),
        ];

        vm.dtOptionsOCL = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallbackOL)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('serverSide', true)
            .withPaginationType('full_numbers')
            .withDisplayLength(10);

        //StatusKes tab and muat turun Lejar - drop down menu
        TaxPayerSI.getDropdown().then(function (r) {
            //console.log(r.data);
            for (var key in r.data) {
                vm[key] = r.data[key];
            }
        });

        //Check if taxpayerid > 0, if yes, load get changehistory, activitylist and case
        if ($window.taxpayerid > 0) {

            getChangeHistoryActivityCase();
        }

        //Case Expand And Collapse Filter default value(Hide Content)
        vm.show = false;
        //Activities Expand And Collapse Filter default value(Hide Content)
        vm.ActShow = false;
        vm.IsPelangganPembayarCukaiDisable = true;
        vm.IsCukaiAgentDisable = true;
        vm.OCLShow = false;
    }

    function onbeforeunload(e) {

        if (!$window.beforeUnloadCanceled) {
            return e.returnValue = "Unsaved changes";
        }
    }

    vm.redirectTo = function (url) {

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

    vm.toggleChangeTPProfile = toggleChangeTPProfile;
    function toggleChangeTPProfile(toggle) {
        if (toggle == true) {

        }
    }

    vm.tabAction = tabAction;
    function tabAction(cls, type, init) {
        reset();
        if (init) { getLatestTab(); }
        switch (cls) {
            case '01':
                type == "Profile" ? tabProfile01Click() : tabServices01Click();
                break;
            case '02':
                type == "Profile" ? tabProfile02Click() : tabServices02Click();
                break;
            case '03':
                type == "Profile" ? tabProfile03Click() : tabServices03Click();
                break;
            case '04':
                type == "Profile" ? tabProfile04Click() : tabServices04Click();
                break;
            case '05':
                tabProfile05Click();
                break;
            case '06':
                tabProfile06Click();
                break;
            case '07':
                tabProfile07Click();
                break;
            case '08':
                tabProfile08Click();
                break;
        }
    }

    function getLatestTab() {
        $("li[class^='Services_']").each(function () {
            var myClassName = this.className;
            if (myClassName.indexOf("Services_01") >= 0) {
                vm.tabServices01Click();
                console.log("Services_01");
                return false;
            }
            else if (myClassName.indexOf("Services_02") >= 0) {
                vm.tabServices02Click();
                console.log("Services_02");
                return false;
            }
            else if (myClassName.indexOf("Services_03") >= 0) {
                vm.tabServices03Click();
                console.log("Services_03");
                return false;
            }
            else if (myClassName.indexOf("Services_04") >= 0) {
                vm.tabServices04Click();
                console.log("Services_04");
                return false;
            }
        });
    }

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

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

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

    //Profile Tab 04
    vm.tabProfile04Click = tabProfile04Click;
    function tabProfile04Click() {
        vm.IsProfileTab = vm.tabProfile04Active = true;
        $("html, body").animate({ scrollTop: 0 }, 400);
    }

    //Profile Tab 05
    vm.tabProfile05Click = tabProfile05Click;
    function tabProfile05Click() {
        vm.IsProfileTab = vm.tabProfile05Active = true;
        $("html, body").animate({ scrollTop: 0 }, 400);
    }

    //Profile Tab 06
    vm.tabProfile06Click = tabProfile06Click;
    function tabProfile06Click() {
        vm.IsProfileTab = vm.tabProfile06Active = true;
        $("html, body").animate({ scrollTop: 0 }, 400);
    }

    //Profile Tab 07
    vm.tabProfile07Click = tabProfile07Click;
    function tabProfile07Click() {
        vm.IsProfileTab = vm.tabProfile07Active = true;
        $("html, body").animate({ scrollTop: 0 }, 400);
    }

    //Profile Tab 08
    vm.tabProfile08Click = tabProfile08Click;
    function tabProfile08Click() {
        vm.IsProfileTab = vm.tabProfile08Active = true;
        $("html, body").animate({ scrollTop: 0 }, 400);
    }

    //Services Tab 01
    vm.tabServices01Click = tabServices01Click;
    function tabServices01Click() {
        vm.IsServicesTab = vm.tabServices01Active = true;
        $("html, body").animate({ scrollTop: 0 }, 400);
    }

    //Services Tab 02
    vm.tabServices02Click = tabServices02Click;
    function tabServices02Click() {
        vm.IsServicesTab = vm.tabServices02Active = true;
        $("html, body").animate({ scrollTop: 0 }, 400);
    }

    //Services Tab 03
    vm.tabServices03Click = tabServices03Click;
    function tabServices03Click() {
        vm.IsServicesTab = vm.tabServices03Active = true;
        $("html, body").animate({ scrollTop: 0 }, 400);
    }

    //Services Tab 04
    vm.tabServices04Click = tabServices04Click;
    function tabServices04Click() {
        vm.IsServicesTab = vm.tabServices04Active = true;
        $("html, body").animate({ scrollTop: 0 }, 400);
    }

    function reset() {
        vm.IsProfileTab = false;
        vm.IsServicesTab = false;

        // Set Table visibility
        vm.tabProfile01Active = false;
        vm.tabProfile02Active = false;
        vm.tabProfile03Active = false;
        vm.tabProfile04Active = false;
        vm.tabProfile05Active = false;
        vm.tabProfile06Active = false;
        vm.tabProfile07Active = false;
        vm.tabProfile08Active = false;

        vm.tabServices01Active = false;
        vm.tabServices02Active = false;
        vm.tabServices03Active = false;
        vm.tabServices04Active = false;
    }

    vm.SaveInOutboundDetails = function (isDirty) {
        var result = null;

        // checking for changes
        if (isDirty) {
            angular.forEach($scope.myForm, function (value, key) {
                if (key[0] == '$') return;

                var displayName = $('#' + key).data('displayfield');

                if (value.$pristine == false) {
                    vm.ChangesHistory.push({
                        ID: vm.tp.TPID,
                        FieldName: key,
                        DisplayName: displayName,
                        OldValue: '',
                        NewValue: value.$viewValue,
                        IsChanged: !value.$pristine
                    });
                }
            });

            vm.correspondenceUpdate = {
                TPID: vm.tp.TPID,
                IsPelangganPembayarSama: vm.tp.IsPelangganPembayarSama,
                InCallerID: vm.tp.InCallerID,
                InTelefonMB: vm.tp.InTelefonMB,
                InUpdateTelefonMBDate: vm.tp.InUpdateTelefonMBDate,
                InEmailMB: vm.tp.InEmailMB,
                InUpdateEmailMBDate: vm.tp.InUpdateEmailMBDate,
                OutTelefonBimbit: vm.tp.OutTelefonBimbit,
                OutTelefonPejabat: vm.tp.OutTelefonPejabat,
                OutTelefonJPDP: vm.tp.OutTelefonJPDP,
                OutEmailMB: vm.tp.OutEmailMB,
                OutUpdateTPDate: vm.tp.OutUpdateTPDate,
                ChangeStamp: vm.tp.ChangeStamp
            };

            var tpUpdate = {
                TaxpayerCorrespondence: vm.correspondenceUpdate,
                ChangeHistory: vm.ChangesHistory
            };

            result = TaxPayerSI.UpdatedInOutboundDetails(tpUpdate);
            result.then(function (r) {
                if (!r.status === 200) {
                    swal("Failed", r.data, "error");
                    return;
                }

                swal({
                    title: GeneralService.SaveMessage.Title,
                    text: GeneralService.SaveMessage.Text,
                    type: "success",
                    timer: 2500,
                    showConfirmButton: true
                }, function () {
                    vm.redirectTo('/taxpayer/profile/detail/' + vm.tp.TPID);
                });
            });
        }
        else {
            swal("Failed", "No Changes has been made!", "error");
            var deferred = $q.defer(); // required for click and disabled
            deferred.reject('');
            result = deferred.promise;
        }
        return result;
    }

    function getChangeHistoryActivityCase() {
        // Load ChangeHistory data
        var ajaxCallbackCH = function (data, callback, settings) {

            data.TPID = $window.taxpayerid;
            data.FieldName = vm.FieldName;
            data.DateFrom = vm.DateFrom == undefined ? null : $filter('date')(vm.DateFrom, $scope.DateTimeFormat);
            data.DateTo = vm.DateTo == undefined ? null : $filter('date')(vm.DateTo, $scope.DateTimeFormat);
            data.LastUpdatedBy = vm.LastUpdatedBy;

            TaxPayerSI.getPagedChangeHistory(data).then(function (r) {
                if (r.status == 200) {
                    if (r.data.data) {
                        for (i = 0; i < r.data.data.length; i++) {
                            if (r.data.data[i].OldValue)
                                r.data.data[i].OldValue = r.data.data[i].OldValue.replace(/\n/g, '<br/>');
                            if (r.data.data[i].NewValue)
                                r.data.data[i].NewValue = r.data.data[i].NewValue.replace(/\n/g, '<br/>');
                        }
                    }
                    callback(r.data);
                    //console.log(r);
                }
            });
        }

        //Bind table - start 
        vm.dtColumnsTPChangesHistory = [
            //DTColumnBuilder.newColumn('ID').withTitle('ID'),
            DTColumnBuilder.newColumn('FieldName').withTitle('Nama Medan').withOption('width', '16%'),
            DTColumnBuilder.newColumn('OldValue').withTitle('Maklumat Asal').withOption('width', '27%'),
            DTColumnBuilder.newColumn('NewValue').withTitle('Maklumat Dipinda').withOption('width', '27%'),
            DTColumnBuilder.newColumn('CreatedByName').withTitle('Dikemaskini Oleh').withOption('width', '15%'),
            DTColumnBuilder.newColumn('CreatedDateTime').withTitle('Tarikh Dikemaskini').withOption('width', '15%').renderWith(function (data, type) {
                return $filter('date')(data, $scope.DateTimeFormat);
            })

        ];

        vm.dtOptionsTPChangesHistory = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallbackCH)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('searching', true)
            .withOption('serverSide', true)
            .withOption('autoWidth', false)
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
        //.withColumnFilter({
        //});
        //Bind Table - end

        //Get Activities List
        vm.Kategori1 = {};
        vm.Kategori2 = {};
        vm.Kategori3 = {};
        vm.ActAliran = {};
        vm.ActChn = {};
        vm.ActStatus = {};
        var ajaxCallbackAL = function (data, callback, settings) {
            data.TPID = $window.taxpayerid;
            data.Kategori1ID = !vm.Kategori1 ? "" : vm.Kategori1.Kategori1ID;
            data.Kategori2ID = !vm.Kategori2 ? "" : vm.Kategori2.Kategori2ID;
            data.Kategori3ID = !vm.Kategori3 ? "" : vm.Kategori3.Kategori3ID;
            data.ActChannelID = vm.ActChn == null ? "" : vm.ActChn.ActChannelID;
            data.AliranID = vm.ActAliran == null ? "" : vm.ActAliran.Value;
            data.ActStatusID = vm.ActStatus == null ? "" : vm.ActStatus.Value;

            ActivitySI.getPagedActivityListByID(data).then(function (r) {
                if (r.status == 200) {
                    callback(r.data);
                    //console.log(r.data);
                }
            });
        }

        //Bind table - start 
        vm.dtColumnsActivityList = [
            //DTColumnBuilder.newColumn('ID').withTitle('ID'),
            DTColumnBuilder.newColumn('StatusID').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('ActivityID').withTitle('No. Aktiviti').renderWith(renderActlink).withOption('width', '14%'),
            DTColumnBuilder.newColumn('CaseRefNo').withTitle('No. Kes').renderWith(renderCaselink).withOption('width', '14%'),
            DTColumnBuilder.newColumn('ActChannelName').withTitle('Aktiviti').withOption('width', '10%'),
            // Todo: currently the Aliran icon is hardcoded.
            DTColumnBuilder.newColumn('Aliran').withTitle('Aliran').withOption('width', '8%'),
            //DTColumnBuilder.newColumn('Aliran').withTitle('Aliran'),
            DTColumnBuilder.newColumn('Kategori1Name').withTitle('Kategori').renderWith(renderKategori).withOption('width', '21%'),
            DTColumnBuilder.newColumn('Status').withTitle('Status').withOption('width', '7%'),
            DTColumnBuilder.newColumn('LastUpdatedByName').withTitle('Dikemaskini Oleh').withOption('width', '15%'),
            DTColumnBuilder.newColumn('LastUpdatedDateTime').withTitle('Tarikh Dikemaskini').renderWith(function (data, type) {
                return $filter('date')(data, $scope.DateTimeFormat);
            }).withOption('width', '10%')

        ];

        vm.dtOptionsActivityList = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallbackAL)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('searching', true)
            .withOption('serverSide', true)
            .withOption('autoWidth', false)
            .withOption('order', [5, 'asc'])
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
        //Bind Table - end

        function renderActlink(data, type, row, meta) {
            return '<a href="/Activity/Profile/detail/' + row.ActivityID + '" target="_blank">' + row.ActRefNo + '</a>';

        }

        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' || !row.CaseRefNo)
                link = '-';
            return link
        }

        function renderAliran(data, type, row, meta) {
            var link = '';
            switch (row.ActChannelID) {
                case (2)://email
                    if (row.HCLEmailBlastID > 0)
                        link = '<a title="HCL Email Blast ID" href="/Outbound/Profile/detail/' + row.HCLEmailBlastID + '" target="_blank"> ' + row.HCLEmailBlastID + '</a>' //todo when profile available
                    break;
                case (5)://phone
                    if (row.OutboundID > 0)
                        link = '<a title="Outbound ID" href="/HCLEmailBlast/Profile/detail/' + row.OutboundID + '" target="_blank"> ' + row.OutboundID + '</a>' //todo when profile available
                    break;
            }

            return data == 'Masuk' ? ' <span class="arrow" style="padding:5px;"><i style="transform:rotate(-45deg)" class="fa fa-arrow-down"  title="Masuk"></i></span>'
                : '<span class="arrow outboundArrow" style="padding:5px;"> <i style = "transform:rotate(-45deg)" class="fa fa-arrow-up" title="Keluar"></i>' + link + '</span>';
        }

        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.dtOptionsActivityList = DTOptionsBuilder.newOptions()
        //.withOption('ajax', ajaxCallbackAL)
        //.withDataProp('data')
        //.withOption('processing', true)
        //.withOption('searching', true)
        //.withOption('serverSide', true)
        //.withPaginationType('full_numbers')
        //.withDisplayLength(10);
        function renderStatus(data, type, row, meta) {
            var statusDesc = '';
            if (row.StatusLevel1Name != '' && row.StatusLevel1Name != undefined)
                statusDesc += '<ul class="list-inline"><li><b>' + row.StatusLevel1Name + ' </b></li>';
            if (row.StatusLevel2Name != '' && row.StatusLevel2Name != undefined)
                statusDesc += '<li class="arrow-separator" style="font-size:0.785em;"><b> ' + row.StatusLevel2Name + ' </b></li>';
            if (row.StatusLevel3Name != '' && row.StatusLevel3Name != undefined)
                statusDesc += '<li class="arrow-separator" style="font-size:0.785em;"><span> ' + row.StatusLevel3Name + '</span></li>';
            if (statusDesc != '')
                statusDesc = statusDesc + '</ul >';

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

            return label;
        }

        //Bind Table - end

        //Get Case List
        vm.Kategori1Case = {};
        vm.Kategori2Case = {};
        vm.Kategori3Case = {};

        var ajaxCallbackCL = function (data, callback, settings) {
            data.TPID = $window.taxpayerid;

            data.Kategori1IDCase = !vm.Kategori1Case ? "" : vm.Kategori1Case.Kategori1ID;
            data.Kategori2IDCase = !vm.Kategori2Case ? "" : vm.Kategori2Case.Kategori2ID;
            data.Kategori3IDCase = !vm.Kategori3Case ? "" : vm.Kategori3Case.Kategori3ID;

            CaseSI.getPagedCaseListByID(data).then(function (r) {
                if (r.status == 200) {
                    callback(r.data);
                    //console.log(r.data);
                }
            });
        }

        //Bind table - start 
        vm.dtColumnsCaseList = [
            //DTColumnBuilder.newColumn('ID').withTitle('ID'),
            DTColumnBuilder.newColumn('StatusLevel1ID').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('CaseID').withTitle('No. Kes').renderWith(renderCaselink).withOption('width', '14%'),
            //DTColumnBuilder.newColumn('CaseRefNo').withTitle('Case Ref No.').renderWith(renderCaselink),
            DTColumnBuilder.newColumn('Kategori1Name').withTitle('Kategori').renderWith(renderKategori).withOption('width', '22%'),
            // Todo: currently the Aliran icon is hardcoded.
            DTColumnBuilder.newColumn('Aliran').withTitle('Aliran').withOption('width', '5%'),
            //DTColumnBuilder.newColumn('Aliran').withTitle('Aliran'),
            DTColumnBuilder.newColumn('JenisKempenName').withTitle('Kempen').withOption('width', '10%').renderWith(renderNullAsDash),
            DTColumnBuilder.newColumn('StatusLevel1Name').withTitle('Status').renderWith(renderStatus).withOption('width', '22%'),
            //DTColumnBuilder.newColumn('StatusLevel2Name').withTitle('Status Level 2'),
            //DTColumnBuilder.newColumn('StatusLevel3Name').withTitle('Status Level 3'),
            DTColumnBuilder.newColumn('LastUpdatedByName').withTitle('Dikemaskini Oleh').withOption('width', '13%'),
            DTColumnBuilder.newColumn('LastUpdatedDateTime').withTitle('Tarikh Dikemaskini').renderWith(function (data, type) {
                return $filter('date')(data, $scope.DateTimeFormat);
            }).withOption('width', '12%'),

        ];

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

        vm.dtOptionsCaseList = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallbackCL)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('searching', true)
            .withOption('serverSide', true)
            .withOption('defaultContent', '-')
            .withPaginationType('full_numbers')
            .withOption('autoWidth', false)
            .withDisplayLength(10);
        //Bind Table - end

    }

    vm.dtInstanceTPChangesHistory = {};

    //Search TP
    vm.searchTP = function () {

        vm.blnValid = true;
        vm.showErrCreatedDate = false;
        vm.ErrMsgCreatedDate = "";
        var d = new Date(vm.DateFrom);
        var dt = new Date(vm.DateTo);

        if ((!vm.DateFrom && vm.DateTo) ||
            (vm.DateFrom && !vm.DateTo)) {
            vm.ErrMsgCreatedDate = "Banjaran tarikh tidak sah.";
            vm.showErrCreatedDate = true;
            vm.blnValid = false;
        }
        if (d > dt) {
            //console.log("1")
            vm.ErrMsgCreatedDate = "Date To must be greater than Date From.  ";
            //console.log(vm.ErrMsgCreatedDate)
            vm.showErrCreatedDate = true;
            vm.blnValid = false;
        }

        if (vm.blnValid) {
            vm.showErrCreatedDate = false;
            vm.ErrMsgCreatedDate = "";
            vm.dtInstanceTPChangesHistory.reloadData();
        }
    }

    vm.clear = function () {
        vm.DateFrom = null;
        vm.DateTo = null;
        vm.FieldName = '';
        vm.showErrCreatedDate = false;
        vm.ErrMsgCreatedDate = "";
        vm.blnValid = true;
        vm.LastUpdatedBy = '';
    }

    vm.actKategori1Changed = function (kategori1ID) {
        vm.Kategori2 = {};
        vm.Kategori3 = {};
        vm.Kategori3Options = {};

        if (!kategori1ID) {
            vm.Kategori2Options = {};
        }
        else {
            var m = $filter('filter')(vm.MainKategoriOptions, { Kategori1ID: kategori1ID }, true);
            if (m.length != 0) {
                vm.Kategori2Options = m[0].SubKategori;
            }
            else {
                vm.Kategori2Options = {};
            }
        }
    };

    vm.actKategori2Changed = function (kategori2ID) {
        vm.Kategori3 = {};
        vm.Kategori3Options = null;

        var m = $filter('filter')(vm.Kategori2Options, { Kategori2ID: kategori2ID }, true);
        if (m.length != 0) {
            vm.Kategori3Options = m[0].InnerSubKategori;
        }
        else {
            vm.Kategori3Options = {};
        }
    };

    //Search ActivityList
    vm.dtInstanceActivityList = {};

    vm.searchAL = function () {

        vm.blnValid = true;

        if (vm.blnValid) {
            vm.dtInstanceActivityList.reloadData();
        };
    }

    vm.clearAL = function () {
        if (vm.Kategori1) vm.Kategori1.Kategori1ID = '';
        if (vm.Kategori2) vm.Kategori2.Kategori2ID = '';
        if (vm.Kategori3) vm.Kategori3.Kategori3ID = '';
        vm.Kategori2Options = {};
        vm.Kategori3Options = {};
        if (vm.ActChn) vm.ActChn.ActChannelID = '';
        vm.ActAliran = '';
        vm.ActStatus = '';

    }

    //Search CaseList
    vm.dtInstanceCaseList = {};

    vm.searchCL = function () {
        vm.blnValid = true;
        //console.log(vm);
        if (vm.blnValid) {
            vm.dtInstanceCaseList.reloadData();
        };
    }

    vm.clearcaseCL = function () {
        if (vm.Kategori1Case) vm.Kategori1Case.Kategori1ID = '';
        if (vm.Kategori2Case) vm.Kategori2Case.Kategori2ID = '';
        if (vm.Kategori3Case) vm.Kategori3Case.Kategori3ID = '';
        vm.Kategori2OptionsCase = {};
        vm.Kategori3OptionsCase = {};
    }

    vm.caseKategori1Changed = function (kategori1IDCase) {
        vm.Kategori2Case = {};
        vm.Kategori3Case = {};
        vm.Kategori3OptionsCase = {};

        if (!kategori1IDCase) {
            vm.Kategori2OptionsCase = {};
        }
        else {
            var m = $filter('filter')(vm.MainKategoriOptions, { Kategori1ID: kategori1IDCase }, true);
            if (m.length != 0) {
                vm.Kategori2OptionsCase = m[0].SubKategori;
            }
            else {
                vm.Kategori2OptionsCase = {};
            }
        }
    };

    vm.caseKategori2Changed = function (kategori2IDCase) {
        vm.Kategori3Case = {};
        vm.Kategori3OptionsCase = null;

        var m = $filter('filter')(vm.Kategori2OptionsCase, { Kategori2ID: kategori2IDCase }, true);
        if (m.length != 0) {
            vm.Kategori3OptionsCase = m[0].InnerSubKategori;
        }
        else {
            vm.Kategori3OptionsCase = {};
        }
    };

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

    //Download Addtional Info
    vm.ShowRetrieveDataDetail = function () {
        var result = null;
        vm.LoadingAdditionalData = true;
        var data = {
            NoCukaiSTS: vm.tp.NoCukaiSTS,
            NoCukaiCode: vm.tp.NoCukaiCode,
            FileTypeID: vm.tp.FileTypeID,
            EmplFileTypeID: vm.tp.EmplFileTypeID,
            EmplNoCukaiSTS: vm.tp.EmplNoCukaiSTS
        };
        result = TaxPayerSI.getAdditionalDataByTP(data);
        TaxPayerSI.getAdditionalDataByTP(data).then(function (r) {
            console.log("addtional data");
            console.log(r.data);
            vm.TPAdditionalData = r.data;
            vm.DownloadAdditionalData = true;
        }, function (r) {
            returnResult();
        }).finally(function () {
            vm.LoadingAdditionalData = false;
        });

        return result;
    }
    //Download Addtional Info

    vm.DownloadRingkasanBayBalik = function () {
        vm.LoadingRingkasanBayBalik = true;
        var data = {
            NoCukaiSTS: vm.tp.NoCukaiSTS,
            NoCukaiCode: vm.tp.NoCukaiCode
        };

        TaxPayerSI.getRingkasanBayaranBalikTP(data).then(function (r) {
            console.log("RingkasanBayaranBalik data");
            console.log(r.data);
            vm.TPRingkasanBayaranBalik = r.data;
            vm.RingkasanBayarBalikInfo = true;

        }).finally(function () {
            vm.LoadingRingkasanBayBalik = false;
        });
    }

    vm.DownloadStatusBayBalik = function () {
        vm.LoadingStatusBayBalik = true;
        var data = {
            NoCukai: vm.tp.NoCukai,
            NoCukaiCode: vm.tp.NoCukaiCode
        };

        TaxPayerSI.getStatusBayaranBalikbyTP(data).then(function (r) {
            console.log("getStatusBayaranBalikbyTP data");
            console.log(r.data);
            vm.TPStatusBayarBalik = r.data;
            vm.StatusBayBalikInfo = true;

        }).finally(function () {
            vm.LoadingStatusBayBalik = false;
        });

    }

 

    vm.DownloadCP = function () {
        vm.LoadingPungutanCP = true;
        var data = {
            NoCukaiSTS: vm.tp.NoCukaiSTS,
            NoCukaiCode: vm.tp.NoCukaiCode
        };

        TaxPayerSI.getPungutanCPbyTP(data).then(function (r) {
            console.log("PungutanCP data");
            console.log(r.data);
            vm.TPPungutanCP = r.data;
            vm.PungutanCPDetail = true;

        }).finally(function () {
            vm.LoadingPungutanCP = false;
        });
    }

    vm.DownloadCKHT = function () {
        vm.LoadingPungutanCKHT = true;
        var data = {
            NoCukaiSTS: vm.tp.NoCukaiSTS,
            NoCukaiCode: vm.tp.NoCukaiCode
        };

        TaxPayerSI.getPungutanCKHTbyTP(data).then(function (r) {
            console.log("PungutanCP data");
            console.log(r.data);
            vm.TPPungutanCKHT = r.data;
            vm.PungutanCKHTDetail = true;

        }).finally(function () {
            vm.LoadingPungutanCKHT = false;
        });

    }

    vm.DownloadAnsuran = function () {
        vm.LoadingAnsuran = true;
        var data = {
            NoCukaiSTS: vm.tp.NoCukaiSTS,
            NoCukaiCode: vm.tp.NoCukaiCode
        };

        TaxPayerSI.getAllAnsuranByTP(data).then(function (r) {
            console.log("Ansuran data");
            console.log(r.data);
            vm.AnsuranList = r.data; 
        }).finally(function () {
            vm.LoadingAnsuran = false;
        });
    }

    vm.DownloadAnggaran = function () {
        vm.LoadingAnggaran = true;
        var data = {
            NoCukaiSTS: vm.tp.NoCukaiSTS,
            NoCukaiCode: vm.tp.NoCukaiCode,
            FileTypeID: vm.tp.FileTypeID
        };

        TaxPayerSI.getAllAnggaranByTP(data).then(function (r) {
            console.log("Anggaran data");
            console.log(r.data);
            vm.AnggaranList = r.data;
        }).finally(function () {
            vm.LoadingAnggaran = false;
        });
    }

    vm.DownloadKawalBorang = function () {
        vm.LoadingKawalBorang = true;
        var data = {
            NoCukaiSTS: vm.tp.NoCukaiSTS,
            NoCukaiCode: vm.tp.NoCukaiCode
        };

        TaxPayerSI.getKawalBorangDataByTP(data).then(function (r) {
            console.log("DownloadKawalBorang data");
            console.log(r.data);
            vm.TPKawalTerimaBorang = r.data;
            vm.KawalTerimaBorangInfo = true;
        }).finally(function () {
            vm.LoadingKawalBorang = false;
        });
    }

    vm.DownloadRingkasanTaksiran = function () {
        vm.LoadingRingkasanTaksiran = true;
        var data = {
            NoCukaiSTS: vm.tp.NoCukaiSTS,
            NoCukaiCode: vm.tp.NoCukaiCode
        };

        TaxPayerSI.getRingkasanTaksiranByTP(data).then(function (r) {
            console.log("RingkasanTaksiran data");
            console.log(r.data);
            vm.TPRingkasanTaksiran = r.data;
            vm.RingkasanTaksiranInfo = true;
        }).finally(function () {
            vm.LoadingRingkasanTaksiran = false;
        });

    }

    vm.DownloadRingkasanLejer = function () {
        vm.LoadingRingkasanLejer = true;
        var data = {
            NoCukaiSTS: vm.tp.NoCukaiSTS,
            NoCukaiCode: vm.tp.NoCukaiCode
        };

        TaxPayerSI.getRingkasanLejerByTP(data).then(function (r) {
            console.log("Lejer data");
            console.log(r.data);
            vm.TPRingkasanLejer = r.data;
            //vm.TPRingkasanLejer = $filter('filter')(r.data, function (o) {
            //    for (var i = 0; i < vm.JenisLejarOptions.length; i++) {
            //        if (vm.JenisLejarOptions[i].Text = o.JenisLejer) {
            //            return true;
            //        }
            //    }
            //    return false;
            //});
            vm.RingkasanLejarInfo = true;
        }).finally(function () {
            vm.LoadingRingkasanLejer = false;
        });
    }

    

    vm.lejerFilter = function (criteria,strOptionType) {

        return function (o) {
            var isTrue =true;
            if (criteria) {
                if (vm.LejerProperty == 'TahunTaksiran') {
                    isTrue = o.TahunTaksiran == criteria.Year || !criteria.Year;
                }
                if (vm.LejerProperty == 'TahunKalendar') {
                    isTrue = o.TahunKalendar == criteria.Year || !criteria.Year;
                }

                if (strOptionType !='JenisLejer')
                    isTrue = isTrue && (!criteria.JenisLejer || o.JenisLejer == criteria.JenisLejer)
            }
            return isTrue;
        }
    }
    
    vm.DownloadLejerTerperinci = function () {
        vm.LoadingLejerTerperinci = true;
        var data = {
            NoCukaiSTS: vm.tp.NoCukaiSTS,
            NoCukaiCode: vm.tp.NoCukaiCode
        };
       
        vm.OptionsQuery = {};
        vm.OptionsQuery.LejerTerperinciYear = "item[tax.LejerProperty] as item[tax.LejerProperty]  for item in tax.TPLejerTerperinci | unique: tax.LejerProperty";
        TaxPayerSI.getLejerDataByTP(data).then(function (r) {
            console.log("Lejer data");
            console.log(r.data);
            vm.TPLejerTerperinci = r.data;
            //vm.LejerTahunOptions = [];
            //vm.JenisLejarTerperinciOptions = [];
            vm.lejerCriteria = {};
            vm.LejerProperty = 'TahunTaksiran';
            if (vm.TPLejerTerperinci && vm.TPLejerTerperinci.length>0)
                vm.lejerCriteria.Year = vm.TPLejerTerperinci[0].TahunTaksiran;
            //if (vm.TPLejerTerperinci) {
            //    for (var i = 0; i < vm.TPLejerTerperinci.length; i++) {
            //        if (vm.LejerTahunOptions.indexOf(vm.TPLejerTerperinci[i].TahunTaksiran) == -1)
            //            vm.LejerTahunOptions.push(vm.TPLejerTerperinci[i].TahunTaksiran);

            //        var m = $filter('filter')(vm.JenisLejarTerperinciOptions, { Value: vm.TPLejerTerperinci[i].JenisLejer }, true);
            //        if (!m || m.length < 0)
            //        {
            //            vm.JenisLejarTerperinciOptions.push({
            //                Value: vm.TPLejerTerperinci[i].JenisLejer,
            //                Text: vm.TPLejerTerperinci[i].JenisLejerDecs,
            //                AsmYear: vm.TPLejerTerperinci[i].TahunTaksiran,
            //                CalenderYear: vm.TPLejerTerperinci[i].TahunKalendar
            //            })
            //        }

            //    }
            //}
            vm.LejerTerperinciInfo = true;
        }).finally(function () {
            vm.LoadingLejerTerperinci = false;
        });

    }
     

    //Search OutboundList
    vm.dtInstanceOCL = {};

    vm.searchOutboundList = function () {
        vm.blnValid = true;

        if (vm.blnValid) {
            vm.dtInstanceOCL.reloadData();
        };
    }

    vm.clearCL = function () {
        if (vm.JenisKempenID != null) vm.JenisKempenID = '';
        if (vm.JenisCampaignID != null) vm.JenisCampaignID = '';
        vm.Tahun = '';
        vm.JenisOCLCukai = '';
    }

    vm.makeCall = function (callNo) {
        //todo: insert localstorage item
        if (typeof InteractionHelper !== "undefined") {

            swal({
                title: "Adakah anda pasti untuk menghubungi nombor ini?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Ya",
                cancelButtonText: "Tidak",
                closeOnConfirm: true,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    callNo = callNo.replace('-', '');
                    InteractionHelper.CreateOutboundCall({
                        ID: ((new Date()).getTime() * 10000) + 621355968000000000,
                        callNo: callNo.replace(/\s/g, ''),
                        IDType: vm.tp.CCIDTypeCode,
                        IDNo: vm.tp.IdentityNo
                    });
                }
                else
                {
                    swal("Batal!", "Panggilan telah dibatalkan.", "error");
                }
            });
      
        }
    }
    // datepicker
    vm.openDateFrom = function () {
        vm.dateFromOpened = true;
    };

    vm.openDateTo = function () {
        vm.dateToOpened = true;
    };

    vm.clearDateFrom = function () {
        vm.DateFrom = null;
    };
    vm.clearDateTo = function () {
        vm.DateTo = null;
    };
}


