let RecargasActivity = function () {
    "use strict";

    let dom = App.getContainerMain();
    let domNumero, domLoteria, domMonto, domTableJugadas;

    let url_request = "/recargas/pos/new";
    let url_request_list = "/recargas/pos/list";
    let url_request_cancel = "/recargas/pos/void";
    let url_request_saldo = "/recargas/pos/saldo";

    let initHtml = function () { console.log("VentaActivity.initHtml()");
        dom.empty();

        let html = '' +
            '<section class="box-typical box-vender">' +
            '   <header class="box-typical-header">' +
            '       <div class="tbl-row">' +
            '           <div class="tbl-cell tbl-cell-title col-md-2"><h3>Recargas</h3></div>' +
            '           <div class="tbl-cell tbl-cell-title col-md-3">' +
            '               <div class="input-group date">' +
            '                   <input id="daterange_fecha_desde" type="text" class="form-control">' +
            '                   <span class="input-group-addon"><i class="font-icon font-icon-calend"></i></span>' +
            '               </div>' +
            '           </div>' +
            '           <div class="tbl-cell tbl-cell-title col-md-3">' +
            '               <div class="input-group date">' +
            '                   <input id="daterange_fecha_hasta" type="text" class="form-control">' +
            '                   <span class="input-group-addon"><i class="font-icon font-icon-calend"></i></span>' +
            '               </div>' +
            '           </div>' +
            '       </div>' +
            '   </header>' +
            '   <div class="box-typical-body typical-body2" style="width: calc(100% - 240px);">' +
            '       <div class="table-responsive">' +
            '           <table id="table_jugadas" class="table table-bordered table-hover table-sm">' +
            '               <thead>' +
            '                   <tr>' +
            '                       <th width="25%">Fecha</th>' +
            '                       <th>Compañía</th>' +
            '                       <th width="25%">Teléfono</th>' +
            '                       <th width="15%">Monto</th>' +
            '                       <th width="15%">Estado</th>' +
            '                   </tr>' +
            '               </thead>' +
            '               <tbody></tbody>' +
            '               <tfoot>' +
            '                   <tr><th width="100%" colspan="5" style="text-align: right" id="jugadas_total_monto">$000</th></tr>' +
            '               </tfoot>' +
            '           </table>';
        dom.append(html);

        html = '<section class="box-typical telefonicas-logos">';
        let list = [];
        let companias = [
            {'name': 'Claro', 'id':'claro'},
            {'name': 'Altice', 'id':'orange'},
            {'name': 'Viva', 'id':'viva'},
            {'name': 'Tricom', 'id':'tricom'},
            {'name': 'Digicel', 'id':'digicel'},
            {'name': 'Natcom', 'id':'natcom'},
        ];
        companias.forEach(function (c) {
            list.push('<img id="company_'+c.id+'" src="img/telefonicas/telefonica_'+c.id+'.png" width="90%" height="200">');
        });

        html += list.join('<hr>');
        html += '</section>';
        dom.append(html);

        // click en los logos de las telefonicas
        companias.forEach(function (c) {
            dom.find('#company_'+c.id).click(function() { console.log(c.id)
                recargar(c.id);
            });
        });

        $("#daterange_fecha_desde").val(Time.fecha("DD/MM/YYYY"));
        $("#daterange_fecha_hasta").val(Time.fecha("DD/MM/YYYY"));
    }

    let initListeners = function () { console.log("VentaActivity.initListeners()");
        domTableJugadas = $('#table_jugadas tbody');

        $('#table_jugadas').on('click', 'tbody tr', function () {
            let id = $(this).attr('id');

            if (id) {
                voidConfirm(id);
            }
        });

        let dateOps = ut.datePikerLocale();
        dateOps.singleDatePicker = true;

        $('#daterange_fecha_desde').daterangepicker(dateOps);
        $('#daterange_fecha_desde').on('hide.daterangepicker', function() {
            requestHistory();
        });

        $('#daterange_fecha_hasta').daterangepicker(dateOps);
        $('#daterange_fecha_hasta').on('hide.daterangepicker', function() {
            requestHistory();
        });

        /*$('div').on('click', 'button#icon-void', function (e) {
            e.stopPropagation();
        });*/
    }

    let voidConfirm = function(id) {
        $.confirm({
            escapeKey: true,
            backgroundDismiss: true,
            title: '¿Cancelar esta recarga?',
            content: 'Las transacciones canceladas no pueden restablecerse',
            icon: 'fa fa-question-circle',
            animation: 'scale',
            closeAnimation: 'scale',
            opacity: 0.5,
            buttons: {
                cancel: function () {},
                'confirm': {
                    text: 'Sí, proceder',
                    btnClass: 'btn-blue',
                    keys: ['enter'],
                    action: function () {
                        $.confirm({
                            escapeKey: true,
                            backgroundDismiss: true,
                            title: 'Confirmar acción',
                            content: '¿Confirma que desea cancelar la recarga?',
                            icon: 'fa fa-warning',
                            animation: 'scale',
                            closeAnimation: 'zoom',
                            buttons: {
                                cancel: function () {},
                                confirm: {
                                    text: 'Sí, proceder',
                                    btnClass: 'btn-orange',
                                    keys: ['enter'],
                                    action: function () {
                                        requestVoid(id);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        });
    }

    let recargar = function (compania) {
        $.confirm({
            escapeKey: true,
            backgroundDismiss: true,
            title: 'Realizar Recarga',
            content: ''+
            '<div class="form-group"><input type="text" placeholder="Teléfono" class="input-telefono form-control"/></div>'+
            '<div class="form-group"><input type="text" placeholder="Monto" class="input-monto form-control"/></div>',
            buttons: {
                cancel: function () {
                    //close
                },
                formSubmit: {
                    text: _t('accept'),
                    btnClass: 'btn-blue',
                    action: function () {
                        let jc = this;
                        let elTelefono = jc.$content.find('.input-telefono');
                        let elMonto = jc.$content.find('.input-monto');

                        let telefono = elTelefono.val();
                        let monto = filter.int(elMonto.val());

                        if (telefono.length != 14) {
                            ui.dialogErrorSimple('El teléfono no es válido', function(){elTelefono.focus();});
                            return false;
                        }

                        if (!monto) {
                            ui.dialogErrorSimple('El monto no es válido', function(){elTelefono.focus();});
                            return false;
                        }

                        recargarConfirm(compania, telefono, monto);
                    }
                }
            },
            onContentReady: function () {
                // bind to events
                let jc = this;
                let elTelefono = jc.$content.find('.input-telefono');
                let elMonto = jc.$content.find('.input-monto');
                Inputmask({"mask": "(999) 999-9999"}).mask(elTelefono);

                elTelefono.on('keypress', function (e) {
                    if (e.which == 13) {
                        e.preventDefault();
                        elMonto.focus();
                    }
                });

                elMonto.on('keypress', function (e) {
                    if (e.which == 13) {
                        e.preventDefault();
                        jc.$$formSubmit.trigger('click');
                    }
                });

                elTelefono.focus();
            }
        });
    }

    let recargarConfirm = function (compania, telefono, monto) {
        $.confirm({
            escapeKey: true,
            backgroundDismiss: true,
            title: 'Confirmar Recarga',
            content: ''+
            '<div class="font-weight-bold">Compañía</div>'+
            '<div class="form-group">'+companyName(compania)+'</div>'+
            '<div class="font-weight-bold">Monto</div>'+
            '<div class="form-group">$'+monto+'</div>'+
            '<div class="font-weight-bold">Teléfono</div>'+
            '<div class="form-group">'+telefono+'</div>',
            buttons: {
                cancel: function () {
                    //close
                },
                formSubmit: {
                    text: 'Confirmar',
                    keys: ['enter'],
                    btnClass: 'btn-blue',
                    action: function () {
                        let jc = this;
                        jc.close();

                        Server.sending({
                            'action': packet.RECARGA_REQUEST,
                            'company': compania,
                            'phone': telefono,
                            'monto': monto
                        },
                            'Procesando recarga'
                        );
                    }
                }
            },
            onContentReady: function () {

            }
        });
    }

    let companyName = function (id) {
        if (id == Co.TELEFONICA_CLARO) {
            return Co.TELEFONICA_CLARO_NAME;
        }
        else if (id == Co.TELEFONICA_ORANGE) {
            return Co.TELEFONICA_ORANGE_NAME;
        }
        else if (id == Co.TELEFONICA_VIVA) {
            return Co.TELEFONICA_VIVA_NAME;
        }
        else if (id == Co.TELEFONICA_TRICOM) {
            return Co.TELEFONICA_TRICOM_NAME;
        }
        else if (id == Co.TELEFONICA_DIGICEL) {
            return Co.TELEFONICA_DIGICEL_NAME;
        }
        else if (id == Co.TELEFONICA_NATCOM) {
            return Co.TELEFONICA_NATCOM_NAME;
        }
    }

    let onRequestResult = function(data) { console.log("RecargasActivity.onRequestResult()");
        if (data.success) {
            requestNew(data.company, data.monto, data.phone, data.serial);
        }
        else {
            ui.loadingStop();
            ui.dialogError(data.msg);
        }
    }

    let requestNew = function (company, monto, phone, serial) {
        let data = querystring.stringify({
            'd_id': Server.getDeviceId(),
            'v_id': Vendedor.getId(),
            'r_id': serial,
            'company': company,
            'monto': monto,
            'phone': phone
        });

        let options = {
            host: "fmlotterypanel.com",
            port: 443,
            path: url_request,
            method: "POST",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': data.length
            }
        };

        let req = https.request(options, function (res) {
            let responseString = "";

            res.on("data", function (data) {
                responseString += data;
                // save all the data from response

            });
            res.on("end", function () {
                console.log(responseString);
                ui.loadingStop();
                try {
                    let data = JSON.parse(responseString);
                    if (data.success) {
                        new PrinterRecarga(data).print();
                        requestHistory();
                    }
                    else {
                        ui.dialogError(data.msg);
                    }
                }
                catch(err) {
                    ui.dialogError(err);
                }

            });
        });

        req.write(data);
        req.end();
    }

    let requestVoid = function (id) {
        let data = querystring.stringify({
            'd_id': Server.getDeviceId(),
            'v_id': Vendedor.getId(),
            'reg_id': id
        });

        let options = {
            host: "fmlotterypanel.com",
            port: 443,
            path: url_request_cancel,
            method: "POST",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': data.length
            }
        };

        let req = https.request(options, function (res) {
            let responseString = "";

            res.on("data", function (data) {
                responseString += data;
            });

            res.on("end", function () {
                ui.loadingStop();
                try {
                    let data = JSON.parse(responseString);
                    if (data.success) {
                        ui.dialogSuccess(data.msg);
                        requestHistory();
                    }
                    else {
                        ui.dialogError(data.msg);
                    }
                }
                catch(err) {
                    ui.dialogError(err);
                }
            });
        });

        ui.loadingStart(_t('consultando'));
        req.write(data);
        req.end();
    }

    let requestHistory = function () {
        Server.send({
            'action': packet.RECARGA_HISTORY,
            'fecha_desde': $("#daterange_fecha_desde").val(),
            'fecha_hasta': $("#daterange_fecha_hasta").val(),
            'detallado': 0
        });
    }

    let onHistoryResult = function (data) { console.log("VentaActivity.reload()");
        domTableJugadas.empty();

        let recargas = data.recargas;
        let html;
        recargas.forEach(function (row, index) {
            html = '<tr'+(index<=5?' id="' +row.id+ '"':'')+'>' +
                '<td>' + row.fecha + '</td>' +
                '<td>' + row.compania + '</td>' +
                '<td>' + row.telefono + '</td>' +
                '<td>' + row.monto + '</td>' +
                '<td style="text-align: center"><span class="label label-'+(row.estatus==1?'success':'warning')+'">' + (row.estatus==1?'Enviada':'Cancelada') + '</span></td>' +
                '</tr>';

            domTableJugadas.append(html);
        });

        let total = filter.int(data.ventas.total);
        $('#jugadas_total_monto').text('$ ' + total.formatMoney(0, '.', ','));
    }

    let init = function () {
        if (!App.isActivePage(Co.PAGE_RECARGAS)) {
            App.setCurrentPage(Co.PAGE_RECARGAS);
            initHtml();
            initListeners();
            requestHistory();
        }
    }

    return {
        init: init,
        onRequestResult: onRequestResult,
        onHistoryResult: onHistoryResult,
    }
}();