crmApp.controller("OutboundController", OutboundController);

function OutboundController($scope, $window, $filter, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, OutboundSI, TaxPayerSI, ActivitySI, AntiForgeryService, TaxPayerService, GeneralService, OutboundService, $mdDialog) {
    var vm = this;
    var TabID = "01";
    var TabType = "Profile";
    /**Initialise**/
    vm.hdrTempl = 'loading';
    vm.changesHistory = [];
    vm.dtInstanceOutboundChangesHistory = {};
    /**Initialise End **/

    /**From $window **/
    vm.jenisKempenId = $window.jeniskempenid;
    vm.dataId = $window.dataid
    /**From $window End **/

    /**Constants**/
    vm.constMaklumatAnsuran = 23;
    vm.constMaklumatTunggakan = 24;
    vm.constMaklumatCTL = 25;

    vm.constStatusReturnReject = 28;
    vm.constStatusVerified = 39;
    vm.constStatusScheduled = 29;
    /**Constants End **/

    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;

    vm.Validation = {};
    vm.Validation.Money = GeneralService.Validation.Money15;
    vm.Validation.MoneyMsg = GeneralService.Validation.MoneyMsg;

    vm.Validation.Email = GeneralService.Validation.Email;
    vm.Validation.EmailMsg = GeneralService.Validation.EmailMsg;

    vm.Validation.Phone = GeneralService.Validation.Phone;
    vm.Validation.PhoneMsg = GeneralService.Validation.PhoneMsg;
    /*On page load functions */
    vm.init = function () {
        // datepicker
        vm.dateFromMinDate = null;
        vm.dateFromMaxDate = null;
        vm.buttonBarObj = $scope.ButtonBar;

        vm.dateFromOptions = {
            minDate: null, // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            dateDisabled: false,
            startingDay: 1
        };

        vm.dateToMinDate = null;
        vm.dateToMaxDate = null;
        vm.dateToOptions = {
            minDate: null, // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            dateDisabled: false,
            startingDay: 1
        };

        vm.outboundDateOptions = {
            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
        };

        var querystring = location.search;
        if (querystring) {
            TabID = querystring.substring(querystring.indexOf("=") + 1, querystring.indexOf("&"));
            TabType = querystring.substring(querystring.lastIndexOf("=") + 1, querystring.length);
        }
        tabAction(TabID, TabType);
        vm.hdrTempl = 'tp.profile.header';

        if (vm.jenisKempenId && vm.dataId) {
            var model = {
                JenisKempenID: vm.jenisKempenId,
                DataID: vm.dataId
            };

            OutboundSI.getDropdown(false).then(function (r) {
                for (var key in r.data) {
                    vm[key] = r.data[key];
                }
                console.log("vm", vm);

            });

            OutboundSI.getOutboundDetails(model).then(function (r) {
                vm.outbound = r.data;
                if (vm.outbound.TP)
                    bindHeader(vm.outbound.TP);
                else {
                    objTP = {
                        NoCukaiCode: vm.outbound["FILE_TYPE"],
                        NoCukai: vm.outbound["NoCukai"],
                        TPName: vm.outbound["TAX_PAYER_NAME1"]
                    }

                    bindHeader(objTP);
                }


                OutboundService.init(vm.outbound);

                //CDL
                vm.outbound.UsiaData = OutboundService.Tunggakan.UsiaData;
                vm.outbound.UsiaDebit = OutboundService.Tunggakan.UsiaDebit;

                //Ansuran Datatable
                vm.outbound.AnsuranList = OutboundService.Ansuran.AnsuranList;

                console.log("vm.outbound", vm.outbound);

                formatFieldValues();
                vm.KodSelesaiReturnDesc = vm.outbound.KodSelesaiReturnDesc;
                vm.ReturnReasonOptions = vm.outbound.ReturnedReasonOptions;
            });
        }

        getChangeHistoryAndActivity();
        angular.element($window).on('beforeunload', onbeforeunload);
    }
    /*On page load functions END */

    /*Tab functions*/
    vm.tabAction = tabAction;
    function tabAction(cls, type) {
        TabID = cls;
        TabType = type;
        reset();
        switch (cls) {
            case '01':
                type == "Profile" ? tabProfile01Click() : tabServices01Click();
                break;
            case '02':
                type == "Profile" ? tabProfile01Click() : tabServices02Click();
                break;
        }
    }

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

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

    //Profile Tab 01
    vm.tabProfile01Click = tabProfile01Click;
    function tabProfile01Click() {
        vm.IsProfileTab = vm.tabProfile01Active = 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);
    }

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

        // Set Table visibility
        vm.tabProfile01Active = false;

        vm.tabServices01Active = false;
        vm.tabServices02Active = false;
    }
    /*Tab functions END*/

    function bindHeader(objTP) {
        TaxPayerService.TP.AllowEdit = false;
        TaxPayerService.TP.TPID = objTP.TPID;
        TaxPayerService.TP.Name = objTP.TPName;
        TaxPayerService.TP.TPType = objTP.JenisPengenalan || objTP.TPJenisPengenalan;
        TaxPayerService.TP.IDNo = objTP.TPIDNumber || objTP.IdentityNo;
        TaxPayerService.TP.FileType = objTP.FileType;
        TaxPayerService.TP.TaxNo = objTP.NoCukai || objTP.TPNoCukai;
        TaxPayerService.TP.NoCukaiCode = objTP.TPID ? objTP.NoCukaiCode : null;
        TaxPayerService.TP.StatusFail = objTP.StatusFail;
        TaxPayerService.TP.StatusFailPendua = objTP.StatusFailPendua;
        TaxPayerService.TP.GelaranName = objTP.GelaranName;
        TaxPayerService.TP.HonorificName = objTP.HonorificName;
        TaxPayerService.CWNG.PungutanCP = objTP.CWPungutanCP;
        TaxPayerService.CWNG.PungutanCKHT = objTP.CWPungutanCKHT;
        TaxPayerService.CWNG.PenaksiranCP = objTP.CWPenaksiranCP;
        TaxPayerService.CWNG.PenaksiranCKHT = objTP.CWPenaksiranCKHT;
        TaxPayerService.CWNG.GuamanSivil = objTP.CWGuamanSivil;

        if (!objTP.TPID)
            TaxPayerService.TP.TaxNo = objTP.NoCukaiCode + " " + objTP.NoCukai || objTP.NoCukaiCode + " " + objTP.TPNoCukai;
    }

    function getChangeHistoryAndActivity() {
        //Change History
        var ajaxCallbackCH = function (data, callback, settings) {

            data.ReMSDataID = $window.dataid;
            data.JenisKempenID = $window.jeniskempenid;
            data.FieldName = vm.FieldName;
            data.DateFrom = undefined ? null : $filter('date')(vm.DateFrom, $scope.DateTimeFormat);
            data.DateTo = undefined ? null : $filter('date')(vm.DateTo, $scope.DateTimeFormat);
            data.LastUpdatedBy = vm.LastUpdatedBy;

            TaxPayerSI.getPagedChangeHistory(data).then(function (r) {
                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);
            });
        }

        //Bind table - start 
        vm.dtColumnsOutboundChangesHistory = [
            //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.dtOptionsOutboundChangesHistory = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallbackCH)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('searching', true)
            .withOption('serverSide', true)
            .withOption('autoWidth', false)
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
        //Bind Table - end

        //Activities List
        vm.Kategori1Act;
        vm.Kategori2Act;
        vm.ActAliran = {};
        vm.ActChn = {};
        vm.ActStatus = {};

        var ajaxCallbackAL = function (data, callback, settings) {
            data.ReMSDataID = $window.dataid;
            data.JenisKempenID = $window.jeniskempenid;
            data.Kategori1ID = !vm.Kategori1Act ? "" : vm.Kategori1Act.Kategori1ID;
            data.Kategori2ID = !vm.Kategori2Act ? "" : vm.Kategori2Act.Kategori2ID;
            data.Kategori3ID = !vm.Kategori3Act ? "" : vm.Kategori3Act.Kategori3ID;
            data.ActChannelID = !vm.ActChn ? "" : vm.ActChn.ActChannelID;
            data.AliranID = !vm.ActAliran ? "" : vm.ActAliran.Value;
            data.ActStatusID = !vm.ActStatus ? "" : vm.ActStatus.Value;
            data.TPID = TaxPayerService.TP.TPID;
            ActivitySI.getPagedActivityListByID(data).then(function (r) {
                if (!vm.firstActivityID) {
                    var m = $filter('orderBy')(r.data.data, 'ActivityID');
                    if (m && m.length > 0) {
                        vm.firstActivityID = m[0].ActivityID;
                    }
                }
                callback(r.data);
            });
        }

        //Bind table - start 
        vm.dtColumnsActivityList = [
			//DTColumnBuilder.newColumn('ID').withTitle('ID'),
			DTColumnBuilder.newColumn('StatusID').notSortable().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').renderWith(renderAliran).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%')

        ];

        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)
                link = '-';
            return link
        }

        function renderAliran(data, type, row, meta) {
            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></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('autoWidth', false)
            .withOption('searching', true)
            .withOption('serverSide', true)
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
        //Bind Table - end
    }

    /* Search Change History */
    vm.searchOutboundChangeHistory = 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) {
            vm.ErrMsgCreatedDate = "Date To must be greater than Date From.  ";
            vm.showErrCreatedDate = true;
            vm.blnValid = false;
        }

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

    vm.clear = function () {
        vm.DateFrom = null;
        vm.DateTo = null;
        vm.FieldName = '';
        vm.LastUpdatedBy = '';
        vm.showErrCreatedDate = false;
        vm.ErrMsgCreatedDate = "";
        vm.blnValid = true;
    }
    /* Search Change History END*/

    /*Search Activity List*/
    vm.dtInstanceActivityList = {};

    vm.searchAL = function () {

        vm.blnValid = true;

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

    }

    vm.clearAL = function () {
        if (vm.Kategori1Act) vm.Kategori1Act.Kategori1ID = '';
        if (vm.Kategori2Act) vm.Kategori2Act.Kategori2ID = '';
        if (vm.Kategori3Act) vm.Kategori3Act.Kategori3ID = '';
        vm.Kategori2Options = {};
        vm.Kategori3Options = {};
        if (vm.ActChn) vm.ActChn.ActChannelID = '';
        vm.ActAliran = '';
        vm.ActStatus = '';

    }

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

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

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

        var m = $filter('filter')(vm.Kategori2Options, { Kategori2ID: kategori2IDAct }, true);
        if (m.length != 0) {
            vm.Kategori3Options = m[0].InnerSubKategori;
        }
        else {
            vm.Kategori3Options = {};
        }
    };
    /*Search Activity List END*/

    function onbeforeunload(e) {

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

    vm.redirectTo = function (url) {

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

    vm.saveOutboundDetails = function (makReMSForm) {
        var isDirty = makReMSForm.$dirty;
        if (makReMSForm.$valid) {
            if (isDirty) {
                getChangeHistory();
                updateOutboundDetails();
            }
            else {
                swal("Failed", "No Changes has been made!", "error");
            }
        } else {
            swal("Failed", "Form contains invalid field value(s), please check and try again.", "error");
        }
    }

    function updateOutboundDetails(isVerify) {
        var outboundDetailsModel = angular.copy(vm.outbound);

        model = {
            OutboundDetails: outboundDetailsModel,
            ChangeHistory: vm.changesHistory
        };

        if (isVerify) {
            model.blnIsVerify = true;
        }

        model = consolidateBeforeSave(model);

        switch (vm.outbound.JenisKempenDetails.JenisKempenKategoriSysID) {
            case (vm.constMaklumatAnsuran):
                var data = OutboundSI.updateOutboundDetailsAnsuran(model);
                data.then(function (r) {
                    swal({
                        title: GeneralService.SaveMessage.Title,
                        text: GeneralService.SaveMessage.Text,
                        type: "success",
                        timer: 2500,
                        showConfirmButton: true
                    }, function () {
                        vm.redirectTo('/Outbound/Profile/Detail/' + $window.jeniskempenid + '/' + $window.dataid + '?t=' + TabID + '&ty=' + TabType);
                    });
                });
                break;
            case (vm.constMaklumatTunggakan):
                var data = OutboundSI.updateOutboundDetailsTunggakan(model);
                data.then(function (r) {
                    swal({
                        title: GeneralService.SaveMessage.Title,
                        text: GeneralService.SaveMessage.Text,
                        type: "success",
                        timer: 2500,
                        showConfirmButton: true
                    }, function () {
                        vm.redirectTo('/Outbound/Profile/Detail/' + $window.jeniskempenid + '/' + $window.dataid + '?t=' + TabID + '&ty=' + TabType);
                    });
                });
                break;
            case (vm.constMaklumatCTL):
                var data = OutboundSI.updateOutboundDetailsCTL(model);
                data.then(function (r) {
                    swal({
                        title: GeneralService.SaveMessage.Title,
                        text: GeneralService.SaveMessage.Text,
                        type: "success",
                        timer: 2500,
                        showConfirmButton: true
                    }, function () {
                        vm.redirectTo('/Outbound/Profile/Detail/' + $window.jeniskempenid + '/' + $window.dataid + '?t=' + TabID + '&ty=' + TabType);
                    });
                });
                break;
        }
    };

    vm.saveVerifyData = function (makReMSForm) {
        var isDirty = makReMSForm.$dirty;
        if (makReMSForm.$valid) {
            if (isDirty) {
                swal({
                    title: "Adakah anda pasti untuk sahkan data ini? ",
                    text: "",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonText: "Ya",
                    cancelButtonText: "Tidak",
                    closeOnConfirm: false,
                    closeOnCancel: false
                }, function (isConfirm) {
                    if (isConfirm) {
                        getChangeHistory();
                        updateOutboundDetails(true);
                    }
                    else {
                        swal("Tindakan Pengesahan Data Dibatalkan!", null, "error");
                    }
                });
            }
            else {
                model = {
                    DataID: vm.dataId,
                    JenisKempenID: vm.jenisKempenId
                };

                swal({
                    title: "Adakah anda pasti untuk sahkan data ini? ",
                    text: "",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonText: "Ya",
                    cancelButtonText: "Tidak",
                    closeOnConfirm: false,
                    closeOnCancel: false
                }, function (isConfirm) {
                    if (isConfirm) {
                        var data = OutboundSI.verifyOutboundData(model);
                        data.then(function (r) {
                            swal({
                                title: "Data Disahkan!",
                                //text: GeneralService.SaveMessage.Text,
                                type: "success",
                                timer: 2500,
                                showConfirmButton: true
                            }, function () {
                                vm.redirectTo('/Outbound/Profile/Detail/' + $window.jeniskempenid + '/' + $window.dataid + '?t=' + TabID + '&ty=' + TabType);
                            });
                        });
                    }
                    else {
                        swal("Tindakan Pengesahan Data Dibatalkan!", null, "error");
                    }
                });

            }
        } else {
            swal("Failed", "Form contains invalid field value(s), please check and try again.", "error");
        }

        vm.showValidationMsg = true;
    }


    vm.rejectData = function (isValidReturnForm) {
        if (!isValidReturnForm) {
            swal("Failed", "Please select Return Reason.", "error");
            return;
        }

        swal({
            title: "Are you sure you want to return data to ReMS?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                vm.close();
                model = {
                    DataID: vm.dataId,
                    JenisKempenID: vm.jenisKempenId,
                    ReturnReasonID: vm.returnReasonID
                };

                var data = OutboundSI.rejectOutboundData(model);
                data.then(function (r) {
                    swal({
                        title: GeneralService.SaveMessage.Title,
                        text: GeneralService.SaveMessage.Text,
                        type: "success",
                        timer: 2500,
                        showConfirmButton: true
                    }, function () {
                        vm.redirectTo('/Outbound/Profile/Detail/' + $window.jeniskempenid + '/' + $window.dataid + '?t=' + TabID + '&ty=' + TabType);
                    });
                });
            }
            else {
                swal("Cancelled", "Request cancelled.", "error");
            }
        });
    }

    function consolidateBeforeSave(model, isVerify) {
        arrDate = [
        /*Ansuran*/
        , "ACCOUNT_START_DATE"
        , "ACCOUNT_END_DATE"
        , "AMEN_SHED_DATE"
        , "MIN_DUE_DATE"
        , "SKIM_DATE"
        , "TarikhKenaBayar"
        /*Tunggakan*/
        , "ASSESSMENT_DATE"
        , "PAYMENT_DUE_DATE"
        , "PINK_LETTER_DATE"
        /*CTL*/
        , "CTL_DATE"
        , "DATE_BANK_IN"
        , "DATE_BANK_INVALID"
        , "DATE_CEK_ACCEPT"
        ]

        for (i = 0; i < arrDate.length; i++) {
            console.log('name : ' + arrDate[i]);
            console.log(model.OutboundDetails[arrDate[i]]);
            model.OutboundDetails[arrDate[i]] = $filter('date')(model.OutboundDetails[arrDate[i]], $scope.DateTimeFormat);//new Date(model.OutboundDetails[arrDate[i]]);//moment(model.OutboundDetails[arrDate[i]], $scope.DateTimeFormat).toDate();
            console.log(model.OutboundDetails[arrDate[i]]);
        }

        return model;
    }


    function getChangeHistory() {
        angular.forEach($scope.makReMSForm, function (value, key) {
            if (key[0] == '$') return;

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

            if (value.$pristine == false) {
                var newvalue = value.$viewValue;

                vm.changesHistory.push({
                    ID: $window.dataid,
                    RefID: $window.jeniskempenid,
                    FieldName: key,
                    DisplayName: displayName,
                    OldValue: '',
                    NewValue: newvalue,
                    IsChanged: !value.$pristine
                });
            }
        });
    };

    /*Private Other Functions*/
    function formatFieldValues() {
        arrNumber = [
        /*Ansuran*/
        "TOTAL_AMOUNT"
        , "JUM_PERLU_BYR"
        , "MAX_DUE_AMOUNT"
        /*Tunggakan*/
        , "ASSESSMENT_AMOUNT"
        , "SUM_BAL"
        , "PINK_LETTER_AMT"
        /*CTL*/
        , "CEK_AMOUNT"
        ]

        for (i = 0; i < arrNumber.length; i++)
            vm.outbound[arrNumber[i]] = $filter('number')(vm.outbound[arrNumber[i]], 2);

        arrDate = [
        "ReturnedDateTime"
        /*Ansuran*/
        , "ACCOUNT_START_DATE"
        , "ACCOUNT_END_DATE"
        , "AMEN_SHED_DATE"
        , "MIN_DUE_DATE"
        , "SKIM_DATE"
        , "TarikhKenaBayar"
        /*Tunggakan*/
        , "ASSESSMENT_DATE"
        , "PAYMENT_DUE_DATE"
        , "PINK_LETTER_DATE"
        /*CTL*/
        , "CTL_DATE"
        , "DATE_BANK_IN"
        , "DATE_BANK_INVALID"
        , "DATE_CEK_ACCEPT"
        ]

        for (i = 0; i < arrDate.length; i++) {
            if (vm.outbound[arrDate[i]]) {
                vm.outbound[arrDate[i]] = new Date(vm.outbound[arrDate[i]]);//$filter('date')(new Date(vm.outbound[arrDate[i]]), 'dd MMM yyyy');
            }
        }

        //validate email and decimal
        vm.emailValidation = GeneralService.Validation.Email;
        vm.invalidEmail = false;
        vm.invalidDecimal = false;

        vm.oriEmail = angular.copy(vm.outbound.E_MAIL);

        if (vm.outbound.E_MAIL)
            vm.invalidEmail = !vm.emailValidation.test(vm.outbound.E_MAIL);

        angular.forEach(vm.outbound, function (value, key) {
            for (i = 0; i < arrNumber.length; i++) {
                if (key == arrNumber[i] && vm.outbound[key])
                    if (value.replace(/,/g, "") < 0)
                        vm.invalidDecimal = true;
            }
        });
    }

    vm.onAddActClick = function () {

        var form = angular.element('#addActivityForm');
        form.submit();
    }

    vm.returnBtnClicked = function ($event) {
        vm.openDialog($event, '#myModal');
    };

    vm.formatNumber = function (name) {
        vm.outbound[name] = GeneralService.getFormattedNumber(vm.outbound[name]);
    };

    function validateEmail(email) {
        var re = GeneralService.Validation.Email;
        return re.test(String(email).toLowerCase());
    }
    /*Private Other Functions END*/

    // date picker
    vm.clearDateFrom = function () {
        vm.DateFrom = '';
        vm.DateFrom.$dirty = true;
        vm.DateFrom.$pristine = false;
    };
    vm.clearDateTo = function () {
        vm.DateTo = '';
        vm.DateTo.$dirty = true;
        vm.DateTo.$pristine = false;
    };

    vm.clearCTLDate = function () {
        vm.outbound.CTL_DATE = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["CTL_DATE"].$pristine = false;
        $scope.makReMSForm["CTL_DATE"].$dirty = true;
    };

    vm.clearTarikhMasukBank = function () {
        vm.outbound.DATE_BANK_IN = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["DATE_BANK_IN"].$pristine = false;
        $scope.makReMSForm["DATE_BANK_IN"].$dirty = true;
    };

    vm.clearTarikhBankTendang = function () {
        vm.outbound.DATE_BANK_INVALID = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["DATE_BANK_INVALID"].$pristine = false;
        $scope.makReMSForm["DATE_BANK_INVALID"].$dirty = true;
    };

    vm.clearTarikhTerimaCek = function () {
        vm.outbound.DATE_CEK_ACCEPT = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["DATE_CEK_ACCEPT"].$pristine = false;
        $scope.makReMSForm["DATE_CEK_ACCEPT"].$dirty = true;
    };

    vm.clearTarikhTaksiran = function () {
        vm.outbound.ASSESSMENT_DATE = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["ASSESSMENT_DATE"].$pristine = false;
        $scope.makReMSForm["ASSESSMENT_DATE"].$dirty = true;
    };

    vm.clearTarikhKenaBayar = function () {
        vm.outbound.PAYMENT_DUE_DATE = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["PAYMENT_DUE_DATE"].$pristine = false;
        $scope.makReMSForm["PAYMENT_DUE_DATE"].$dirty = true;
    };

    vm.clearTarikhSurat = function () {
        vm.outbound.PINK_LETTER_DATE = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["PINK_LETTER_DATE"].$pristine = false;
        $scope.makReMSForm["PINK_LETTER_DATE"].$dirty = true;
    };

    vm.clearTarikhAkaunMula = function () {
        vm.outbound.ACCOUNT_START_DATE = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["ACCOUNT_START_DATE"].$pristine = false;
        $scope.makReMSForm["ACCOUNT_START_DATE"].$dirty = true;
    };

    vm.clearTarikhAkaunTutup = function () {
        vm.outbound.ACCOUNT_END_DATE = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["ACCOUNT_END_DATE"].$pristine = false;
        $scope.makReMSForm["ACCOUNT_END_DATE"].$dirty = true;
    };

    vm.clearTarikhMulaAnsuran = function () {
        vm.outbound.MIN_DUE_DATE = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["MIN_DUE_DATE"].$pristine = false;
        $scope.makReMSForm["MIN_DUE_DATE"].$dirty = true;
    };

    vm.clearTarikhBulanPindaan = function () {
        vm.outbound.AMEN_SHED_DATE = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["AMEN_SHED_DATE"].$pristine = false;
        $scope.makReMSForm["AMEN_SHED_DATE"].$dirty = true;
    };

    vm.clearTarikhSkim = function () {
        vm.outbound.SKIM_DATE = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["SKIM_DATE"].$pristine = false;
        $scope.makReMSForm["SKIM_DATE"].$dirty = true;
    };

    vm.clearTarikhKenaBayar = function () {
        vm.outbound.PAYMENT_DUE_DATE = '';
        $scope.makReMSForm.$dirty = true;
        $scope.makReMSForm["PAYMENT_DUE_DATE"].$pristine = false;
        $scope.makReMSForm["PAYMENT_DUE_DATE"].$dirty = true;
    };

    vm.clearImportedDateFromReMS = function () {
        vm.clearImportedDateFromReMS = '';
        vm.clearImportedDateFromReMS.$dirty = true;
        vm.clearImportedDateFromReMS.$pristine = false;
    };
    vm.clearImportedDateToReMS = function () {
        vm.clearImportedDateToReMS = '';
        vm.clearImportedDateToReMS.$dirty = true;
        vm.clearImportedDateToReMS.$pristine = false;
    };

    vm.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.outbound.CCIDTypeCode,
                        IDNo: vm.outbound.IdentityNo,
                        JenisKempenID: vm.jenisKempenId,
                        ReMSDataID: vm.dataId,
                        IsSelfSelectOutbound: true                        
                    });
                }
                else {
                    swal("Batal!", "Panggilan telah dibatalkan.", "error");
                }
            });

        }
    }

}
