crmApp.controller('OutboundReMSBatchController', function ($scope, $mdDialog, $window, AntiForgeryService, $compile, $q, $http, $location, $filter, DTOptionsBuilder, DTColumnBuilder, OutboundSI, GeneralService) {
    var vm = this;
    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;
    vm.selectedJenisKempenID = $window.jeniskempenid;
    vm.selectedBatchID = $window.batchid;

    vm.dtInstanceReMSData = {};
    vm.dtInstanceReMSDataInvalid = {};

    vm.constStatusNew = 27;
    vm.constStatusVerified = 39;

    vm.isHCLEmailBlast = $window.isHCLEmailBlast;

    vm.init = function () {
        tabAction("01");

        if (!vm.isHCLEmailBlast)
            vm.isHCLEmailBlast = false;

        initBatchDetails();
        initData();
        console.log(vm);
    }

    function initBatchDetails() {
        var model = {
            JenisKempenID: vm.selectedJenisKempenID,
            BatchID: vm.selectedBatchID
        };

        if (vm.isHCLEmailBlast) {
            OutboundSI.getEmailBlastBatchDetailsByBatchID(model).then(function (r) {
                if (r.data) {
                    assignBatchValue(r);
                };
            });
        }
        else {
            OutboundSI.getReMSBatchDetailsByBatchID(model).then(function (r) {
                if (r.data) {
                    assignBatchValue(r);
                };
            });
        }
    }

    function assignBatchValue(r) {
        vm.batch = r.data;
        vm.batch.ImportedDateTime = new Date(r.data.ImportedDateTime);
        vm.batch.ReturnedDateTime = new Date(r.data.ReturnedDateTime);
        vm.batch.BatchID = vm.selectedBatchID;
        vm.batch.JenisKempenID = vm.selectedJenisKempenID;
        //vm.batch.CanReturnData = r.data.CanReturnData == "1" ? true : false;
        vm.batch.KodSelesaiDesc = r.data.KodSelesaiDesc;
        vm.ReturnReasonOptions = r.data.ReturnedReasonOptions;
    }

    function initData() {

        // Invalid ReMS Data
        var ajaxCallbackReMSDataInvalid = function (data, callback, settings) {

            data.JenisKempenID = vm.selectedJenisKempenID;
            data.BatchID = vm.selectedBatchID;

            if (vm.selectedJenisKempenID != undefined) {
                if (vm.isHCLEmailBlast) {
                    OutboundSI.getInvalidEmailBlastDataByBatchID(data).then(function (r) {
                        if (r.data) {
                            callback(r.data);
                            vm.showReMSData = true;
                            vm.InvalidDataLoaded = true;
                        }
                    });
                } else {
                    OutboundSI.getInvalidReMSDataByBatchID(data).then(function (r) {
                        if (r.data) {
                            callback(r.data);
                            vm.showReMSData = true;
                            vm.InvalidDataLoaded = true;
                        }
                    });
                }
            }
        }

        if (vm.isHCLEmailBlast) {
            vm.dtColumnsReMSDataInvalid = [
                DTColumnBuilder.newColumn('HasError').withTitle('').withOption('width', '10px').notSortable().renderWith(function (data, type, row) {
                    var link = '';
                    if (data) {
                        //link += '<div class="" style="border-radius: 10px;width: 20px;height: 20px;line-height:20px;text-align:center;margin-left:5px;color: red;"><span class="fa fa-exclamation-circle"></span></div>';
                        link = '<i class="case fa fa-exclamation-circle" style="color:red;" title="Data tidak sah"></i >';
                        if (!vm.tabProfile02Active && !vm.InvalidDataLoaded)
                            tabAction("02");
                    }
                    return link;
                }),
                DTColumnBuilder.newColumn('RowNum').withTitle('No.').notSortable(),
                DTColumnBuilder.newColumn('NamaPembayarCukai').withTitle('Nama P.C.').renderWith(function (data, type, row) {
                    return '<a target="_blank" href="/Outbound/HCLEmailBlastProfile/Detail/' + row.JenisKempenID + '/' + row.EmailDataID + '">' + data + '</a>';
                }),
                DTColumnBuilder.newColumn('NoRujukanCukai').withTitle('No. Rujukan Cukai').renderWith(function (data, type, row) {
                    if (data)
                        return row["JenisFailCukai"] + data;
                    else
                        return "-";
                }),
                DTColumnBuilder.newColumn('Email').withTitle('Emel'),
                DTColumnBuilder.newColumn('StatusName').withTitle('Status'),
            ];
        }
        else {
            vm.dtColumnsReMSDataInvalid = [
                DTColumnBuilder.newColumn('HasError').withTitle('').withOption('width', '10px').notSortable().renderWith(function (data, type, row) {
                    var link = '';
                    if (data) {
                        //link += '<div class="" style="border-radius: 10px;width: 20px;height: 20px;line-height:20px;text-align:center;margin-left:5px;color: red;"><span class="fa fa-exclamation-circle"></span></div>';
                        link = '<i class="case fa fa-exclamation-circle" style="color:red;" title="Data tidak sah"></i >';
                        if (!vm.tabProfile02Active && !vm.InvalidDataLoaded)
                            tabAction("02");
                    }
                    return link;
                }),
                DTColumnBuilder.newColumn('RowNum').withTitle('No.').notSortable(),
                DTColumnBuilder.newColumn('TPName').withTitle('Nama P.C.').renderWith(function (data, type, row) {
                    return '<a target="_blank" href="/Outbound/Profile/Detail/' + row.JenisKempenID + '/' + row.DataID + '">' + data + '</a>';
                }),
                DTColumnBuilder.newColumn('NoRujukanCukai').withTitle('No. Rujukan Cukai').renderWith(function (data, type, row) {
                    return data ? data : '-';
                }),
                DTColumnBuilder.newColumn('TahunTaksiran').withTitle('Tahun Taksiran'),
                DTColumnBuilder.newColumn('StatusName').withTitle('Status'),
                DTColumnBuilder.newColumn('ReturnedReason').withTitle('Alasan Dipulangkan').renderWith(function (data, type, row) {
                    return data ? data : '-';
                })
            ];
        }

        vm.dtOptionsReMSDataInvalid = DTOptionsBuilder.newOptions()
          .withOption('ajax', ajaxCallbackReMSDataInvalid)
          .withDataProp('data')
          .withOption('processing', true)
          .withOption('searching', true)
          .withOption('serverSide', true)
          .withOption('autoWidth', false)
          .withOption('createdRow', function (row, data, dataIndex) {
              $compile(angular.element(row).contents())($scope);
          })
          .withPaginationType('full_numbers')
          .withDisplayLength(10);

        // Valid ReMS Data
        var ajaxCallbackReMSData = function (data, callback, settings) {

            data.JenisKempenID = vm.selectedJenisKempenID;
            data.BatchID = vm.selectedBatchID;
            if (vm.selectedJenisKempenID != undefined) {
                if (vm.isHCLEmailBlast) {
                    OutboundSI.getEmailBlastDataByBatchID(data).then(function (r) {
                        if (r.data) {
                            callback(r.data);
                            vm.showReMSData = true;
                        }
                    });
                }
                else {
                    OutboundSI.getReMSDataByBatchID(data).then(function (r) {
                        if (r.data) {
                            callback(r.data);
                            vm.showReMSData = true;
                        }
                    });
                }
            }
        }

        if (vm.isHCLEmailBlast) {
            vm.dtColumnsReMSData = [
                DTColumnBuilder.newColumn('RowNum').withTitle('No.').notSortable(),
                DTColumnBuilder.newColumn('NamaPembayarCukai').withTitle('Nama P.C.').renderWith(function (data, type, row) {
                    return '<a target="_blank" href="/Outbound/HCLEmailBlastProfile/Detail/' + row.JenisKempenID + '/' + row.EmailDataID + '">' + data + '</a>';
                }),
                DTColumnBuilder.newColumn('NoRujukanCukai').withTitle('No. Rujukan Cukai').renderWith(function (data, type, row) {
                    if (data)
                        return row["JenisFailCukai"] + data;
                    else
                        return "-";
                }),
                DTColumnBuilder.newColumn('Email').withTitle('Emel'),
                DTColumnBuilder.newColumn('StatusName').withTitle('Status')
            ];
        }
        else {
            vm.dtColumnsReMSData = [
                DTColumnBuilder.newColumn('RowNum').withTitle('No.').notSortable(),
                DTColumnBuilder.newColumn('TPName').withTitle('Nama P.C.').renderWith(function (data, type, row) {
                    return '<a target="_blank" href="/Outbound/Profile/Detail/' + row.JenisKempenID + '/' + row.DataID + '">' + data + '</a>';
                }),
                DTColumnBuilder.newColumn('NoRujukanCukai').withTitle('No. Rujukan Cukai'),
                DTColumnBuilder.newColumn('TahunTaksiran').withTitle('Tahun Taksiran'),
                DTColumnBuilder.newColumn('StatusName').withTitle('Status')
            ];
        }
        vm.dtOptionsReMSData = DTOptionsBuilder.newOptions()
          .withOption('ajax', ajaxCallbackReMSData)
          .withDataProp('data')
          .withOption('processing', true)
          .withOption('searching', true)
          .withOption('serverSide', true)
          .withOption('autoWidth', false)
          .withOption('createdRow', function (row, data, dataIndex) {
              $compile(angular.element(row).contents())($scope);
          })
          .withPaginationType('full_numbers')
          .withDisplayLength(10);

    };

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

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

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

    vm.returnData = function (isValid) {

        if (isValid) {

            var model = {
                BatchID: vm.selectedBatchID,
                JenisKempenID: vm.selectedJenisKempenID,
                JenisKempenName: vm.batch.JenisKempenName,
                ReturnReasonID: vm.returnReasonID,
                Remarks: vm.remarks
            };

            swal({
                title: "Are you sure you want to return all data to ReMS?",
                text: "Applicable to both Valid Data and Invalid/Rejected Data tab, Status = New, Verified and Scheduled only.",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Ya",
                cancelButtonText: "Tidak",
                closeOnConfirm: false,
                closeOnCancel: false,
                showLoaderOnConfirm: true
            }, function (isConfirm) {
                if (isConfirm) {
                    vm.close();
                    OutboundSI.returnReMSBatch(model).then(function (r) {

                        if (r.data.IsSuccess) {

                            if (r.data.noOfRecord > 0) {
                                var txt1 = r.data.noOfRecord + " record has been returned.";
                                var txt2 = r.data.noOfRecord + " records have been returned.";
                                swal({
                                    title: "ReMS Batch Returned!",
                                    text: r.data.noOfRecord == 1 ? txt1 : txt2,
                                    type: "success",
                                    //timer: 2500,
                                    showConfirmButton: true,
                                    closeOnConfirm: true
                                }, function () {
                                    //bind data
                                    swal.close();
                                    vm.batch.ReturnedByName = r.data.data.ReturnedByName;
                                    vm.batch.ReturnedDateTime = new Date(r.data.data.ReturnedDateTime);
                                    vm.batch.ReturnReason = r.data.data.ReturnReason;
                                });

                                vm.dtInstanceReMSData.reloadData();
                                vm.dtInstanceReMSDataInvalid.reloadData();
                                tabAction("02");

                                initBatchDetails();
                            }
                            else { // no records
                                swal("Batal!", "No available data to be returned.", "error");
                            }
                        }
                    });
                } else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        } else {
            swal("Gagal!", "Please select Return Reason.", "error");
        }
    }

    vm.rejectEmailBlastDataByBatch = function () {
        var model = {
            BatchID: vm.selectedBatchID,
            JenisKempenID: vm.selectedJenisKempenID,
        };

        swal({
            title: "Adakah anda pasti untuk tolak semua data?",
            text: "Amaran: Terpakai untuk Semua data berstatus Baru, Disahkan dan Dijadualkan sahaja.",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                vm.close();
                OutboundSI.rejectEmailBlastBatch(model).then(function (r) {
                    if (r.data > 0) {
                        var txt1 = r.data + " rekod telah ditolak.";
                        //var txt2 = r.data + " records have been rejected.";
                        swal({
                            title: "Data Kelompok Telah Ditolak!",
                            text: txt1,
                            type: "success",
                            //timer: 2500,
                            showConfirmButton: true,
                            closeOnConfirm: true
                        }, function () {
                            //bind data
                            swal.close();
                            //vm.batch.ReturnedByName = r.data.data.ReturnedByName;
                            //vm.batch.ReturnedDateTime = new Date(r.data.data.ReturnedDateTime);
                            //vm.batch.ReturnReason = r.data.data.ReturnReason;
                        });

                        vm.dtInstanceReMSData.reloadData();
                        vm.dtInstanceReMSDataInvalid.reloadData();
                        tabAction("02");

                        initBatchDetails();
                    }
                    else { // no records
                        swal("Batal!", "No available data to be rejected.", "error");
                    }
                });
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });
    }


    vm.verifyOutboundDataByBatch = function () {
        swal({
            title: "Adakah anda pasti untuk sahkan semua data?",
            text: 'Semua data yang berstatus "Baru" dan alamat emel yang mengikut format akan disahkan.',
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                model = {
                    BatchID: vm.selectedBatchID,
                    JenisKempenID: vm.selectedJenisKempenID
                };

                vm.close();
                OutboundSI.verifyOutboundDataByBatch(model).then(function (r) {
                    if (r.data) {
                        var txt1 = r.data + " rekod telah berjaya disahkan.";
                        //var txt2 = r.data + " records have been verified successfully.";
                        swal({
                            title: "Data Kelompok Disahkan!",
                            text: txt1,
                            type: "success",
                            //timer: 2500,
                            showConfirmButton: true,
                            closeOnConfirm: true
                        }, function () {
                            swal.close();
                        });

                        vm.dtInstanceReMSData.reloadData();
                        vm.dtInstanceReMSDataInvalid.reloadData();

                        initBatchDetails();
                    }
                    else {
                        swal("Batal!", "No available data to be verified.", "error");
                    }
                });
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });
    }

    vm.verifyEmailBlastDataByBatch = function () {
        swal({
            title: "Adakah anda pasti untuk sahkan semua data?",
            text: 'Semua data yang berstatus "Baru", "Ditolak/Dipulangkan" dan alamat emel yang mengikut format akan disahkan.',
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                model = {
                    BatchID: vm.selectedBatchID,
                    JenisKempenID: vm.selectedJenisKempenID
                };

                vm.close();
                OutboundSI.verifyEmailBlastDataByBatch(model).then(function (r) {
                    if (r.data > 0) {
                        var txt1 = + r.data + " rekod telah berjaya disahkan.";
                        //var txt2 = r.data + " records have been verified successfully.";
                        swal({
                            title: "Data Kelompok Disahkan!",
                            text: txt1,
                            type: "success",
                            //timer: 2500,
                            showConfirmButton: true,
                            closeOnConfirm: true
                        }, function () {
                            swal.close();
                        });

                        vm.dtInstanceReMSData.reloadData();
                        vm.dtInstanceReMSDataInvalid.reloadData();

                        initBatchDetails();
                    }
                    else {
                        swal("Batal!", "No available data to be verified.", "error");
                    }
                });
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });
    }

    //Tab action
    vm.tabAction = tabAction;


    vm.tabAction = tabAction;
    function tabAction(cls) {
        reset();

        switch (cls) {
            case '01':
                tabProfile01Click();
                break;
            case '02':
                tabProfile02Click();
                break;
        }
    }

    function reset() {
        vm.tabProfile01Active = false;
        vm.tabProfile02Active = false;
    }

    //Profile Tab 01
    vm.tabProfile01Click = tabProfile01Click;
    function tabProfile01Click() {
        vm.tabProfile01Active = true;
    }

    //Profile Tab 02
    vm.tabProfile02Click = tabProfile02Click;
    function tabProfile02Click() {
        vm.tabProfile02Active = true;
    }

    vm.refreshData = function () {
        vm.dtInstanceReMSData.reloadData();
        vm.dtInstanceReMSDataInvalid.reloadData();
        initBatchDetails();
    }

});