$('.datepicker').datepicker({
	format: 'dd/mm/yyyy',
	endDate: '0d',
	autoclose: true,
	language: 'pt-BR'
});

$('.datepicker').mask('00/00/0000');

$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
$('#tabelaLog').html('<table id="tbLog" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
$('#tbLog').dataTable({
	"data": [],
	"order": [[ 1, 'desc' ]],
	"columns": [{"title": "Ação Executada"}, {"title": "Data"}, {"title": "Nome do Usuário"}, {"title": "Login do Usuário"},{"title": "Importância"},{"title": "Tipo"},{"title": "Opções", "className": "table-buttons"}, {"title": "ID"}],
	"columnDefs": [{"targets": 6, "orderable": false}, {"targets": 7,"visible": false}],
	"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
	responsive: true,
	"deferRender": true
});

function modal_visualizar(id){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modal_visualizar_2(id);
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modal_visualizar_2(id);
	}
}

function modal_visualizar_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_log_adm",
			data: {'id' : id},
			success: function(data){
				$('.preloader').css({display:"none"});
				if(data == '-1') {window.location.href = "./"; return;}
				if(data.substring(0,2) == "-2") {toastr.clear(); toastr.error(data.substring(2)); return;}
				$('#modal-sistema-conteudo').html(data);
				$('#modal-sistema').modal();
			},
			beforeSend: function(){
				$('.preloader').css({display:"block"});
			},
			complete: function(){
				$('.preloader').css({display:"none"});
			},
			error: function(){
				$('.preloader').css({display:"none"});
				toastr.clear(); toastr.error("Houve um erro ao abrir modal."); return;
			}
		});
	});
}

function carregar_dados(){
	$(document).ready(function() {
		var dados = jQuery('#formLog').serialize();
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_log_adm",
			data: dados,
			success: function(data){
				$('.preloader').css({display:"none"});
				if(data == '-1') {window.location.href = "./"; return;}
				if(data.substring(0,2) == "-2") {toastr.clear(); toastr.error(data.substring(2)); return;}
				var json = JSON.parse(data);
				var table_data = [];
				for (var i=0; i < json.length; i++){
					var date = Date.parse(json[i].data).toString('dd/MM/yyyy HH:mm:ss');
					var editar = "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_visualizar("+json[i].id+")' class='btn btn-default text-orange' title='Clique para visualizar a descrição.'><i class='fa fa-list'></i></a></div>";
					table_data[i] = ["",json[i].acao, date, json[i].usuario, json[i].login, json[i].importancia, json[i].tipo, editar, json[i].id, json[i].descricao];
				}
				$(document).ready(function() {
					const colunas = [{},{"title": "Ação Executada"}, {"title": "Data"}, {"title": "Nome do Usuário"}, {"title": "Login do Usuário"},{"title": "Importância"},{"title": "Tipo"},{"title": "Opções", "className": "table-buttons"}];
					$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
					$('#tabelaLog').html('<table id="tbLog" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
					if(json.length >= 2){
						$("#tbLog").append(
							$('<tfoot style="display: table-header-group;" />').append(`<tr>${colunas.map((i) => "<th></th>").join("")}</tr>`)
						);
						$('#tbLog tfoot tr th').each(function (index) {
							if(index !== 7){
								$(this).html('<input type="text" style="width: 100%" class="form-control" placeholder="" />');
							}
						});
					}
					$('#tbLog').dataTable({
						"data": table_data,
						"order": [[ 2, 'desc' ]],
						"columns": colunas,
						"columnDefs": [{"targets": 7, "orderable": false},{className: 'control', orderable: false, targets: 0, width: "5%"}],
						"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
						responsive: {
						    details: {
						    	type: 'column',
						        display: $.fn.dataTable.Responsive.display.modal( {
						            header: function ( row ) {
						                return '<span style="margin-right: 10px"><b>Dados da Entrada</b></span>';
						            }
						        } ),
						        renderer: function ( api, rowIdx, columns ) {
						        	text = "";
						        	text += columns[6].data + "<br>";
						        	for(i = 0;i < columns.length;i++){
						        		column = columns[i];
						        		if(i == 6) { continue; }
						        		if(i > 0) text += "<br>";
						        		text += "<b>" + column.title + ": </b>" + column.data;
						        	}
						        	return text;
						        }
						    }
						},
						initComplete: function () {
							// Apply the search
							this.api()
								.columns([1,3,4,5,6])
								.every(function () {
									var column = this;
                    var select = $('<select class="form-control"><option value=""></option></select>')
                        .appendTo($(column.footer()).empty())
                        .on('change', function () {
                            var val = $.fn.dataTable.util.escapeRegex($(this).val());
                            column.search(val ? '^' + val + '$' : '', true, false).draw();
                        });
                    column
                        .data()
                        .unique()
                        .sort()
                        .each(function (d, j) {
                            select.append('<option value="' + d + '">' + d + '</option>');
                        });
									var that = this;
									$('input', this.footer()).on('keyup change clear', function () {
										if (that.search() !== this.value) {
											that.search(this.value).draw();
										}
									});
									
								});
							this.api()
								.columns([0,2])
								.every(function () {
									var that = this;
									$('input', this.footer()).on('keyup change clear', function () {
										if (that.search() !== this.value) {
											that.search(this.value).draw();
										}
									});
								});
						},
						"deferRender": true,
						"createdRow": function ( row, data, index ) {
							$(row).addClass("id"+data[8]);
						}
					});
				});
			},
			beforeSend: function(){
				$('.info-box-number').html('<div class="preloader"><i class="fa fa-refresh fa-spin"></i></div>');
				$('.preloader').css({display:"block"});
			},
			complete: function(){
				$('.preloader').css({display:"none"});
			},
			error: function(){
				$('.preloader').css({display:"none"});
				toastr.clear(); toastr.error("Houve um erro ao atualizar"); return;
			}
		});
	});
}

function fechar_modal(){
	$('#modal-sistema').modal('hide');
}

function atualizar(){
	var valor = $('#data').val();
	if(valor == "CUSTOM_DATE")
		$('.datadiv').removeClass("hide");
	else{
		$('.datadiv').addClass("hide");
		carregar_dados();
		salvarFiltro(valor,'','');
	}
}

pegarFiltro(function(filtro,data1,data2){
	$('#data').val(filtro);
	$('#datainicial').val(data1);
	$('#datafinal').val(data2);
	if(filtro == "CUSTOM_DATE")
		$('.datadiv').removeClass("hide");
	carregar_dados();
});

$('#data, #switch').change(function(){ atualizar(); });
$('#datapersonalizada').click(function(){
	salvarFiltro($('#data').val(),$('#datainicial').val(),$('#datafinal').val());
	carregar_dados();
});