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

$(() => {

    let otsFilter = '';
    const tipo_envio = $('#tipo_envio').val();

    const selectPedidos = new ClassSelect($('#buscadorPedidos'), '/logistica/selectForNewEnvio', "", true, {
        tipo_envio: () => $('#tipo_envio').val()
    });
    selectPedidos.init();
    const selectDirecciones = new ClassSelect($('#selectDirecciones'), '/logistica/selectDireccionForEnvio', "", true, {
        ot_id: () => selectPedidos.getVal()
    });
    selectDirecciones.init();


    selectPedidos.item.on('select2:open', () => {
        $('.select-direcciones').addClass('d-none');
        $('.add-envio').addClass('d-none');
    })
    selectPedidos.item.on('change', () => {
        selectDirecciones.empty();
        if(tipo_envio == 'ferro_prototipo')
            $('.add-envio').removeClass('d-none');
        else
            $('.select-direcciones').removeClass('d-none');
    })
    selectDirecciones.item.on('select2:open', () => {
        $('.add-envio').addClass('d-none');
    })

    selectDirecciones.item.on('change', () => {
        $('.add-envio').removeClass('d-none');
    })


    $('#btnAddEnvio').on('click', () => {
        let url = '';
        let data = {};
        if(tipo_envio == 'ferro_prototipo'){
            url = '/logistica/generateEnvioFerro';
            data = {
                ot_id: selectPedidos.getVal()
            };
        }
        else{
            url = '/logistica/generateEnvio';
            data = {
                ot_id: selectPedidos.getVal(),
                direccion: selectDirecciones.getText()
            };
        }
        $.post(
            url, 
            data, function (response) {
            if (response.status) {
                window.open(`${window.location.origin}/logistica/envio/${response.data.id_envio}`);
                selectDirecciones.empty();
                selectPedidos.empty();
                $('.select-direcciones').addClass('d-none');
                $('.add-envio').addClass('d-none');
            } else {
                popErrorAlert(response.message);
            }
        }).fail(function (xhr, status, error) {
            popErrorAlert(error);
        });
    })

    
    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",
            "data": function (d) {
                d.otsFilter = otsFilter; 
                d.tipo_envio = $('#tipo_envio').val();
            }
        },
        "columns": [
            { "data": "id" },
            { "data": "ots" },
            { "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');
    });

    $(document).on("keyup", ".envio-filter", (event) => {
        let columnName = $(event.currentTarget).attr("name");
        let columnIndex = $('#tableOfEnvios').DataTable().columns().eq(0).filter(function (index) {
            return $('#tableOfEnvios').DataTable().column(index).dataSrc() === columnName;
        })[0];
        $('#tableOfEnvios').DataTable().column(columnIndex).search($(event.currentTarget).val()).draw()
    })


    $(document).on("keyup", ".envio-filter-ots", (event) => {
        otsFilter = $(event.currentTarget).val(); 
        $('#tableOfEnvios').DataTable().ajax.reload();
    })

    $(document).on("change", ".envio-filter-select", (event) => {
        let columnName = $(event.currentTarget).attr("name");
        let columnIndex = $('#tableOfEnvios').DataTable().columns().eq(0).filter(function (index) {
            return $('#tableOfEnvios').DataTable().column(index).dataSrc() === columnName;
        })[0];
        $('#tableOfEnvios').DataTable().column(columnIndex).search($(event.currentTarget).val()).draw();
    });

});