$(document).ready(function () {
	$("a").removeClass("active");
	$(".Report1,.Report_class").addClass("active");
	setTimeout(function () {
		$(".Report_class").click();
	}, 500);
	var table = $('#tbl2').DataTable({
		"scrollX": true,
		"paging": false,
		"searching": false,
	});

	var empId = $("#empId").val();

	if (empId) {
		getdata();
	}
});

String.prototype.toHHMM = function () {
	var sec_num = parseInt(this, 10); // don't forget the second param
	var hours   = Math.floor(sec_num / 3600);
	var minutes = Math.floor((sec_num - (hours * 3600)) / 60);

	if (hours   < 10) {hours   = "0"+hours;}
	if (minutes < 10) {minutes = "0"+minutes;}
	return hours + ':' + minutes
}

$('#empId').keyup(function (e) {
	if (e.keyCode == 13) {
		getdata();
	}
});

function getdata() {
	var empid = $("#empId").val().trim();
	if (empid == "") {
		Swal.fire(
			'Error!',
			'Enter Employee ID.',
			'error'
		);
		return false;
	}
	HoldOn.open({
		theme: "sk-bounce",
		message: "Please wait...."
	});
	$.ajax({
		url: base_urlJs + "Report_Controller/loadReport1",
		type: "get",
		data: {empid: empid},
		success: function (data) {
			HoldOn.close();
			var reportData = JSON.parse(data);
			if (reportData === 0) {
				Swal.fire(
					'No data found',
					'Please Check the Employee ID',
					'warning'
				);
				return false;
			}
			if (typeof (reportData) === 'object') {
				loadTables(reportData);
			} else {
				Swal.fire(
					'Error!',
					'Internal Server Error',
					'error'
				);
				return false;
			}


		},
		error: function (jqXhr) {
			HoldOn.close();
			toastsCall('bg-danger', 'Error', 'Internal Server Error!');
		}
	});

}


