$(".formAddSql").submit(function(e) {
    e.preventDefault();
    e.stopPropagation();
    
    get_ajax(get_form('.formAddSql'), 'sistema/ajax/migration_ajax/insert_sql', 
        success =>{
            location.reload();
        },
        erro => {
            msgErro('.msgAddSql',erro);
        });
});

$(".btnDelete").on('click', function(){
    $(this).addClass('d-none');
    $(this).parents(".formAtualizaSql").find('.divButton').removeClass('d-none');
});

$(".btnDelNao").on('click', function(){
    $(this).parents(".formAtualizaSql").find('.divButton').addClass('d-none');
    $(this).parents(".formAtualizaSql").find('.btnDelete').removeClass('d-none');
});

$(".btnActTipo").on('click', function(){
    
    $("button[type=submit]", $(this).parents(".formAtualizaSql")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});

$(".formAtualizaSql").submit(function(e) {
    e.preventDefault();
    e.stopPropagation();
    
    $tipo = $("button[type=submit][clicked=true]").data("tipo");
    
    $data = get_form(this);
    
    if($tipo == "update"){
        
        loadButton($('.btnUpdate'));
        get_ajax($data, 'sistema/ajax/migration_ajax/atualiza_sql',  
        success =>{
            msgSuccess($(this).find('.msgRetorno'),success);
            $(this).find('.data_hora').html(success.update['0'].data_hora);
            $(this).find('.responsavel').html(success.update['0'].responsavel);
            
            $(this).find('.alert').fadeTo(2000, 500).slideUp(500, function(){
                $(this).slideUp(500);
            });
        },
        erro => {
            msgErro('.msgRetorno',erro);
        });
    }
    if($tipo == "delete"){
        
        get_ajax($data, 'sistema/ajax/migration_ajax/inativa_sql',  
        success =>{
            msgSuccess($(this).find('.msgRetorno'),success);
            $(this).find('.alert').fadeTo(2000, 500).slideUp(500, function(){
                $(this).slideUp(500);
            });
            $(this).find('.cardSql').remove();
        },
        erro => {
            msgErro('.msgRetorno',erro);
        });
    }
});

function get_ajax($data = [], $uri, $success = null, $error = null ){
    
    if($error == null)
    {
        $error = function($erro){
            if($erro.msg != undefined)
                alert($erro.msg);
            else{
                console.log($erro.responseText);
                    msg = $($($erro.responseText)[7]).find('h1').text();
                if(msg == '')
                    msg = $($($erro.responseText)[8]).find('h1').text();
                if(msg == '')
                    msg =   $($erro.responseText).find('h4').text()+'\n'+$($($erro.responseText).find('p')[1]).text();
                if(msg == '' || msg == undefined || msg == 'undefined')
                    msg =   "ERRO!";
                alert(msg);
            }
        };
    }
    
    if($success == null)
    {
        $success = function(e){
            //e);
        };
    }
    
    $.ajax({
		url: base_url+$uri, 
		dataType: 'json',
		type: 'POST',
		data: $data,
		success: function(retorno)
		{
		    loadButton(null,false);
		    if(retorno.valid == false)
		    {   
		        $error(retorno);
		    }
		    else
		    {
		        $success(retorno)
		    }
		},
		error: function(error)
		{
		    loadButton(null,false);
		    $error(error);
		}
    });
    
}

function msgSuccess($div, $success){
    setAlert($div, $success.msg, 'success');
}
function msgErro($div, $erro){
    if($erro.msg != undefined)
        setAlert($div, $erro.msg, 'danger');
    else{
        //$msg = "<b>"+$($($erro.responseText)[7]).find('h1').text()+"</b>, "+$($($erro.responseText)[7]).find('p').text()
            console.log($erro.responseText);
                msg = $($($erro.responseText)[7]).find('h1').text();
            if(msg == '')
                msg = $($erro.responseText)[8].find('h1').text();
             if(msg == '')
                msg =   $($erro.responseText).find('h4').text()+'\n'+$($($erro.responseText).find('p')[1]).text();
            if(msg == '')
                msg =   "ERRO!";
                    
        setAlert($div, msg, 'danger');
    }
}

function setAlert($div, $msg, $cor){
    $html = '<div class="alert alert-'+$cor+' alert-dismissible fade show" role="alert">' +
         $msg +
    '    <button class="close" type="button" data-dismiss="alert" aria-label="Close">' +
    '        <span aria-hidden="true">×</span>' +
    '    </button>' +
    '</div>';
    $($div).html($html); 
}
// VARIAVES PARA O LOAD BUTTON
var textLoad = "<i class='fa fa-circle-o-notch fa-spin'></i>";
var textButton = '';
var btn = null;
function loadButton(button = null, disabled = true)
{
    if(button != null)
        btn = button;
        
    if(disabled == true)
    {
        textButton = btn.html();
        btn.prop('disabled', true);
        btn.html(textLoad);//+' '+textButton
    }
    else
    {
	    if(btn != null){
            btn.prop('disabled', false);
	    	btn.html(textButton);
	    	btn = null;
	    }
    }
}

function get_form($form)
{
    data = [];
    var nameRadio = [];
    
    $($form).find('input:not([type=radio]):input:not([type=checkbox]):input:not([type=file])').each(function(key,value){
        if(this.name != "")
            data.push({"name": this.name, "value": this.value});
    });
    
    $($form).find('input[type=file]').each(function(key,value){
        if(this.name != ""){
            data.push({"name": this.name, "value": $(this).data('value')});
        }
    });
    
    $($form).find('textarea').each(function(key,value){
       
        if(this.name != "")
        {
            data.push({"name": this.name, "value": this.value});
        }
    });
    
    $($form).find('input[type=radio]').each(function(key,value){
        if(nameRadio[this.name] == undefined)
            nameRadio[this.name] = '';
        if($(this).is(':checked'))
            nameRadio[this.name] = this.value;
    });
    
    for(var name in nameRadio){
        data.push({"name": name, "value": nameRadio[name]});
    };
    
    $($form).find('select option:selected').each(function(key,value)    {
        if(this.parentElement.localName == 'select')
            data.push({"name": this.parentElement.name, "value": this.value});
            
        if(this.parentElement.parentElement.localName == 'select')
            data.push({"name": this.parentElement.parentElement.name, "value": this.value});
    });
    
    $($form).find('input[type=checkbox]:checked').each(function(key,value)    {
        if(this.name != "")
            data.push({"name": this.name, "value": this.value});
    });
    
    $($form).find('input[type=checkbox]:not(:checked)').each(function(key,value)    {
        if(this.name != "")
            data.push({"name": this.name, "value": ""});
    });
    
    
    return data;
}