let t_h_v;

let active_row=false;
let active_obj=false;


document.addEventListener('DOMContentLoaded', function () {
    //DataTables Historial Ventas - Ajax
    t_h_v = $('#t_ventas').DataTable({
        "aPreocesing": true,
        "aServerSide": false,
        "ajax": {
            "url": "" + base_url + 'ventas/listar_ventas',
            "dataSrc": ""
        },
        "columns": [{"data": "id"},
                    {"data": "codcliente"},            
                    {"data": "nombre"},
                    {"data": "fecha"},
                    {"data": "total"},                    
                    {"data": "estado"},
                    {"data": "vendedor"},
                    {"data": "autorizacion"},                    
               ],
        "columnDefs": [
                { responsivePriority: 30000, targets: -2 },
                { responsivePriority: 30000, targets: -1 }
            ],
        /*"drawCallback": function () {
            let api = this.api();
            $(api.columns(2).footer()).html(
                'Total:  Q.' + api.columns(2).data().sum().toFixed(2)
            )
            /*$(api.columns(2).footer()).html(
                'Total:  ' + api.columns(2, {
                    page: 'current'
                }).data().sum()
            )            
        },*/
        "dom": "<'row'<'col-sm-4'l><'col-sm-4 text-center'B><'col-sm-4'f>>" +
            "<'row'<'col-sm-12'tr>>" +
            "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        buttons,
        language,
        "resonsieve": true,
        "responsive": true,
        "bDestroy": true,
        "iDisplayLength": 10,
        "order": [
            [0, "desc"]
        ]
    });

    t_h_v.on( 'draw', function () {
        $('#t_ventas tbody tr').removeClass('selected');
        activo_buttons(false)
    } );

    $('#t_ventas tbody').on( 'click', 'tr', function (e) {
        let classList = e.currentTarget.classList;
       
        if (classList.contains('selected')) {
            classList.remove('selected');
        }
        else {
            t_h_v.rows('.selected').nodes().each((row) => row.classList.remove('selected'));
            classList.add('selected');
        }
        activo_buttons( t_h_v.row( this ).data()  );
    } );

    function activo_buttons(obj)
    {
        active_obj=obj;
        active_row=active_obj.id;

        if($('#t_ventas tbody tr.selected').length==0)
        {
            $('BUTTON.btn-toolbar-status').attr('disabled', 'disabled');
            $('BUTTON.btn-recuperar').hide();
            $('BUTTON.btn-eliminar').show();            
        } else {
            $('BUTTON.btn-toolbar-status').removeAttr('disabled');
            if(active_obj.estado_txt==='pagado' || active_obj.estado_txt==='pendiente') {
                $('BUTTON.btn-anular').show();
            } else {
                $('BUTTON.btn-anular').hide();
            }
            
            if(active_obj.autorizacion_estado===true) {
                $('BUTTON.btn-autorizar').show();
            } else {
                $('BUTTON.btn-autorizar').hide();
            }   
        }
    }
    

    $('#min').change(function (e) {
        t_h_v.draw();
    });
    //Busqueda por Rango de Fechas DataTables - Hasta
    $('#max').change(function (e) {
        t_h_v.draw();
    });
})
function btnAnular(id) {
    Swal.fire({
        title: 'Esta seguro de anular la Venta?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Si!',
        cancelButtonText: 'No'
    }).then((result) => {
        if (result.isConfirmed) {
            const url = base_url + 'ventas/anular/' + id;
            console.log(base_url + 'ventas/anular/' + id)
            const http = new XMLHttpRequest();
            http.open("GET", url, true);
            http.send();
            http.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    const res = JSON.parse(this.responseText);
                    alertas(res.msg, res.icono);
                    t_h_v.ajax.reload();
                }
            }
        }
    })
}
function btnFacturarFel(id)
{
    Swal.fire({
        title: 'Esta seguro de facturar la Venta?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Si!',
        cancelButtonText: 'No'
    }).then((result) => {
        if (result.isConfirmed) {
            const url = base_url + 'ventas/registrarFactura/' + id;
            const http = new XMLHttpRequest();
            http.open("GET", url, true);
            http.send();
            http.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    const res = JSON.parse(this.responseText);
                    if(res.icono=='success')
                    {
                        alertas(res.msg, res.icono);
                        t_h_v.ajax.reload();
                        //generar PDF                        
                    } else {
                        alerta_permanent(res.msg, res.icono);
                    }
                }
            }
        }
    })
}