let dtRoles = null;

let initDataTable = function () {
    dtRoles = $("#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/roles/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: "id", orderable: true, className: "text-center" },
            { data: "name", orderable: true, className: "text-left",
                render: function(data, type, row, meta) {
                    return data.charAt(0).toUpperCase() + data.slice(1);
                }
            },
            { data: "permisos", orderable: true, className: "text-left",
                render: function(data, type, row, meta) {
                    let listaPermisos = "";
                    const permisos = data.split(",");
                    permisos.forEach(p => {
                        listaPermisos += `
                            <span class="badge bg-soft-success text-success mr-1 p-1 mb-2">
                                ${p.toUpperCase()}
                            </span>
                        `;
                    });
                    return listaPermisos;
                }
            }
            
        ],
        columnDefs: [{
            title: "Accion",
            targets: 4,
            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>`
        },
        { width: "100px", targets: 1 },
        { width: "200px", targets: 2 }],
        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/roles/edit/${data.id}`,
                contentType: false,
                processData: false,
                success: function (datos){
                    clearFormFields("form");
                    clearErrorMsg();

                    $("#id").val(datos.id);
                    $("#rol").val(datos.name);

                    datos.permissions.forEach((e) => {
                        $(`#permiso_${e.id}`).prop("checked", true);
                    });
                    

                    $("#modalRol").modal("show");
                    $("#modalRol .modal-title").html(`Editar el Rol [${datos.id}]`);
                    $(".modal-backdrop").css("zoom", "1.2");
                }
            });
        }

        if(this.id == "btnEliminar"){
            /*Swal.fire({
                title: "Confirmacion",
                text: "Seguro que desea inhabilitar al usuario: " + data.nombreCompleto,
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "SI",
                cancelButtonText: "NO"
              }).then(function (result) {
                if (result.value) {
                    $.ajax({
                        method: 'GET',
                        url: $urlBase + "/admin/configuracion/usuarios/eliminar/" + data.id,
                        success: function (response){
                            if(response.success){
                                Swal.fire({
                                    title: '',
                                    text: response.message,
                                    type: 'success',
                                    confirmButtonClass: 'btn btn-confirm mt-2'
                                });
                                $("#usuarios-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 (){
    
    $("#btnNuevaRol").on("click", function (e){
        $("#id").val(0);
        $("#modalRol").modal("show");
        $("#modalRol .modal-title").html("Alta de Rol");
        $(".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);
        
        let url = `${$urlBase}/configuracion/roles/store`;
        if(e.target.id.value != 0){
            url = `${$urlBase}/configuracion/roles/update`;
        }

        $.ajax({
            method: "POST",
            url: url,
            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/roles";
                    });
                }else{
                    console.log(response.error);
                    printErrorMsg(response.error);    
                }
            }
        });
    });
});