$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
$('#tabelaGSuite').html('<table id="tbGSuite" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
$('#tbGSuite').dataTable({
	"data": [],
	"order": [[ 0, 'desc' ]],
	"columns": [{"title": "ID"},{"title": "Nome"}, {"title": "Status"},{"title": "CPF ou CNPJ"},{"title": "Venc."},{"title": "Valor"},{"title": "Qtd."},{"title": "Tipo"},{"title": "Opções"}],
	"columnDefs": [{"targets": 8, "orderable": false}],
	"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
	responsive: true
});

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

function modal_reenvio_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_reenvio_boleto",
			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 modal_editar(id){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modal_editar_2(id);
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modal_editar_2(id);
	}
}

function modal_editar_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_agendamento_gsuite",
			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 modal_confirmacao(id){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modal_confirmacao_2(id);
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modal_confirmacao_2(id);
	}
}

function modal_confirmacao_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_agendamento_deletar",
			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-confirmacao-conteudo').html(data);
				$('#modal-confirmacao').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 modalNovoAgendamento(){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modalNovoAgendamento_2();
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modalNovoAgendamento_2();
	}
}

function modalNovoAgendamento_2(){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_novo_agendamento_gsuite",
			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 executarVerificacao(){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			executarVerificacao_2();
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		executarVerificacao_2();
	}
}

function executarVerificacao_2(){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/verificar_boletos",
			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;}
				toastr.clear(); toastr.success("Verificação executada com sucesso!");
			},
			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 executar a verificação!"); return;
			}
		});
	});
}

function carregar_dados(){
	$(document).ready(function() {
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_gsuite",
			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 = [];
				var quantidade = 0;
				for (var i=0; i < json.length; i++){
					var editar = "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_reenvio("+json[i].id+")' class='btn btn-default text-green' title='Clique para reenviar o boleto.'><i class='fa fa-send'></i></a><a href= 'javascript:void(0);' onclick='modal_editar("+json[i].id+")' class='btn btn-default text-orange' title='Clique para editar o agendamento.'><i class='fa fa-edit'></i></a><a href= 'javascript:void(0);' onclick='modal_confirmacao("+json[i].id+")' class='btn btn-default text-red' title='Clique para deletar o agendamento.'><i class='fa fa-trash'></i></a></div>";
					table_data[i] = ["",json[i].nome, json[i].id, json[i].status, json[i].cpf_cnpj,json[i].vencimento, json[i].valor, json[i].quantidade,json[i].tipo, editar, json[i].telefone, json[i].email, json[i].pesquisa];
					quantidade++;
				}
				$(document).ready(function() {
					$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
					$('#tabelaGSuite').html('<table id="tbGSuite" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
					$('#tbGSuite').dataTable({
						"data": table_data,
						"order": [[ 2, 'desc' ]],
						"columns": [{},{"title": "Nome"}, {"title": "ID"}, {"title": "Status"},{"title": "CPF ou CNPJ"},{"title": "Venc."},{"title": "Valor"},{"title": "Qtd."},{"title": "Tipo"},{"title": "Opções", "className": "table-buttons"},{"title": "Telefone"},{"title": "Email"}],
						"columnDefs": [{"targets": 9, "orderable": false},{className: 'control', orderable: false, targets: 0, width: "5%"}],
						"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
						"createdRow": function ( row, data, index ) {
							$(row).addClass("id"+data[2]);
							if($('td', row).eq(3).text() == "Ativo")
								$(row).css("background-color","#f9fffa");
							else
								$(row).css("background-color","#fbf2cc");
						},
						responsive: {
						    details: {
						    	type: 'column',
						        display: $.fn.dataTable.Responsive.display.modal( {
						            header: function ( row ) {
						                return '<span style="margin-right: 10px"><b>Dados do Agendamento</b></span>';
						            }
						        } ),
						        renderer: function ( api, rowIdx, columns ) {
						        	text = "";
						        	text += columns[8].data + "<br>";
						        	for(i = 0;i < columns.length;i++){
						        		column = columns[i];
						        		if(i == 8) { continue; }
						        		if(i > 0) text += "<br>";
						        		text += "<b>" + column.title + ": </b>" + column.data;
						        	}
						        	return text;
						        }
						    }
						},
						"deferRender": true
					});
				});
			},
			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 atualizar"); return;
			}
		});
	});
}

function atualizar_linha(json){
	var table = $('#tbGSuite').DataTable();
	var registro = json;
	var tableRow = table.row(".id"+registro.id);
	var rowData = tableRow.data();
	if (rowData == null){
		return;
	}
	rowData[1] = registro.nome;
	rowData[3] = registro.status;
	rowData[4] = registro.cpf_cnpj;
	rowData[5] = registro.vencimento;
	rowData[6] = registro.valor;
	rowData[7] = registro.quantidade;
	rowData[8] = registro.tipo;
	rowData[10] = registro.telefone;
	rowData[11] = registro.email;
	rowData[12] = registro.pesquisa;
	tableRow.data(rowData);
	tableRow.invalidate();
	table.draw(false);
}

function adicionar_linhas(json){
	var table = $('#tbGSuite').DataTable();
	var newRows = [];
	for (var i=0; i < json.length; i++){
		var editar = "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_reenvio("+json[i].id+")' class='btn btn-default text-green' title='Clique para reenviar o boleto.'><i class='fa fa-send'></i></a><a href= 'javascript:void(0);' onclick='modal_editar("+json[i].id+")' class='btn btn-default text-orange' title='Clique para editar o contato.'><i class='fa fa-edit'></i></a></div>";
		var dados = ["",json[i].nome, json[i].id, json[i].status, json[i].cpf_cnpj,json[i].vencimento, json[i].valor, json[i].quantidade,json[i].tipo, editar, json[i].telefone, json[i].email, json[i].pesquisa];
		newRows[i] = dados;
	}
	table.rows.add(newRows);
	table.draw(false);
}

function remover_agendamento(id){
	var table = $('#tbGSuite').DataTable();
	var tableRow = table.row(".id"+id.toString());
	var rowData = tableRow.data();
	if (rowData == null){
		return;
	}
	tableRow.remove();
	table.draw(false);
}

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

function fechar_modal_confirmacao(){
	$('#modal-confirmacao').modal('hide');
}

carregar_dados();