window.myLine = null;
window.autoUpdateFunc = null;
window.runningUpdate = false;
window.stopUpdate = false;
window.chartData = {};
window.elementVisibility = {};
window.drawData = null;
window.eixoX = $('#eixox').val();
window.eixoY = $('#eixoy').val();
window.eixoR = $('#eixor').val();

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

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

window.ffs = false;


function fullscreen(){
	var elem = document.getElementById("chart-container");
	elem.style.height = "100%";
	window.ffs = true;
	if (elem.requestFullscreen) {
		elem.requestFullscreen();
	} else if (elem.msRequestFullscreen) {
		elem.msRequestFullscreen();
	} else if (elem.mozRequestFullScreen) {
		elem.mozRequestFullScreen();
	} else if (elem.webkitRequestFullscreen) {
		elem.webkitRequestFullscreen();
	}
}



function carregar_dados(){
	$(document).ready(function() {
		var dados = jQuery('#formGrafico').serialize();
		// console.log("Dados: "+dados);
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_resultados_gerais",
			data: dados,
			success: function(data){
				// console.log("Data: "+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;}
				if(window.runningUpdate){
					window.drawData = JSON.parse(data);
				}
				else{
					desenharGrafico(JSON.parse(data));
					if($('#atualizar-auto').val() == "s"){
						if(window.autoUpdateFunc == null){
							window.autoUpdateFunc = setInterval(function(){ atualizarGrafico(); }, 15000);
						}
					}
				}
			},
			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 getRandomColor(brightness){
	function randomChannel(brightness){
		var r = 255-brightness;
		var n = 0|((Math.random() * r) + brightness);
		var s = n.toString(16);
		return (s.length==1) ? '0'+s : s;
	}
	return '#' + randomChannel(brightness) + randomChannel(brightness) + randomChannel(brightness);
}

function shadeBlendConvert(p, from, to) {
    if(typeof(p)!="number"||p<-1||p>1||typeof(from)!="string"||(from[0]!='r'&&from[0]!='#')||(typeof(to)!="string"&&typeof(to)!="undefined"))return null; //ErrorCheck
    if(!this.sbcRip)this.sbcRip=(d)=>{
        let l=d.length,RGB=new Object();
        if(l>9){
        	d=d.split(",");
            if(d.length<3||d.length>4)return null;//ErrorCheck
            RGB[0]=i(d[0].slice(4)),RGB[1]=i(d[1]),RGB[2]=i(d[2]),RGB[3]=d[3]?parseFloat(d[3]):-1;
        }else{
            if(l==8||l==6||l<4)return null; //ErrorCheck
            if(l<6)d="#"+d[1]+d[1]+d[2]+d[2]+d[3]+d[3]+(l>4?d[4]+""+d[4]:""); //3 digit
            d=i(d.slice(1),16),RGB[0]=d>>16&255,RGB[1]=d>>8&255,RGB[2]=d&255,RGB[3]=l==9||l==5?r(((d>>24&255)/255)*10000)/10000:-1;
        }
        return RGB;}
    var i=parseInt,r=Math.round,h=from.length>9,h=typeof(to)=="string"?to.length>9?true:to=="c"?!h:false:h,b=p<0,p=b?p*-1:p,to=to&&to!="c"?to:b?"#000000":"#FFFFFF",f=this.sbcRip(from),t=this.sbcRip(to);
    if(!f||!t)return null; //ErrorCheck
    if(h)return "rgb("+r((t[0]-f[0])*p+f[0])+","+r((t[1]-f[1])*p+f[1])+","+r((t[2]-f[2])*p+f[2])+(f[3]<0&&t[3]<0?")":","+(f[3]>-1&&t[3]>-1?r(((t[3]-f[3])*p+f[3])*10000)/10000:t[3]<0?f[3]:t[3])+")");
    else return "#"+(0x100000000+(f[3]>-1&&t[3]>-1?r(((t[3]-f[3])*p+f[3])*255):t[3]>-1?r(t[3]*255):f[3]>-1?r(f[3]*255):255)*0x1000000+r((t[0]-f[0])*p+f[0])*0x10000+r((t[1]-f[1])*p+f[1])*0x100+r((t[2]-f[2])*p+f[2])).toString(16).slice(f[3]>-1||t[3]>-1?1:3);
}

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

document.addEventListener("fullscreenchange", function( event ) {
    if  (!document.fullscreen) {
    	if(window.ffs == false){
    		var element = document.getElementById("chart-container");
        	element.style.height = "60vh";
    	}
    	else{
    		window.ffs = false;
    	}
    }
});

document.addEventListener("webkitfullscreenchange", function( event ) {
    if  (!document.fullscreen) {
    	if(window.ffs == false){
    		var element = document.getElementById("chart-container");
        	element.style.height = "60vh";
    	}
    	else{
    		window.ffs = false;
    	}
    }
});

document.addEventListener("mozfullscreenchange", function( event ) {
    if  (!document.fullscreen) {
    	if(window.ffs == false){
    		var element = document.getElementById("chart-container");
        	element.style.height = "60vh";
    	}
    	else{
    		window.ffs = false;
    	}
    }
});

document.addEventListener("MSFullscreenChange", function( event ) {
    if  (!document.fullscreen) {
    	if(window.ffs == false){
    		var element = document.getElementById("chart-container");
        	element.style.height = "60vh";
    	}
    	else{
    		window.ffs = false;
    	}
    }
});

function atualizarGraficosComDados(updateData){
	if(updateData != null & window.chartData != null){
		var selectX = $('#eixox').val();
		var selectY = $('#eixoy').val();
		var selectR = $('#eixor').val();
		var drawX = 0;
		var drawY = 0;
		var drawR = 0;

		var chartDt = jQuery.extend({}, window.chartData);
		var chart = window.myLine;
		var datasets = chart.data.datasets;
		window.biggestRadius = 1;
		var minX = 999999999;
		var minY = 999999999;
		var maxX = 0;
		var maxY = 0;

		var legendaX = "";
		var legendaY = "";

		if(selectX == "forms") legendaX = "Formulários";
		else if(selectX == "whatsapp") legendaX = "WhatsApp";
		else if(selectX == "ligacoes") legendaX = "Ligações";

		if(selectY == "forms") legendaY = "Formulários";
		else if(selectY == "whatsapp") legendaY = "WhatsApp";
		else if(selectY == "ligacoes") legendaY = "Ligações";

		for (var i=0; i < updateData.length; i++){
			var dados = updateData[i];
			var ligacoes = parseInt(dados.ligacoes);
			var whatsapp = parseInt(dados.whatsapp);
			var forms = parseInt(dados.forms);

			var elemVisible = true;
			if(window.elementVisibility.hasOwnProperty(dados.id)){
				elemVisible = window.elementVisibility[dados.id];
			}
			else{
				window.elementVisibility[dados.id] = true;
			}

			if(selectX == "forms") drawX = forms;
			else if(selectX == "whatsapp") drawX = whatsapp;
			else if(selectX == "ligacoes") drawX = ligacoes;

			if(selectY == "forms") drawY = forms;
			else if(selectY == "whatsapp") drawY = whatsapp;
			else if(selectY == "ligacoes") drawY = ligacoes;

			if(selectR == "forms") drawR = forms;
			else if(selectR == "whatsapp") drawR = whatsapp;
			else if(selectR == "ligacoes") drawR = ligacoes;

			var idCliente = parseInt(dados.id);

			if(elemVisible){
				if(drawX < minX) minX = drawX;
				if(drawY < minY) minY = drawY;
				if(drawX > maxX) maxX = drawX;
				if(drawY > maxY) maxY = drawY;
				if(drawR > window.biggestRadius) window.biggestRadius = drawR;
			}

			if(chartDt.hasOwnProperty(dados.id)){
				var indexDt = chartDt[dados.id];
				var dataset = datasets[indexDt];

				dataset.data[0].x = drawX;
				dataset.data[0].y = drawY;
				dataset.data[0].value = elemVisible ? drawR : -1;
			}
			else{
				var rdcolor = getRandomColor(30);
				var border = shadeBlendConvert(-0.20, rdcolor);

				var dataDt = [{
					x: drawX,
					y: drawY,
					value: drawR
				}];

				datasets.push({
					label: dados.nome,
					data: dataDt,
					backgroundColor: rdcolor,
					borderColor: border,
					idCliente: dados.id
				});

				window.chartData[idCliente] = datasets.length - 1;
			}

			delete chartDt[dados.id];
		}

		for (var property in chartDt) {
			if (chartDt.hasOwnProperty(property)) {
				var indexDt = chartDt[property];
				var dataset = datasets[indexDt];
				dataset.data[0].value = -1;
			}
		}

		var difX = maxX - minX;
		var difY = maxY - minY;
		var maxGraphX = Math.ceil(maxX + Math.max(1, 15 * difX / 100));
		var minGraphX = Math.ceil(minX - Math.max(1, 15 * difX / 100));
		var maxGraphY = Math.ceil(maxY + Math.max(1, 15 * difY / 100));
		var minGraphY = Math.ceil(minY - Math.max(1, 15 * difY / 100));
		var stepX = Math.ceil(Math.max(1, 10 * difX / 100));
		var stepY = Math.ceil(Math.max(1, 10 * difY / 100));

		chart.options.scales.yAxes[0].ticks.max = maxGraphY;
		chart.options.scales.yAxes[0].ticks.min = minGraphY;
		chart.options.scales.yAxes[0].ticks.stepSize = stepY;
		chart.options.scales.yAxes[0].scaleLabel.labelString = legendaY;
		chart.options.scales.xAxes[0].ticks.max = maxGraphX;
		chart.options.scales.xAxes[0].ticks.min = minGraphX;
		chart.options.scales.xAxes[0].ticks.stepSize = stepX;
		chart.options.scales.xAxes[0].scaleLabel.labelString = legendaX;

		chart.update();
	}
}

document.getElementById("canvas").onclick = function(evt) {
	if(window.myLine != null){
		var activePoints = window.myLine.getElementAtEvent(evt);
		if (activePoints[0]) {
			var chart = window.myLine;
			var datasets = chart.data.datasets;
			var idx = activePoints[0]['_datasetIndex'];
			var dataset = datasets[idx];
			dataset.data[0].value = -1;
			window.elementVisibility[dataset.idCliente] = false;
			subAtualizar();
		}
	}
};

function atualizarGrafico(){
	if(window.runningUpdate){
		return;
	}

	if(window.stopUpdate){
		if(window.autoUpdateFunc != null){
			var wFunc = window.autoUpdateFunc;
			window.autoUpdateFunc = null;
			clearInterval(wFunc);
		}
		return;
	}

	if(window.drawData != null){
		window.runningUpdate = true;
		atualizarGraficosComDados(window.drawData);
		window.runningUpdate = false;
		return;
	}

	subAtualizar();
}

function subAtualizar(){
	if(window.runningUpdate){
		return;
	}

	window.runningUpdate = true;

	var updateData = null;

	$(document).ready(function() {
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_resultados_gerais",
			data: jQuery('#formGrafico').serialize(),
			success: function(data){
				if(data == '-1') {window.location.href = "./"; return;}
				if(data.substring(0,2) == "-2") { window.runningUpdate = false; return;}
				updateData = JSON.parse(data);
				atualizarGraficosComDados(updateData);
				window.runningUpdate = false;
			},
			error: function(){
				window.runningUpdate = false;
			}
		});
	});
}


function desenharGrafico(dados){
	window.runningUpdate = true;
	var presets = window.chartColors;
	var utils = Samples.utils;
	utils.srand(110);

	if(window.myLine != null){ window.myLine.destroy(); }
	moment.locale('pt-BR');
	var timeFormat = 'DD/MM/YYYY';

	var selectX = $('#eixox').val();
	var selectY = $('#eixoy').val();
	var selectR = $('#eixor').val();
	var drawX = 0;
	var drawY = 0;
	var drawR = 0;

	window.biggestRadius = 1;
	var datasets = [];
	var minX = 999999999;
	var minY = 999999999;
	var maxX = 0;
	var maxY = 0;
	window.chartData = {};

	var legendaX = "";
	var legendaY = "";

	if(selectX == "forms") legendaX = "Formulários";
	else if(selectX == "whatsapp") legendaX = "WhatsApp";
	else if(selectX == "ligacoes") legendaX = "Ligações";

	if(selectY == "forms") legendaY = "Formulários";
	else if(selectY == "whatsapp") legendaY = "WhatsApp";
	else if(selectY == "ligacoes") legendaY = "Ligações";

	for (var i=0; i < dados.length; i++){
		var forms = parseInt(dados[i].forms);
		var ligacoes = parseInt(dados[i].ligacoes);
		var whatsapp = parseInt(dados[i].whatsapp);
		var rdcolor = getRandomColor(30);
		var border = shadeBlendConvert(-0.20, rdcolor);
		var idCliente = parseInt(dados[i].id);

		var elemVisible = true;
		if(window.elementVisibility.hasOwnProperty(dados[i].id)){
			elemVisible = window.elementVisibility[dados[i].id];
		}
		else{
			window.elementVisibility[dados.id] = true;
		}

		if(selectX == "forms") drawX = forms;
		else if(selectX == "whatsapp") drawX = whatsapp;
		else if(selectX == "ligacoes") drawX = ligacoes;

		if(selectY == "forms") drawY = forms;
		else if(selectY == "whatsapp") drawY = whatsapp;
		else if(selectY == "ligacoes") drawY = ligacoes;

		if(selectR == "forms") drawR = forms;
		else if(selectR == "whatsapp") drawR = whatsapp;
		else if(selectR == "ligacoes") drawR = ligacoes;

		if(elemVisible){
			if(drawX < minX) minX = drawX;
			if(drawY < minY) minY = drawY;
			if(drawX > maxX) maxX = drawX;
			if(drawY > maxY) maxY = drawY;
			if(drawR > window.biggestRadius) window.biggestRadius = drawR;
		}
		else{
			drawR = -1;
		}

		rdcolor = hexToRgb(rdcolor);
		rdcolor = "rgba("+rdcolor.r+", "+rdcolor.g+", "+rdcolor.b+", 0.5)";

		var dataDt = [{
			x: drawX,
			y: drawY,
			value: drawR
		}];

		datasets.push({
			label: dados[i].nome,
			data: dataDt,
			backgroundColor: rdcolor,
			borderColor: border,
			idCliente: dados[i].id
		});

		window.chartData[idCliente] = i;
	}

	var difX = maxX - minX;
	var difY = maxY - minY;
	var maxGraphX = Math.ceil(maxX + Math.max(1, 15 * difX / 100));
	var minGraphX = Math.ceil(minX - Math.max(1, 15 * difX / 100));
	var maxGraphY = Math.ceil(maxY + Math.max(1, 15 * difY / 100));
	var minGraphY = Math.ceil(minY - Math.max(1, 15 * difY / 100));
	var stepX = Math.ceil(Math.max(1, 10 * difX / 100));
	var stepY = Math.ceil(Math.max(1, 10 * difY / 100));

	var config = {
		type: 'bubble',
		data: {
			datasets: datasets
		},
		options: {
			elements: {
				point: {
					radius: function(context) {
						var index = context.dataIndex;
						var data = context.dataset.data[index];
						var width = context.chart.width;
						var height = context.chart.height;
						var baseSize = Math.min(width, height);
						var base = Math.max(1,data.value); 
						return data.value == -1 ? 0 : Math.max(baseSize / 200, base * (15 * baseSize / 100) / window.biggestRadius);
					}
				}
			},
			layout: {
	            padding: 10
	        },
			responsive: true,
			maintainAspectRatio: false,
			title: {
				text: "Gráfico Geral"
			},
			tooltips: {
				titleFontFamily: "'Source Sans Pro',sans-serif",
				bodyFontFamily: "'Source Sans Pro',sans-serif",
				xPadding: 8,
				yPadding: 8,
				bodySpacing: 4,
				displayColors: false,
				callbacks: {
					label: function(tooltipItem, data) {
						var selectX = $('#eixox').val();
						var selectY = $('#eixoy').val();
						var selectR = $('#eixor').val();

						var datasetIndex = tooltipItem.datasetIndex;
						var dataset = data.datasets[datasetIndex];
						var content = dataset.data[tooltipItem.index];

						if(selectX == "forms") drawX = "Formulários";
						else if(selectX == "whatsapp") drawX = "WhatsApp";
						else if(selectX == "ligacoes") drawX = "Ligações";

						if(selectY == "forms") drawY = "Formulários";
						else if(selectY == "whatsapp") drawY = "WhatsApp";
						else if(selectY == "ligacoes") drawY = "Ligações";

						if(selectR == "forms") drawR = "Formulários";
						else if(selectR == "whatsapp") drawR = "WhatsApp";
						else if(selectR == "ligacoes") drawR = "Ligações";

						return [drawX + ": " + content.x,drawY + ": " + content.y, drawR + ": " + content.value];
	                },
	                labelTextColor:function(tooltipItem, chart){
	                    return '#ffffff';
	                },
	                title: function(tooltipItem, data) {
						var datasetIndex = tooltipItem[0].datasetIndex;
						var dataset = data.datasets[datasetIndex];
						return dataset.label;
	                }
				}
			},
			legend: {
				display: false,
			},
			scales: {
				yAxes: [{ 
					scaleLabel: {
						display: true,
						labelString: legendaY
					},
					ticks: {
						beginAtZero: false,
                        callback: function (value) { if (Number.isInteger(value)) { return value; } },
                        max: maxGraphY,
                        min: minGraphY,
                        stepSize: stepY
                    }
				}],
				xAxes: [{ 
					scaleLabel: {
						display: true,
						labelString: legendaX
					},
					ticks: {
						beginAtZero: false,
                        callback: function (value) { if (Number.isInteger(value)) { return value; } },
                        max: maxGraphX,
                        min: minGraphX,
                        stepSize: stepX
                    }
				}]
			}
		}
	};
	$(document).ready(function() {
		var ctx = document.getElementById("canvas").getContext("2d");
		window.myLine = new Chart(ctx, config);
		window.drawData = null;
	});
	window.runningUpdate = false;
}

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

$('#procurar').keyup(function(){ 
	if ($('#procurar').val() === "") {
		atualizar();
	}
});
$('#data, #switch, #periodo, #procurar').change(function(){ atualizar(); });
$('#datapersonalizada').click(function(){
	salvarFiltro($('#data').val(),$('#datainicial').val(),$('#datafinal').val());
	carregar_dados();
});

desenharGrafico([]);

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

$('#atualizar-auto').change(function(){ 
	if($('#atualizar-auto').is(':checked')){
		window.stopUpdate = false;
		if(window.autoUpdateFunc == null){
			window.autoUpdateFunc = setInterval(function(){ atualizarGrafico(); }, 5000);
		}
	}
	else{
		window.stopUpdate = true;	
	}
});

$('.eixografico').change(function(event){
	var valueX = $('#eixox').val();
	var valueY = $('#eixoy').val();
	var valueR = $('#eixor').val();
	if(event.target.id == "eixox"){
		if(valueX == valueY){
			$('#eixoy').val(window.eixoX);
			window.eixoY = window.eixoX;
		}
		else if(valueX == valueR){
			$('#eixor').val(window.eixoX);
			window.eixoR = window.eixoX;
		}
		window.eixoX = valueX;
	}
	else if (event.target.id == "eixoy"){
		if(valueY == valueX){
			$('#eixox').val(window.eixoY);
			window.eixoX = window.eixoY;
		}
		else if(valueY == valueR){
			$('#eixor').val(window.eixoY);
			window.eixoR = window.eixoY;
		}
		window.eixoY = valueY;
	}
	else{
		if(valueR == valueX){
			$('#eixox').val(window.eixoR);
			window.eixoX = window.eixoR;
		}
		else if(valueR == valueY){
			$('#eixoy').val(window.eixoR);
			window.eixoY = window.eixoR;
		}
		window.eixoR = valueR;
	}

	subAtualizar();
});