crmApp.controller("OutboundHCLEmailBlastController", OutboundHCLEmailBlastController);

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

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

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

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

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

    /*On page load functions */
    vm.init = function () {

        var querystring = location.search;
        if (querystring) {
            TabID = querystring.substring(querystring.indexOf("=") + 1, querystring.indexOf("&"));
            TabType = querystring.substring(querystring.lastIndexOf("=") + 1, querystring.length);
        }
        // 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
        };

        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.getEmailBlastDetails(model).then(function (r) {
                vm.outbound = r.data;
                vm.oriEmail = angular.copy(vm.outbound.Email);

                if (vm.outbound.TP)
                    bindHeader(vm.outbound.TP);

                if (vm.outbound.TarikhDaftar)
                    vm.outbound.TarikhDaftar = new Date(vm.outbound.TarikhDaftar);//$filter('date')(new Date(vm.outbound.TarikhDaftar), 'dd MMM yyyy');

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

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

    //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*/
    vm.Validation = {};
    vm.Validation.Phone = GeneralService.Validation.Phone;
    vm.Validation.PhoneMsg = GeneralService.Validation.PhoneMsg;

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

    function bindHeader(objTP) {
        if (objTP.TPID > 0)
        {
            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.NoCukaiCode;
            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 != "" ? objTP.CWPungutanCP : "-";
            TaxPayerService.CWNG.PungutanCKHT = objTP.CWPungutanCKHT != "" ? objTP.CWPungutanCKHT : "-";
            TaxPayerService.CWNG.PenaksiranCP = objTP.CWPenaksiranCP != "" ? objTP.CWPenaksiranCP : "-";
            TaxPayerService.CWNG.PenaksiranCKHT = objTP.CWPenaksiranCKHT != "" ? objTP.CWPenaksiranCKHT : "-";
            TaxPayerService.CWNG.GuamanSivil = objTP.CWGuamanSivil != "" ? objTP.CWGuamanSivil : "-";
        }
        else
        {
            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.NoCukaiCode + " " +  objTP.NoCukai || objTP.NoCukaiCode + " " + objTP.TPNoCukai;
            TaxPayerService.TP.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 != "" ? objTP.CWPungutanCP : "-";
            TaxPayerService.CWNG.PungutanCKHT = objTP.CWPungutanCKHT != "" ? objTP.CWPungutanCKHT : "-";
            TaxPayerService.CWNG.PenaksiranCP = objTP.CWPenaksiranCP != "" ? objTP.CWPenaksiranCP : "-";
            TaxPayerService.CWNG.PenaksiranCKHT = objTP.CWPenaksiranCKHT != "" ? objTP.CWPenaksiranCKHT : "-";
            TaxPayerService.CWNG.GuamanSivil = objTP.CWGuamanSivil != "" ? objTP.CWGuamanSivil : "-";
        }

    }

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

            data.EmailDataID = $window.dataid;
            data.JenisKempenID = $window.jeniskempenid;
            data.FieldName = vm.FieldName;
            data.DateFrom = $filter('date')(vm.DateFrom, $scope.DateTimeFormat);
            data.DateTo = $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.dtColumnsEmailBlastChangesHistory = [
            //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.dtOptionsEmailBlastChangesHistory = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallbackEmailBlast)
            .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 ajaxCallbackEmailBlastAL = function (data, callback, settings) {
            data.EmailDataID = $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.dtColumnsEmailBlastActivityList = [
			//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.dtOptionsEmailBlastActivityList = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallbackEmailBlastAL)
            .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.dtInstanceEmailBlastChangesHistory.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.dtInstanceEmailBlastActivityList = {};

    vm.searchAL = function () {

        vm.blnValid = true;

        if (vm.blnValid) {
            vm.dtInstanceEmailBlastActivityList.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.saveEmailBlastDetails = function (makEmailBlastForm) {
        var isDirty = makEmailBlastForm.$dirty;

        if (makEmailBlastForm.$valid) {
            if (isDirty) {
                getChangeHistory();
                updateEmailBlastDetails();
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {

            //if (makEmailBlastForm.$error.pattern[0].$name == "Email")
            //{
            //    swal("Failed", "Invalid Email Address!", "error");
            //}
            //else if (makEmailBlastForm.$error.pattern[0].$name == "NoTelefon")
            //{
            //    swal("Failed", "Invalid Phone Number!", "error");
            //}
            //else
            //{
            //    swal("Failed", "Please fill in all the required fields!", "error");
            //}
            swal("Failed", "Form contains invalid field value(s), please check and try again.", "error");

            vm.showValidationMsg = true;
        
        }
    }

    vm.saveVerifyData = function (makEmailBlastForm) {
        var isDirty = makEmailBlastForm.$dirty;
        if (makEmailBlastForm.$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();
                        updateEmailBlastDetails(vm.constStatusVerified);
                    }
                    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.verifyEmailBlastData(model);
                        data.then(function (r) {
                            swal({
                                title: "Data Disahkan!",
                                //text: GeneralService.SaveMessage.Text,
                                type: "success",
                                timer: 2500,
                                showConfirmButton: true
                            }, function () {
                                vm.redirectTo('/Outbound/HCLEmailBlastProfile/Detail/' + $window.jeniskempenid + '/' + $window.dataid + '?t=' + TabID + '&ty=' + TabType);
                            });
                        });
                    }
                    else {
                        swal("Tindakan Pengesahan Data Dibatalkan!", null, "error");
                    }
                });

            }
        } else {

            //if (makEmailBlastForm.$error.pattern[0].$name == "Email") {
            //    swal("Failed", "Invalid Email Address!", "error");
            //}
            //else if (makEmailBlastForm.$error.pattern[0].$name == "NoTelefon") {
            //    swal("Failed", "Invalid Phone Number!", "error");
            //}
            //else {
            //    swal("Failed", "Please fill in all the required fields!", "error");
            //}

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

            vm.showValidationMsg = true;
        }
    }

    vm.saveRejectData = function (makEmailBlastForm) {
        var isDirty = makEmailBlastForm.$dirty;
       // if (makEmailBlastForm.$valid) {
            if (isDirty) {
                swal({
                    title: "Adakah anda pasti untuk menolak data ini? ",
                    text: "",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonText: "Ya",
                    cancelButtonText: "Tidak",
                    closeOnConfirm: false,
                    closeOnCancel: false
                }, function (isConfirm) {
                    if (isConfirm) {
                        getChangeHistory();
                        updateEmailBlastDetails(vm.constStatusReturnReject);
                    }
                    else {
                        swal("Tindakan Untuk Tolak Data Dibatalkan!", null, "error");
                    }
                });
             
            }
            else {

                model = {
                    DataID: vm.dataId,
                    JenisKempenID: vm.jenisKempenId
                };

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



                    }
                    else {
                        swal("Tindakan Untuk Tolak Data Dibatalkan!", null, "error");
                    }
                });
           }
        //} else {

        //    if (makEmailBlastForm.$error.pattern[0].$name == "Email") {
        //        swal("Failed", "Invalid Email Address!", "error");
        //    }
        //    else if (makEmailBlastForm.$error.pattern[0].$name == "NoTelefon") {
        //        swal("Failed", "Invalid Phone Number!", "error");
        //    }
        //    else {
        //        swal("Failed", "Please fill in all the required fields!", "error");
        //    }

        //    vm.showValidationMsg = true;
        //}
    }

    function updateEmailBlastDetails(emailBlastStatus) {
        var emailBlastDetailsModel = angular.copy(vm.outbound);
        if (emailBlastStatus == vm.constStatusVerified)
        {
            emailBlastDetailsModel.EmailBlastStatusID = vm.constStatusVerified
        }
        else if (emailBlastStatus == vm.constStatusReturnReject)
        {
            emailBlastDetailsModel.EmailBlastStatusID = vm.constStatusReturnReject
        }

        var IsEmailValid = validateEmail(vm.outbound.Email);
        if (IsEmailValid) {
            emailBlastDetailsModel.HasError = false;
        }
        else
        {
            emailBlastDetailsModel.HasError = true;
        }

        model = {
            EmailBlastDetails: emailBlastDetailsModel,
            ChangeHistory: vm.changesHistory
        };

        model = consolidateBeforeSave(model);

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

    function consolidateBeforeSave(model) {
        arrDate = ["TarikhDaftar"]

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

        return model;
    }


    function getChangeHistory() {
        angular.forEach($scope.makEmailBlastForm, 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 = [
        "AsetSMUP"
        , "AsetStamps"
        , "PendapatanSMUP"
        , "PendapatanVIS"
        , "KontrakVIS"
        , "BakiLejerSTS"
        ]

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

        arrDate = ["TarikhDaftar"]

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

    vm.onAddActClick = function () {

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

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

    function validateEmail(email) {
        //var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        var re = GeneralService.Validation.Email;
        return re.test(String(email).toLowerCase());
    }

    // 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.clearTarikhDaftar = function () {
        vm.outbound.TarikhDaftar = '';
        $scope.makEmailBlastForm.$dirty = true;
        $scope.makEmailBlastForm["TarikhDaftar"].$pristine = false;
        $scope.makEmailBlastForm["TarikhDaftar"].$dirty = true;
    };
}
