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

    let dom = App.getContainerMain();
    let iconPrint;

    let ticket_id = 0;

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

        let html = '' +
            '<section class="box-typical">' +
            '   <header class="box-typical-header">' +
            '       <div class="tbl-row">' +
            '           <div class="tbl-cell tbl-cell-title col-md-2"><h3>Tickets</h3></div>' +
            '           <div class="tbl-cell tbl-cell-title col-md-3">' +
            '               <div class="input-group date">' +
            '                   <input id="daterange_fecha" 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-2">' +
            '               <select class="select2-arrow manual select2-no-search-arrow" id="tickets_tipo">' +
            '                   <option value="-1">Todos</option>' +
            '                   <option value="1">Pendientes</option>' +
            '                   <option value="2">Ganadores</option>' +
            '                   <option value="3">Perdedores</option>' +
            '                   <option value="0">Anulados</option>' +
            '               </select>' +
            '           </div>' +
            '           <div class="tbl-cell tbl-cell-action-bordered"><button type="button" class="action-btn" id="icon-print"><i class="fa fa-print" aria-hidden="true"></i></button></div>' +
            '       </div>' +
            '   </header>' +
            '   <div class="box-typical-body typical-body2">' +
            '       <div class="table-responsive">' +
            '           <table id="table_tickets" class="table table-bordered table-hover table-sm">' +
            '               <thead>' +
            '                   <tr>' +
            '                       <th>No.</th>' +
            '                       <th width="20%">Hora</th>' +
            '                       <th width="20%">Monto</th>' +
            '                       <th width="20%">Estado</th>' +
            '                       <th width="5%"></th>' +
            '                   </tr>' +
            '               </thead>' +
            '               <tbody></tbody>' +
            '           </table>' +
            '       </div>' +
            '   </div>' +
            '</section>';

        dom.append(html);

        iconPrint = $('#icon-print');
    }

    //TicketCopiar.activeTicket($(this).data('id'));
    //TicketAnular.activeTicket($(this).data('id'));

    let initListener = function () {
        /*$(".select2-icon").not('.manual').select2({
            templateSelection: select2Icons,
            templateResult: select2Icons
        });

        $(".select2-arrow").not('.manual').select2({
            theme: "arrow"
        });

        $('.select2-no-search-arrow').select2({
            minimumResultsForSearch: "Infinity",
            theme: "arrow"
        });*/

        let dateOps = ut.datePikerLocale();
        dateOps.singleDatePicker = true;
        $('#daterange_fecha').daterangepicker(dateOps);
        $('#daterange_fecha').on('hide.daterangepicker', function() {
            initRequest();
        });

        $('#table_tickets').on('click', '.span_link', function () {
            ticket_id = $(this).data('id');

            Server.send({
                'action': packet.TICKETJUGADAS,
                'ticketId': ticket_id
            });
        });

        $('#tickets_tipo').select2({
            minimumResultsForSearch: "Infinity",
            theme: "arrow"
        });

        $('#tickets_tipo').on('change', function() {
            //alert( this.value );
            initRequest();
        });

        iconPrint.click(function() {
            print();
        });
    }

    let initRequest = function () {
        let data = {
            'action': packet.TICKETS,
            'fecha': $("#daterange_fecha").val(),
            'estatus':  $("#tickets_tipo").val()
        }

        Server.send(data);
    }

    let onData = function (data) {
        Tickets.init(data.tickets);

        let table = $('#table_tickets tbody');
        table.empty();
        let count = table.children('tr').length + 1;

        let tickets = Tickets.getAll();
        for (let i=0; i<tickets.length; i++) {
            let t = tickets[i];

            let html = '<tr id="tr_tickets_' +count+ '">' +
                (t.isPremiado()?'<td><b>' + t.getTicket() + '</b></td>':'<td>' + t.getTicket() + '</td>') +
                (t.isPremiado()?'<td><b>' + t.getFecha() + '</b></td>':'<td>' + t.getFecha() + '</td>') +
                (t.isPremiado()?'<td style="text-align: right"><b>' + t.getMonto() + '</b></td>':'<td style="text-align: right">' + t.getMonto() + '</td>') +
                (t.isPremiado()?'<td><b>' + t.getPremio() + '</b></td>':'<td>' + t.getEstatus() + '</td>') +
                '<td><span class="span_link" data-id="' +t.getId()+ '"><i class="fa fa-external-link-square"></i></span></td>' +
                '</tr>';

            table.append(html);
        }
    }

    let onDataJugadas = function (data) {

        let html_jugadas = '';
        let jugadas = data.jugadas;
        for (let i=0; i<jugadas.length; i++) {
            let j = jugadas[i];
            let jugada = new Jugada(j.numero, j.loteria, j.valor, j.jugstr);

            html_jugadas += '<tr>' +
                '<td>' + jugada.getJugstr() + '</td>' +
                '<td>' + jugada.getNumero2() + '</td>' +
                '<td>' + jugada.getLoteriasAbreviado() + '</td>' +
                '<td style="text-align: right">' + jugada.getValor() + '</td>' +
                '</tr>';
        }

        let html = '' +
            '           <table id="table_tickets_jugadas" class="table table-bordered table-condensed table-striped">' +
            '               <thead>' +
            '                   <tr>' +
            '                       <th width="10%">PR</th>' +
            '                       <th width="40%">Número</th>' +
            '                       <th width="30%">Lotería</th>' +
            '                       <th width="20%">Valor</th>' +
            '                   </tr>' +
            '               </thead>' +
            '               <tbody>' + html_jugadas + '</tbody>' +
            '           </table>'

            $.confirm({
                title: 'Jugadas',
                content: html,
                animation: 'scale',
                boxWidth: '30%',
                closeAnimation: 'scale',
                backgroundDismiss: true,
                useBootstrap: false,
                buttons: {
                    cancel: {
                        text: 'Cerrar'
                    },
                    copy: {
                        text: 'Copiar',
                        btnClass: 'btn-blue',
                        keys: ['enter', 'shift'],
                        action: function() {
                            TicketCopiar.activeTicket(ticket_id);
                            TicketCopiar.copiarPreguntar();
                        }
                    },
                    void: {
                        text: 'Anular',
                        btnClass: 'btn-danger',
                        action: function() {
                            requestVoid(ticket_id);
                        }
                    }
                }
            });
    }
    
    let requestVoid = function (ticket) {
        $.confirm({
            title: '¿Desea anular el ticket?',
            content: "Se enviará una solicitud de cancelación",
            buttons: {
                cancel: function () {},
                confirm: {
                    text: 'Sí, proceder',
                    btnClass: 'btn-blue',
                    keys: ['enter'],
                    action: function() {
                        Server.send({
                            'action': packet.TICKET_REQUEST_VOID,
                            'ticketId': ticket
                        });
                    }
                }
            }
        });
    }

    let onResultRequestVoid = function(data) {
        if (data.success) {
            ui.dialogSuccess("Solicitud enviada!");
        }
        else {
            ui.dialogError(data.msg);
        }
    }

    let print = function () {
        if (!Tickets.countGanadores()) {
            $.alert({
                title: 'No hay tickets ganadores',
                content: '',
                animation: 'scale',
                closeAnimation: 'bottom',
                backgroundDismiss: true,
                buttons: {
                    okay: {
                        text: 'Cerrar',
                        btnClass: 'btn-blue',
                        action: function () {
                            // do nothing
                        }
                    }
                }
            });
        }
        else {
            PrinterGanadores.print($("#daterange_fecha").val());
        }
    }

    let init = function () {
        if (!App.isActivePage(Co.PAGE_REPORTE_TICKETS)) {
            App.setCurrentPage(Co.PAGE_REPORTE_TICKETS);

            initHtml();
            $("#daterange_fecha").val(Time.fecha("DD/MM/YYYY"));

            initListener();
            initRequest();
        }
    }

    return {
        init: init,
        onData: onData,
        onDataJugadas: onDataJugadas,
        onResultRequestVoid: onResultRequestVoid,
        print: print
    }
}();