let dtUsuarios = null;

let initDataTable = function () {
    dtUsuarios = $("#datatable").DataTable({
        dom: `
            <'row'<'col-sm-2'f><'col-sm-4'<"toolbar">><'col-sm-6'p>>
            <'row'<'col-sm-12't>>
            <'row'<'col-sm-5'i><'col-sm-7'p>>
        `,
        language: {
            url: '//cdn.datatables.net/plug-ins/1.10.21/i18n/Spanish.json'
        },
        serverSide: true,
        ajax: {
            url: $urlBase + "/configuracion/usuarios/get",
            data: function (data){
                
            },
            dataType: "json"
        },
        pageLength: 50,
        columns: [{
            data: "id",
            orderable: false,
                render: function(data, type, row, meta) {
                    if (type === "display") {
                        data = `<div class="custom-control custom-checkbox">
                            <input type="checkbox" class="custom-control-input dt-checkboxes">
                                <label class="custom-control-label">&nbsp;</label>
                            </div>`;
                    }
                    return data;
                },
                checkboxes: {
                    selectRow: true,
                    selectAllRender: `<div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input dt-checkboxes">
                            <label class="custom-control-label">&nbsp;</label>
                    </div>`
                }
            },
            { data: "nombre", orderable: true, className: "text-left" },
            { data: "apellido", orderable: true, className: "text-left" },
            { data: "tipoUsuario", orderable: true, className: "text-left" },
            { data: "email", orderable: true, className: "text-left" },
            { data: "telefonos", orderable: true, className: "text-center" }
        ],
        columnDefs: [{
            title: "Accion",
            targets: 6,
            data: null,
            className: "text-center",
            defaultContent: `<div>
                <a href="javascript:void(0);" class="action-icon" id="btnEditar">
                    <i class="mdi mdi-square-edit-outline"></i>
                </a>
                <a href="javascript:void(0);" class="action-icon" id="btnEliminar">
                    <i class="mdi mdi-delete"></i>
                </a>
            </div>`
        }],
        select: {
            style: "multi"
        },
        order: [[1, "desc"]],
        drawCallback: function() {
            $(".dataTables_paginate > .pagination").addClass("pagination-rounded");
        },
        info: true,
        initComplete: function (){ }
    });

    $("#datatable tbody").on("click", "#btnEditar, #btnEliminar", function (){
        
        let oTable = $("#datatable").DataTable();
        var data = oTable.row($(this).parents('tr')).data();
        
        if(this.id == "btnEditar"){
            $.ajax({
                method: 'GET',
                url: $urlBase + `/configuracion/usuarios/edit/${data.id}`,
                contentType: false,
                processData: false,
                success: function (datos){

                    clearFormFields("form");
                    clearErrorMsg();

                    $("#id").val(data.id);
                    $("#nombre").val(data.nombre);
                    $("#apellido").val(data.apellido);
                    $("#email").val(data.email);
                    $("#usuario").val(data.usuario);
                    $("#telefonos").val(data.telefonos);
                    $("#idEmpresa").val(data.idEmpresa);
                    $("#tipoUsuario").val(data.tipoUsuario);
                    $("#hab").val(data.hab);
                    
                    $("#modalUsuario").modal("show");
                    $("#modalUsuario .modal-title").html(`Editar el Usuario [${data.id}]`);
                    $(".modal-backdrop").css("zoom", "1.2");
                }
            });
        }

        if(this.id == "btnEliminar"){
            Swal.fire({
                title: "Confirmacion",
                text: "Seguro que desea inhabilitar el Usuario: " + data.usuario,
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "SI",
                cancelButtonText: "NO"
              }).then(function (result) {
                if (result.value) {
                    $.ajax({
                        method: 'GET',
                        url: $urlBase + "/configuracion/usuarios/destroy/" + data.id,
                        success: function (response){
                            if(response.success){
                                Swal.fire({
                                    title: '',
                                    text: response.message,
                                    type: 'success',
                                    confirmButtonClass: 'btn btn-confirm mt-2'
                                });
                                $("#datatable").DataTable().draw();                    
                            }
                        }
                    });
                }
            });
        }
    });
}

function printErrorMsg (msg) {
    $(".print-error-msg").find("ul").html('');
    $(".print-error-msg").css('display','block');
    $.each( msg, function( key, value ) {
        $(".print-error-msg").find("ul").append('<li>'+value+'</li>');
    });
}

function clearErrorMsg () {
    $(".print-error-msg").find("ul").html('');
    $(".print-error-msg").css('display','none');
}

function clearFormFields(formId){
    document.querySelector(`#${formId}`).reset();
}

$(document).ready(function (){
   
    $("#btnNuevoUsuario").on("click", function (e){
        $("#id").val(0);
        $("#modalUsuario").modal("show");
        $("#modalUsuario .modal-title").html("Alta de Usuario");
        $(".modal-backdrop").css("zoom", "1.2");
        clearFormFields("form");
        clearErrorMsg();
    });
    
    $("#form").on("submit", function (e){
        e.preventDefault();
        
        let form = document.getElementById("form");
        let formData = new FormData(form);
        
        $.ajax({
            method: "POST",
            url: `${$urlBase}/configuracion/usuarios/store`,
            data: formData,
            dataType: 'JSON',
            contentType: false,
            processData: false,
            beforeSend: function (){
                
            },
            success: function (response){
                if($.isEmptyObject(response.error)) {      
                    Swal.fire({
                        title: '',
                        text: response.message,
                        type: 'success',
                        confirmButtonClass: 'btn btn-confirm mt-2'
                    }).then(function (){
                        location.href = $urlBase + "/configuracion/usuarios";
                    });
                }else{
                    console.log(response.error);
                    printErrorMsg(response.error);    
                }
            }
        });
    });
});