let t_proveedor;
const form = document.getElementById('formulario');
const id_proveedor = document.getElementById('id');
const title = document.getElementById('title');
const btnAccion = document.getElementById('btnAccion');
const ruc = document.getElementById('ruc');
const nombre = document.getElementById('nombre');
const telefono = document.getElementById('telefono');
const direccion = document.getElementById('direccion');

let active_row=false;
let active_obj=false;

document.addEventListener('DOMContentLoaded', function () {
    //DataTables Proveedor - Ajax
    t_proveedor = $('#t_proveedor').DataTable({
        "aPreocesing": true,
        "aServerSide": false,
        "ajax": {
            "url": "" + base_url + "proveedor/listar",
            "dataSrc": ""
        },
        "columns": [{
            "data": "id"
        },
        { "data": "ruc" },
        { "data": "nombre" },
        { "data": "telefono" },
        { "data": "direccion" },
        { "data": "estado" },
        ],
        "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,
        "bDestroy": true,
        "iDisplayLength": 10,
        "order": [
            [0, "desc"]
        ]
    });

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

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

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

        if($('#t_proveedor tbody tr.selected').length==0)
        {
            $('BUTTON.btn-toolbar-status').attr('disabled', 'disabled');
        } else {
            $('BUTTON.btn-toolbar-status').removeAttr('disabled');
        }
    }

    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function (form) {
        form.addEventListener('submit', function (event) {
            event.preventDefault();
            if (form.checkValidity() === false) {
                event.stopPropagation();
                form.classList.add('was-validated');
            } else {
                const url = base_url + 'proveedor/registrar';
                const http = new XMLHttpRequest();
                http.open("POST", url, true);
                http.send(new FormData(this));
                http.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        const res = JSON.parse(this.responseText);
                        alertas(res.msg, res.icono);
                        if (res.icono == 'success') {
                            $('#nuevo_proveedor').modal('hide');
                            t_proveedor.ajax.reload();
                        }
                    }
                }
            }

        }, false);
    });
})

function frmProveedor() {
    id_proveedor.value = '';
    title.innerHTML = 'Nuevo Proveedor';
    btnAccion.innerHTML = 'Registrar';
    form.reset();
    $('#nuevo_proveedor').modal('show');
}

function btnEditarPr(id) {

    console.log(id)
    title.innerHTML = 'Modificar Proveedor';
    btnAccion.innerHTML = 'Modificar';
    const url = base_url + 'proveedor/editar/' + 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);
            id_proveedor.value = res.id;
            ruc.value = res.ruc;
            nombre.value = res.nombre;
            telefono.value = res.telefono;
            direccion.value = res.direccion;
            $('#nuevo_proveedor').modal('show');
        }
    }
}

function btnEliminarPr(id) {
    Swal.fire({
        title: 'Esta seguro de eliminar?',
        text: "El proveedor no se eliminará de forma permanente, solo cambiará el estado a inactivo!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Si!',
        cancelButtonText: 'No'
    }).then((result) => {
        if (result.isConfirmed) {
            const url = base_url + "proveedor/eliminar/" + 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);
                    if (res.icono == 'success') {
                        t_proveedor.ajax.reload();
                    }                    
                }
            }
        }
    })
}

function btnReingresarPr(id) {
    Swal.fire({
        title: 'Esta seguro de reingresar?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Si!',
        cancelButtonText: 'No'
    }).then((result) => {
        if (result.isConfirmed) {
            const url = base_url + "proveedor/reingresar/" + 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);
                    if (res.icono == 'success') {
                        t_proveedor.ajax.reload();
                    } 
                }
            }

        }
    })
} //fin proveedores