import Ajax from '../../components/ajax.js';

$(()=>{

    $('#buscadorPedidos').on('keydown', function(e) {
        if (e.key === 'Enter' || e.keyCode === 13) {
            e.preventDefault(); // Evita el submit si está dentro de un form
            let search = $(this).val().trim();
            new Ajax(
                '/logistica/buscar/'+search,
                {},
                {},
                function(response) {
                    if(!response.status){
                        popErrorAlert(response.message);
                    }
                    if(response.data){

                        window.open(`${window.location.origin}/logistica/envio/${response.data.id_envio}`);
                    }
                    
                },
                function(xhr, status, error) {
                    if(status == 'error' && typeof(error)== 'string')
                        popErrorAlert(error);
                    else
                        popErrorAlert(error.responseJSON.message);
                }
            ).get();
            
        }
    });

    const tableEnvios = $('#tableOfEnvios').DataTable({
        processing: true,
        serverSide: true,
        autoWidth: true,
        responsive: true,
        scrollX: true,
        orderCellsTop: true,
        lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500],
        pageLength: 50,
        "dom": 'lBrtip',
        "ajax": {
            "url": "/logistica/datatableEnvios",
        },
        "columns": [
            { "data": "id" },
            { "data": "pedidos" },
            { "data": "num_lineas" },
            { "data": "att" },
            { "data": "direccion" },
            { "data": "ciudad" },
            { "data": "pais" },
            { "data": "cp" },
            { "data": "email" },
            { "data": "telefono" },
            { 
                "data": "finalizado",
                "className": "text-center",
            },
            { "data": "action" }

        ],
        "language": {
            url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
        },
        "columnDefs": [
            {
                orderable: false,
                searchable: false,
                targets: [11]
            },
        ],
        "order": [[0, "desc"]],
    });

    $(document).on('click', '.btn-edit', function (e) {
        window.location.href = '/logistica/envio/' + $(this).attr('data-id');
    });
    
});