function loadTables(array) {
	var workingDays = 20;

	if (array['empData'] !== "undefined") {
		var empData = array['empData'];
		$("#empName").html(empData[0]['empName']);
		$("#empDes").html(empData[0]['designation']);
		$("#emp_num").html(empData[0]['empId']);
		$("#dep").html(empData[0]['department']);
		$("#super").html(empData[0]['Supervisor']);
		$("#duration").html(empData[0]['duration']);

	}

	if (array['empTask'] !== "undefined") {

		var empTask = array['empTask'];
		var table2_body = "";
		var table3_body = "";
		var table4_body = "";
		var table5_body = "";
		var monthlyTot = 0;
		var monthlyTotSec = 0;
		var charArr = [];
		var chart2TastList = []
		var chart2EmpHrList = [];
		var chart2SpuHrList = [];
		var satisfactionTot = 0;
		var discrepTot = 0;
		for (i = 0; i < empTask.length; i++) {
			satisfactionTot += Number(empTask[i]['satisfaction']);
			discrepTot += Number(empTask[i]['discrepancy']);

			if (empTask[i]['satisfaction'] === 0) {
				var start = "<i class='fas fa-frown-open' style='color: red;'></i>"
			} else {
				var start = ""
				for (st = 0; st < empTask[i]['satisfaction']; st++) {
					start += "<i class='fas fa-star' style='color: #56ff00;'></i>"
				}
			}

			if(empTask[i]['sup_value']==0 || empTask[i]['sup_value']==""){
				var valu_added="No Value";
			}else {
				var valu_added="";
				for (st = 0; st < empTask[i]['sup_value']; st++) {
					valu_added += "<i class='fas fa-dollar-sign' style='color: rgba(255,0,59,0.38);'></i>"
				}
			}
			var h_var="";
			if(empTask[i]['frequent']=="Monthly"){
				h_var= ((empTask[i]['times'])*(empTask[i]['hours_sec'])).toString().toHHMM()
				h_var+=" hours / month"
				monthlyTotSec+=((empTask[i]['times'])*(empTask[i]['hours_sec']))
				var hr = ((empTask[i]['times'])*(empTask[i]['hours_sec']));
			}else if(empTask[i]['frequent']=="Weekly"){
				h_var= ((empTask[i]['times'])*(empTask[i]['hours_sec'])).toString().toHHMM()
				h_var+=" hours / week = "
				h_var+=((empTask[i]['times'])*(empTask[i]['hours_sec'])*4).toString().toHHMM()
				h_var+=" hours / month"
				monthlyTotSec+=((empTask[i]['times'])*(empTask[i]['hours_sec'])*4)
				var hr = (empTask[i]['hours_sec'] * empTask[i]['times']) * 4;
			}else if(empTask[i]['frequent']=="Daily"){
				h_var= ((empTask[i]['times'])*(empTask[i]['hours_sec'])).toString().toHHMM()
				h_var+=" hours / day = "
				h_var+=((empTask[i]['times'])*(empTask[i]['hours_sec'])*workingDays).toString().toHHMM()
				h_var+=" hours / month"
				monthlyTotSec+=((empTask[i]['times'])*(empTask[i]['hours_sec'])*workingDays)
				var hr = empTask[i]['hours_sec'] * empTask[i]['times'] * workingDays;
			}

			monthlyTot += hr;
			charArr.push({
				name: 'Task ' + (i + 1),
				y: hr,
			});

			table2_body += "<tr>" +
				"<td>" + (i + 1) + "</td>" +
				"<td>" + empTask[i]['activity']  + "</td>" +
				"<td>" + empTask[i]['times'] +" / "+  empTask[i]['frequent'] + "</td>" +
				"<td>"+h_var+"</td>" +
				"<td style='text-align: center'><span id='value_"+(i + 1)+"'></span></td>" +
				"<td>" + valu_added + "</td>" +
				"<td>" + start + "(" + empTask[i]['satisfaction'] + ")</td>" +
				"</tr>";

			if(empTask[i]['targetSatisfaction']==0 ){
				var targetSatisfaction="<i class='far fa-frown-open' style='color: #ff0707;'></i>";
			}else if(empTask[i]['targetSatisfaction']==""){
				var targetSatisfaction="N/A";
			}else {
				var targetSatisfaction="";
				for (st = 0; st < empTask[i]['targetSatisfaction']; st++) {
					targetSatisfaction += "<i class='far fa-smile-beam' style='color: #ffc107;'></i>"
				}
			}

			table3_body+="<tr> " +
				"<td>" + (i + 1) + "</td>" +
				"<td>" + empTask[i]['activity']  + "</td>" +
				"<td>"+empTask[i]['targetText']+"</td>" +
				"<td>"+targetSatisfaction+"</td>" +
				"<td>"+empTask[i]['targetMonitor']+ " <br>"+empTask[i]['monitorFrequent'] +"</td>" +
				"<td>"+empTask[i]['suggestion']+"</td>" +
				"</tr>"



			table4_body += "<tr>" +
				"<td>" + (i + 1) + "</td>" +
				"<td>" + empTask[i]['activity'] + "</td>" +
				"<td>" + empTask[i]['sup_hr'] + "</td>" +
				"<td>" + empTask[i]['hours'] + "</td>" +
				"<td>" + empTask[i]['discrepancy'] + "</td>" +
				"</tr>";

			table5_body+="<tr>" +
				"<td>" + (i + 1) + "</td>" +
				"<td>" + empTask[i]['activity'] + "</td>" +
				"<td>" + empTask[i]['sup_exp_tar'] + "</td>" +
				"<td>" + valu_added + "</td>" +
				"<td>"+empTask[i]['sup_monitor']+ " <br>"+empTask[i]['sup_monitor_frqu'] +"</td>"+
				"<td>" + empTask[i]['sup_suggestion'] + "</td>"
				"</tr>";


			chart2TastList.push("Task " + (i + 1));
			chart2SpuHrList.push(parseFloat(empTask[i]['sup_hr'].replace(":",".")));
			chart2EmpHrList.push(parseFloat(empTask[i]['hours'].replace(":",".")));
		}
		$('#tbl2').DataTable().destroy();
		$("#table2_body").html(table2_body);
		for (c = 0; c < charArr.length; c++) {
			var newY = ((charArr[c]['y'] / monthlyTotSec) * 100).toFixed(2);
			charArr[c]['y'] = parseFloat(newY);
			$("#value_"+(c+1)).html(newY+"%");
		}


		var table = $('#tbl2').DataTable({
			"scrollX": true,
			"paging": false,
			"searching": false,
		});


		$("#table4_body").html(table4_body);
		$("#table5_body").html(table5_body);
		$("#table3_body").html(table3_body);
		drawCart1(charArr);
		drawchart2(chart2TastList, chart2EmpHrList, chart2SpuHrList);
		var stlv = (satisfactionTot / empTask.length).toFixed(2);
		$("#satis_level").html(stlv + "/5");
		$("#avg_sat").html(((stlv / 5) * 100).toFixed(0) + "% ");
		$("#satisprogress-bar").css("width", ((stlv / 5) * 100).toFixed(0) + "%");
		$("#w_hours").html(monthlyTotSec.toString().toHHMM());
		$("#w_hours_p").html(((monthlyTotSec.toString().toHHMM().replace(":",".") / 160) * 100).toFixed(2) + "% ");
		$("#hoursprogress-bar").css("width", ((monthlyTotSec.toString().toHHMM().replace(":",".") / 160) * 100).toFixed(2) + "%");
		$("#discrep_lv").html(discrepTot);
		$(".highcharts-credits").hide();
	}

	console.log(monthlyTotSec.toString())
	console.log(monthlyTotSec.toString().toHHMM())
}

function drawCart1(dataList) {
	Highcharts.chart('char1', {
		chart: {
			plotBackgroundColor: null,
			plotBorderWidth: null,
			plotShadow: false,
			type: 'pie'
		},
		title: {
			text: 'Month Analysis'
		},
		tooltip: {
			pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
		},
		accessibility: {
			point: {
				valueSuffix: '%'
			}
		},
		plotOptions: {
			pie: {
				allowPointSelect: true,
				cursor: 'pointer',
				dataLabels: {
					enabled: true,
					format: '<b>{point.name}</b>: {point.percentage:.1f} %'
				}
			}
		},
		series: [{
			name: 'Out of total hours',
			colorByPoint: true,
			data: dataList
		}]
	});
}

function drawchart2(categories, Employee, Supervisor) {
//                                console.log(Employee)
//                                console.log(Supervisor)
	Highcharts.chart('char2', {
		chart: {
			type: 'column'
		},
		title: {
			text: 'Expectaion Vs Actual Hours'
		},

		xAxis: {
			categories: categories,
			crosshair: true
		},
		yAxis: {
			min: 0,
			title: {
				text: 'Hours'
			}
		},
		tooltip: {
			headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
			pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
				'<td style="padding:0"><b>{point.y:.1f} </b></td></tr>',
			footerFormat: '</table>',
			shared: true,
			useHTML: true
		},
		plotOptions: {
			column: {
				pointPadding: 0.2,
				borderWidth: 0
			}
		},
		series: [{
			name: 'Supervisor',
			data: Supervisor

		}, {
			name: 'Employee',
			data: Employee

		}]
	});
}

