$('.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');
$('#tabelaLeads').html('<table id="tbLeads" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
$('#tbLeads').dataTable({
	"data": [],
	"order": [[ 4, 'desc' ]],
	"columns": [{"title": "Nome"}, {"title": "Email"}, {"title": "Telefone"}, {"title": "Cliente"},{"title": "Data"},{"title": "Opções", "className": "table-buttons"},{"title": "Status"},{"title": "Qualidade"},{"title": "Valor Fechado"},{"title": "Valor Orçado"},{"title": "ID"}],
	"columnDefs": [{"targets": 5, "orderable": false},{"targets": 10, "visible": 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_contato_admin",
			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('#formContatos').serialize();
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_todos_contatos",
			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=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_editar("+json[i].id+")' class='btn btn-default text-orange' title='Clique para editar o contato.'><i class='fa fa-edit'></i></a></div>";
					table_data[i] = ["",json[i].nome, json[i].email, json[i].telefone, json[i].cliente, date, editar,json[i].status, json[i].qualidade, json[i].valorfechado, json[i].valororcado, json[i].id];
					quantidade++;
				}
				$(document).ready(function() {
					const colunas = [{},{"title": "Nome"}, {"title": "Email"}, {"title": "Telefone"}, {"title": "Cliente"},{"title": "Data"},{"title": "Opções", "className": "table-buttons"},{"title": "Status"},{"title": "Qualidade"},{"title": "Valor Fechado"},{"title": "Valor Orçado"}];
					$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
					$('#tabelaLeads').html('<table id="tbLeads" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
					if(json.length >= 2){
						$("#tbLeads").append(
							$('<tfoot style="display: table-header-group;" />').append(`<tr>${colunas.map((i) => "<th></th>").join("")}</tr>`)
						);
						$('#tbLeads tfoot tr th').each(function (index) {
							if(index !== 6){
								$(this).html('<input type="text" style="width: 100%" class="form-control" placeholder="" />');
							}
						});
					}
					$('#tbLeads').dataTable({
						"data": table_data,
						"order": [[ 5, 'desc' ]],
						"columns": colunas,
						"columnDefs": [{"targets": 6, "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 Contato</b></span>';
						            }
						        } ),
						        renderer: function ( api, rowIdx, columns ) {
						        	text = "";
						        	text += columns[5].data + "<br>";
						        	for(i = 0;i < columns.length;i++){
						        		column = columns[i];
						        		if(i == 5) { continue; }
						        		if(i > 0) text += "<br>";
						        		text += "<b>" + column.title + ": </b>" + column.data;
						        	}
						        	return text;
						        }
						    }
						},
						initComplete: function () {
							// Apply the search
							this.api()
								.columns([7,8])
								.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,9,10])
								.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[11]);
							var current = $('td', row).eq(7);
							if(current.text() == "Fechado"){
								current.css('color','green');
							}
							else if(current.text() == "Perdeu"){
								current.css('color','red');
							}
							else if(current.text() == "Novo"){
								current.css('color','blue');
							}
						}
					});
				});
			},
			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(){
	var valor = $('#data').val();
	if(valor == "CUSTOM_DATE")
		$('.datadiv').removeClass("hide");
	else{
		$('.datadiv').addClass("hide");
		carregar_dados();
		salvarFiltro(valor,'','');
	}
}

function atualizar_linhas(json){
	var table = $('#tbLeads').DataTable();
	for (var i=0; i < json.length; i++){
		var registro = json[i];
		var tableRow = table.row(".id"+registro.id);
		var rowData = tableRow.data();
		if (rowData == null){
			continue;
		}
		var cell = $('td', tableRow.node()).eq(7);
		if(registro.status == "Fechado"){
			cell.css('color','green');
		}
		else if(registro.status == "Perdeu"){
			cell.css('color','red');
		}
		else if(registro.status == "Novo"){
			cell.css('color','blue');
		}
		else{
			cell.css('color','#333');
		}
		rowData[1] = registro.nome;
		rowData[2] = registro.email;
		rowData[3] = registro.telefone;
		rowData[4] = registro.cliente;
		rowData[7] = registro.status;
		rowData[8] = registro.qualidade;
		rowData[9] = registro.valorfechado;
		rowData[10] = registro.valororcado;
		tableRow.data(rowData);
		tableRow.invalidate();
	}
	table.draw(false);
}

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