$('.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');
$('#tabelaEmail').html('<table id="tbEmail" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
$('#tbEmail').dataTable({
	"data": [],
	"order": [[ 3, 'desc' ]],
	"columns": [{"title": "Remetente"}, {"title": "ID"}, {"title": "Email do Remetente"}, {"title": "Data de Registro"}, {"title": "Status"}, {"title": "Tipo"}, {"title": "Opções", "className": "table-buttons"}, {"title": "Assunto"}],
	"columnDefs": [{"targets": 6, "orderable": false}],
	"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
	responsive: true
});

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_email_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 marcarPendente(id){
	var table = $('#tbEmail').DataTable();
	var tableRow = table.row(".id"+id);
	var rowData = tableRow.data();
	if (rowData == null){
		return;
	}
	rowData[5] = "Marcado para Reenvio";
	var editar = "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_editar("+id+");' class='btn btn-default text-orange' title='Clique para visualizar dados do e-mail.'><i class='fa fa-edit'></i></a></div>";
	rowData[7] = editar;
	var cell = $('td', tableRow.node()).eq(5);
	cell.css('color','#333');
	tableRow.data(rowData);
	tableRow.invalidate();
	table.draw(false);
}

function atualizar_linha(json){
	var table = $('#tbEmail').DataTable();
	var registro = json;
	var tableRow = table.row(".id"+registro.id);
	var rowData = tableRow.data();
	if (rowData == null){
		return;
	}
	rowData[1] = registro.nomeremetente;
	rowData[3] = registro.remetente;
	rowData[8] = registro.assunto;
	tableRow.data(rowData);
	tableRow.invalidate();
	table.draw(false);
}

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

function reenviarEmails_2(){
	$(document).ready(function(){
		var dados = jQuery('#formEmail').serialize();
		jQuery.ajax({
			type: "POST",
			url: "action/reenviar_emails_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;}
				toastr.clear(); toastr.success("E-mails não enviados foram marcados para reenvio");
			},
			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 marcar e-mails para reenvio."); return;
			}
		});
	});
}

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

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

function reenviarEmail_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/reenviar_email_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;}
				toastr.clear(); toastr.success("E-mail marcado para reenvio com sucesso");
				marcarPendente(id);
			},
			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 marcar e-mail para reenvio."); return;
			}
		});
	});
}

function carregar_dados(){
	$(document).ready(function() {
		var dados = jQuery('#formEmail').serialize();
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_email_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 = [];
				var quantidade = 0;
				for (var i=1; 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_editar("+json[i].id+");' class='btn btn-default text-orange' title='Clique para visualizar dados do e-mail.'><i class='fa fa-edit'></i></a>";
					if(json[i].status == "Não Enviado"){
						editar += "<button type='button' class='btn btn-default dropdown-toggle' title='Clique para visualizar informações avançadas do usuário.' data-toggle='dropdown' aria-expanded='false'><span class='caret'></span><span class='sr-only'>Exibir Opções</span></button><ul class='dropdown-menu' role='menu'><li><a href='javascript:void(0);' onclick='verErro("+json[i].id+");'>Visualizar Erro</a></li><li><a href='javascript:void(0);' onclick='reenviarEmail("+json[i].id+");'>Reenviar E-mail</a></li></ul>";
					}
					if(json[i].status == "Arquivado"){
						editar += "<button type='button' class='btn btn-default dropdown-toggle' title='Clique para visualizar informações avançadas do usuário.' data-toggle='dropdown' aria-expanded='false'><span class='caret'></span><span class='sr-only'>Exibir Opções</span></button><ul class='dropdown-menu' role='menu'><li><a href='javascript:void(0);' onclick='verErro("+json[i].id+");'>Visualizar Erro</a></li></ul>";
					}
					editar += '</div>';
					table_data[i-1] = ["",json[i].nomeremetente, json[i].id, json[i].remetente, date,json[i].status, json[i].tipo, editar, json[i].assunto];
					quantidade++;
				}

				$('#enviospendentes').html(json[0].pendentes);
				$('#naoenviados').html(json[0].falhos);
				$('#enviados').html(json[0].enviados);
				$('#rotina').html(json[0].rotina);

				$(document).ready(function() {
					const colunas = [{},{"title": "Remetente"}, {"title": "ID"}, {"title": "Email do Remetente"}, {"title": "Data de Registro"}, {"title": "Status"}, {"title": "Tipo"}, {"title": "Opções", "className": "table-buttons"}, {"title": "Assunto"}];
					$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
					$('#tabelaEmail').html('<table id="tbEmail" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
					if(json.length >= 2){
						$("#tbEmail").append(
							$('<tfoot style="display: table-header-group;" />').append(`<tr>${colunas.map((i) => "<th></th>").join("")}</tr>`)
						);
						$('#tbEmail tfoot tr th').each(function (index) {
							if(index !== 7){
								$(this).html('<input type="text" style="width: 100%" class="form-control" placeholder="" />');
							}
						});
					}
					$('#tbEmail').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 do E-mail</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([3,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,1,2,3,4,5,6,7,8,9])
								.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[2]);
							var current = $('td', row).eq(5);
							if(current.text() == "Enviado"){
								current.css('color','green');
							}
							else if(current.text() == "Não Enviado" || current.text() == "Arquivado"){
								current.css('color','red');
							}
							else if(current.text() == "Pendente"){
								current.css('color','blue');
							}
						}
					});
				});
			},
			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 atualizar(){
	var valor = $('#data').val();
	if(valor == "CUSTOM_DATE")
		$('.datadiv').removeClass("hide");
	else{
		$('.datadiv').addClass("hide");
		carregar_dados();
		salvarFiltro(valor,'','');
	}
}

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

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, #exibicao').change(function(){ atualizar(); });
$('#datapersonalizada').click(function(){
	salvarFiltro($('#data').val(),$('#datainicial').val(),$('#datafinal').val());
	carregar_dados();
});