<%-- 
    Document   : vistaDobleDisponibilidad
    Created on : 17-nov-2018, 8:48:37
    Author     : sistem20user
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="pe.siso.horario.Beans.PeriodoAcademico"%>
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>JSP Page</title>
		<link rel="stylesheet" href="../assets/css/jquery-ui.css" />
		<!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
		<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
		<link href="css/snackbar.css" rel="stylesheet" type="text/css"/>
		<link href="css/alert.css" rel="stylesheet" type="text/css"/>

    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

		<!--jquery-->
		<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

		<!--axios-->
		<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
		<%
			HttpSession session_actual = request.getSession(true);
			PeriodoAcademico periodo=(PeriodoAcademico)session_actual.getAttribute("periodo");
		%>
		<style type="text/css">
				@media print {
			  #divBusqueda {display:none}
			  #lblTitulo{text-align: center;font-size: 40px;font-weight: bold}
			}
		</style>
		
				<script type="text/javascript" language="javascript">

			function alertDGC(mensaje)
					{
						var dgcTiempo=500
						var ventanaCS='<div class="dgcAlert"><div class="dgcVentana"><div class="dgcCerrar"></div><div class="dgcMensaje">'+mensaje+'<br><div class="dgcAceptar">Aceptar</div></div></div></div>';
						$('body').append(ventanaCS);
						var alVentana=$('.dgcVentana').height();
						var alNav=$(window).height();
						var supNav=$(window).scrollTop();
						$('.dgcAlert').css('height',$(document).height());
						$('.dgcVentana').css('top',((alNav-alVentana)/2+supNav-100)+'px');
						$('.dgcAlert').css('display','block');
						$('.dgcAlert').animate({opacity:1},dgcTiempo);
						$('.dgcCerrar,.dgcAceptar').click(function(e) {
							$('.dgcAlert').animate({opacity:0},dgcTiempo);
							setTimeout("$('.dgcAlert').remove()",dgcTiempo);
						});
					}
				
		</script>
		
		
	</head>

	<style>
		td{
			border : 3px solid;
			text-align : center;
		}
	</style>
	

	<body>
		<script>
				window.alert = function (message) {
						alertDGC(message);
					};
		</script>
		<div class="container">
			<div class="row" id="divBusqueda">
				<div class="col s8 offset-s2">
					<div class="card">
						<div class="card-content">
							<span class="card-title">Buscar disponibilidad</span>
							<div class="row">
								<div class="input-field col s6">
									<select id="cbArea" onchange="listarPlana(this);desactivarBuscar();desactivarPrint();">
									</select>
									<label>Area:</label>
								</div>
								<div class="input-field col s6">
									<select id="cbPlana" onchange="activarBuscar();">
									</select>
									<label>Plana:</label>
								</div>
							</div>
						</div>
						<div class="card-action center">
							<a class="waves-effect waves-light btn blue" id="btnBuscar" onclick="activarPrint();"><i class="material-icons left">search</i>buscar</a>
							
							
							<i class="ace-icon fa fa-print bigger-160"><a class="waves-effect waves-light btn grey" id="btnImprimir" onclick="pintarTDRed();window.print();">IMPRIMIR</a></i>
<!--							<a class="btn btn-app btn-light btn-xs align-left" onclick="window.print();" target="_blank" id="iconoImprimir">
								<i class="ace-icon fa fa-print bigger-160"></i>-->
									
                    <select onchange="doSearchZona();" id="cmbZonas">
												
												<option value="NORTE">NORTE</option>
												<option value="ESTE">ESTE</option>
												<option value="LIMA">LIMA</option>
												<option value="CALLAO">CALLAO</option>
												<option value="HUANCAYO">HUANCAYO</option>
												<option value="ICA">ICA</option>
											</select>
										
						</div>
					</div>
				</div>
			</div>

			<div class="row">
				<div class="col s12">
					<div class="card">
						<div class="card-content">
							<span class="card-title" id="lblTitulo">Lista de docentes y disponibilidad</span>
						
							<div class="row">
								<div id="divListaDisponibilidad">

								</div>
							</div>
						</div>
					</div>
				</div>
			</div>

		</div>
		<!-- The actual snackbar -->
    <div id="snackbar">Se bloqueo el dia correctamente..</div>
		<script>
			
//			$("#btnBuscar").attr('disabled','disabled');
		function desactivarBuscar(){
			$("#btnBuscar").attr('disabled','disabled');
		}
			function activarBuscar(){
			$("#btnBuscar").attr('disabled',false);
		}
						
				

			var elems = document.querySelectorAll('select');
			var instances = M.FormSelect;
			document.addEventListener('DOMContentLoaded', function () {
				listarArea()

				document.querySelector('#btnBuscar').addEventListener('click', function () {
					listarDisponibilidad()
				})
				
			});
			function listarArea() {
				axios.get('../ServletArea?Accion=cargarAreaJson')
					.then(data => {
						let option = '<option value="">[SELECCIONE]</option>'
						data.data.forEach(v => {
							option += '<option value="' + v.codigoArea + '">' + v.nombreArea + '</option>'
						})
						document.querySelector('#cbArea').innerHTML = option
						instances.init(elems)
					})
			}
			
			function doSearchZona(){
				debugger
			  var tableReg = document.getElementById('tablaDispo');
				var searchText = document.querySelector('#cmbZonas').value.toLowerCase();
				var cellsOfRow = "";
				var found = false;
				var compareWith = "";

				// Recorremos todas las filas con contenido de la tabla
				for (var i = 1; i < tableReg.rows.length; i++) {
					console.log(tableReg.rows.length)
					cellsOfRow = tableReg.rows[i].getElementsByTagName('td');
					

					found = false;
					// Recorremos todas las celdas
					for (var j = 0; j < cellsOfRow.length && !found; j++) {
						compareWith = cellsOfRow[j].innerHTML.toLowerCase();
						 //console.log(cellsOfRow);
						// Buscamos el texto en el contenido de la celda
						if (searchText.length == 0 || (compareWith.indexOf(searchText) > -1))
						{
							found = true;
						}
					}
					
					if (found) {
						//mostar todo el thead y tbody
						tableReg.rows[i].style.display = '';
					} else {
						// si no ha encontrado ninguna coincidencia, esconde la
						// fila de la tabla
						
						tableReg.rows[i].style.display = 'none';
					}
				}
			}
		

			function listarDisponibilidad() {
				
				
				let codigoPlana = document.querySelector('#cbPlana').value
				let codigoPeriodo = '<%= periodo!=null?periodo.getCodigoPeriodo():""%>'
//        let distritos=new ZonaDistritoServices();
				
				if (codigoPlana && codigoPeriodo) {
					let json = {
						codigoPlana,
						codigoPeriodo
					}

					$.ajax({
						url: '../ServletHorario?Accion=listarVistaDobleDisponibilidad',
						type: 'POST',
						dataType: 'json',
						data: {
							json: JSON.stringify(json)
						},
						success: function (data, textStatus, jqXHR) {
							
						
							let html = ''
							let nTurno =[]
							let nDia=[]
							let mensaje='No registrado'
							data.data.forEach(function (docente) {
	          if(typeof(docente.celular && docente.distrito)  == "undefined"){
							
		                  html +=  '<div class="divider"></div>'
												html +=	'<div class="section">'
			                        
															html += '<h6 id="nombreDocente">' + docente.nombre + '</h6>'
															html += '<label id="codDocente" style="visibility:hidden;">' + docente.codDocente + '</label>'
																html += '<p>Celular: No registrado</p>'
																html += '<p>Distrito: No registrado</p>'
																html += '<p>Direccion: No registrado</p>'
																html += '<p>Correo: No registrado</p>'
																html += '<br>'




													if (docente.disponibilidad) {
                           
														let disponibilidad = docente.disponibilidad.split('-') || []
														let diasM = []
														let diasT = []
														let aulasM = []
														let aulasT = []

														if (docente.arrayAulas) {
															docente.arrayAulas.forEach(v => {
																if (v.turno == '1') {
																	aulasM.push(v)
																} else if (v.turno == '2') {
																	aulasT.push(v)
																}
															})
														}
														
														let diasin=docente.diasin.split('-') || []
														let diasMS = []
														let diasTS = []
														
														diasin.forEach(function(b){
															let nTurnoS = b.split('#')[0]
															let nDiaS = b.split('#')[1]
															
															if (nTurnoS == '1') {
																diasMS.push(nDiaS)
															} else if (nTurno == '2') {
																diasTS.push(nDiaS)
															}
																
														})
														
														
														let bloqueo = docente.bloqueo.split('-') || []
														let diasMB = []
														let diasTB = []
														let aulasMB = []
														let aulasTB = []
														
														 bloqueo.forEach(function(b){
															let nTurno = b.split('#')[0]
															let nDia = b.split('#')[1]
															
															if (nTurno == '1') {
																diasMB.push(nDia)
															} else if (nTurno == '2') {
																diasTB.push(nDia)
															}
																
														})
														

														disponibilidad.forEach(function (d) {
															let turno = d.split('#')[0]
															let dia = d.split('#')[1]

															if (turno == '1') {
																diasM.push(dia)
															} else if (turno == '2') {
																diasT.push(dia)
															}
														})

														html += '<p class="col s12">'
														html += '<table class="centered" id="tableDisponibilidad">'
														html += '<thead>'
														html += '<tr>'
														html += '<td>TURNO</td>'
														html += '<td id="dia">LUNES</td>'
														html += '<td id="dia">MARTES</td>'
														html += '<td id="dia">MIERCOLES</td>'
														html += '<td id="dia">JUEVES</td>'
														html += '<td id="dia">VIERNES</td>'
														html += '<td id="dia">SABADO</td>'
														html += '</tr>'
													html += '</thead>'
														html += '<tbody>'


														html += '<tr>'
														html += '<td id="turno">M</td>'

														for (let i = 0; i < 6; i++) {
															let aulas = aulasM.map(a => {
																if (a.dia == i + 1) {
																	return a.sede + ' - ' + a.aulas
																}
															})
															
															if (diasM.some(d => d == (i + 1))) {
																
																html += `<td class="green" onclick="colorChange(this);">` + aulas.join(' \n ') + `</td>`
																
															} else if(diasMB.some(t => t == ( i + 1))){
																
																html += `<td class="blue"  onclick="colorChange(this);" id="changed">` + aulas.join(' \n ') + `</td>`
																
															}else if(diasMS.some(r => r == ( i + 1))){
																
																html += `<td class="blue"  onclick="colorChange(this);" id="changed">` + aulas.join(' \n ') + `</td>`
																
															} else { 

																html += `<td class="red"  onclick="colorChange(this);" id="changed">` + aulas.join(' \n ') + `</td>`
															}
														}


														html += '</tr>'

														html += '<tr>'
														html += '<td id="turno">T</td>'

														for (let i = 0; i < 6; i++) {
															let aulas = aulasT.map(a => {
																
																if (a.dia == i + 1) {
																	return a.sede + ' - ' + a.aulas
																}
															})
															if (diasT.some(d => d == (i + 1))) {
																
																html += `<td class="green"  onclick="colorChange(this);">` + aulas.join(' \n ') + `</td>`
																
															}else if(diasTB.some( t => t == (i + 1))){
																
																html += `<td class="blue"  onclick="colorChange(this);" id="changed">` + aulas.join(' \n ') + `</td>`
																
															}else if(diasTS.some(q => q == ( i + 1))){
																
																html += `<td class="blue"  onclick="colorChange(this);" id="changed">` + aulas.join(' \n ') + `</td>`
																
															} else {
																
													
															html += `<td class="red"  onclick="colorChange(this);" id="changed">` + aulas.join(' \n ') + `</td>`
																
															}
														}

														html += '</tr>'

														html += '</tbody>'
														html += '</table>'
														html += '</p>'
														
														
													} else {
														html += '<p>EL DOCENTE NO TIENE DISPONIBILIDAD REGISTRADA</p>'
													}
                          html += `
														</div>
																		`

																		

		
		
		
	       }else{
		
		              	
									 
												html +=  '<div class="divider"></div>'
												html +=	'<div class="section">'
			                        
															html += '<h6 id="nombreDocente">' + docente.nombre + '</h6>'
															html += '<label id="codDocente" style="visibility:hidden;">' + docente.codDocente + '</label>'
																html += '<p>Celular: '+ docente.celular +'</p>'
																html += '<p>Distrito: '+ docente.distrito +'</p>'
																html += '<p>Direccion: '+ docente.direccion +'</p>'
																html += '<p>Correo: '+ docente.correo +'</p>'
																html += '<br>'




													if (docente.disponibilidad) {
                           
														let disponibilidad = docente.disponibilidad.split('-') || []
														let diasM = []
														let diasT = []
														let aulasM = []
														let aulasT = []

														if (docente.arrayAulas) {
															docente.arrayAulas.forEach(v => {
																if (v.turno == '1') {
																	aulasM.push(v)
																} else if (v.turno == '2') {
																	aulasT.push(v)
																}
															})
														}
														
														let diasin=docente.diasin.split('-') || []
														let diasMS = []
														let diasTS = []
														
														diasin.forEach(function(b){
															let nTurnoS = b.split('#')[0]
															let nDiaS = b.split('#')[1]
															
															if (nTurnoS == '1') {
																diasMS.push(nDiaS)
															} else if (nTurno == '2') {
																diasTS.push(nDiaS)
															}
																
														})
														
														
														let bloqueo = docente.bloqueo.split('-') || []
														let diasMB = []
														let diasTB = []
														let aulasMB = []
														let aulasTB = []
														
														 bloqueo.forEach(function(b){
															let nTurno = b.split('#')[0]
															let nDia = b.split('#')[1]
															
															if (nTurno == '1') {
																diasMB.push(nDia)
															} else if (nTurno == '2') {
																diasTB.push(nDia)
															}
																
														})
														

														disponibilidad.forEach(function (d) {
															let turno = d.split('#')[0]
															let dia = d.split('#')[1]

															if (turno == '1') {
																diasM.push(dia)
															} else if (turno == '2') {
																diasT.push(dia)
															}
														})

														html += '<p class="col s12">'
														html += '<table class="centered">'
													 html += '<thead>'
														html += '<tr>'
														html += '<td>TURNO</td>'
														html += '<td id="dia">LUNES</td>'
														html += '<td id="dia">MARTES</td>'
														html += '<td id="dia">MIERCOLES</td>'
														html += '<td id="dia">JUEVES</td>'
														html += '<td id="dia">VIERNES</td>'
														html += '<td id="dia">SABADO</td>'
														html += '</tr>'
														html += '</thead>'
														html += '<tbody>'


														html += '<tr>'
														html += '<td id="turno">M</td>'

														for (let i = 0; i < 6; i++) {
															let aulas = aulasM.map(a => {
																if (a.dia == i + 1) {
																	return a.sede + ' - ' + a.aulas
																}
															})
															
															if (diasM.some(d => d == (i + 1))) {
																
																html +=  `<td class="green" onclick="colorChange(this);"> `+ aulas.join(' \n ') +  `</td> `
																
															} else if(diasMB.some(t => t == ( i + 1))){
																
																html +=  '<td class="blue"  onclick="colorChange(this);" id="changed"> ' + aulas.join(' \n ') +  '</td> '
																
															}else if(diasMS.some(r => r == ( i + 1))){
																
																html +=  '<td class="blue"  onclick="colorChange(this);" id="changed"> ' + aulas.join(' \n ') +  '</td> '
																
															} else { 

																html +=  '<td class="red"  onclick="colorChange(this);" id="changed"> ' + aulas.join(' \n ') +  '</td> '
															}
														}


														html += '</tr>'

														html += '<tr>'
														html += '<td id="turno">T</td>'

														for (let i = 0; i < 6; i++) {
															let aulas = aulasT.map(a => {
																
																if (a.dia == i + 1) {
																	return a.sede + ' - ' + a.aulas
																}
															})
															if (diasT.some(d => d == (i + 1))) {
																
																html +=  `<td class="green"  onclick="colorChange(this);"> ` + aulas.join(' \n ') +  `</td> `
																
																
															}else if(diasTB.some( t => t == (i + 1))){
																
																html +=  '<td class="blue"  onclick="colorChange(this);" id="changed"> ' + aulas.join(' \n ') +  '</td> '
																
															}else if(diasTS.some(q => q == ( i + 1))){
																
																html +=  '<td class="blue"  onclick="colorChange(this);" id="changed"> ' + aulas.join(' \n ') +  '</td>'
																
															} else {
																
													
															html +=  '<td class="red"  onclick="colorChange(this);" id="changed"> ' + aulas.join(' \n ') +  '</td> '
																
															}
														}

														html += '</tr>'

														html += '</tbody>'
											      html += '</table>'
														html += '</p>'
															
													} else {
														html += '<p>EL DOCENTE NO TIENE DISPONIBILIDAD REGISTRADA</p>'
													}

											
													html += `
														</div>
																		`
																			
												
		
		
	}
		
																				
							})
							document.querySelector('#divListaDisponibilidad').innerHTML = html
						}
					})
				}

			}
			function colorChange(obj){
				debugger
				
					let periodo = '<%= periodo!=null?periodo.getCodigoPeriodo():""%>'
								
				  let codigoDoc=	$(obj).parents('div.section').find('#codDocente').text();
				  let nombreDoc=	$(obj).parents('div.section').find('#nombreDocente').text();
				  
	        let turno=	$(obj).parents('tr').find('#turno').text();
					
					let numeroTurno=0;
					if(turno === "T"){
						numeroTurno = 2
					}else if(turno === "M"){
						numeroTurno = 1
					}
					
					
					let dia=	$(obj).parent().children().index(obj);
					
					
				if($(obj).hasClass('blue')){
					
					let isBoss2 = confirm("¿Esta seguro de querer desbloquear el dia "+convertirDia(dia) +" ?");
					if(isBoss2){
							 
			          $.ajax({
								url:'../ServletHorario?Accion=rollbackDisponibilidad',
								type:'POST',
								data:{
									codDocente:codigoDoc,
									diaBloquear:dia,
									periodo:periodo,
									turno:numeroTurno
									
								},
								success: function (data, textStatus, jqXHR) {
						
								if(data.trim() == 2){
									
									if($(obj).hasClass('blue')){
										
										 $(obj).removeClass('blue');
								 
											$(obj).addClass('red');
											mostrarSnackBar();
									}
									   
								}else if(data.trim() == 3){
								   if($(obj).hasClass('blue')){
										
										 $(obj).removeClass('blue');
								 
											$(obj).addClass('green');
											mostrarSnackBar();
									}
		
		              }
										 	
								     
                }
							})
					}
					
				}else{
					
						
						let isBoss = confirm("¿Esta seguro de querer bloquear el dia "+convertirDia(dia) +" ?");
						
						if(isBoss){
							
							//aqui realizar peticion AJAX
							$.ajax({
								url:'../ServletHorario?Accion=updateDisponibilidad',
								type:'POST',
								data:{
									codDocente:codigoDoc,
									diaBloquear:dia,
									periodo:periodo,
									turno:numeroTurno
									
								},
								success: function (data, textStatus, jqXHR) {
						
								if(data.trim() == 1){
									
									if($(obj).hasClass('green')){
										
										 $(obj).removeClass('green');
											$(obj).addClass('blue');
											mostrarSnackBar();
									}else{
										 $(obj).removeClass('red');
											$(obj).addClass('blue');
											mostrarSnackBar();
									}
									   
								}else{console.log("error");}
										 	
								     
                }
							})
							
							
						
							
						}else{
							window.exit();
						}
					}			
//				$(obj).parents('tr').find('#changed').removeClass('red');
//				$(obj).parents('tr').find('#changed').addClass('blue');
				
			}
			
			function convertirDia(dia){
				let diaLetras="";
					switch(dia){
					case 1:
						diaLetras="Lunes";
				  break;
				case 2:
					diaLetras="Martes";
					break;
					case 3:
					diaLetras="Miercoles";
					break;
					case 4:
					diaLetras="Jueves";
					break;
					case 5:
					diaLetras="Viernes";
					break;
					case 6:
					diaLetras="Sabado";
					break;
					default :
						break;
					
				}
				
				return diaLetras;
			}
			
			function mostrarSnackBar() {
					// Get the snackbar DIV
					var x = document.getElementById("snackbar");

					// Add the "show" class to DIV
					x.className = "show";

					// After 3 seconds, remove the show class from DIV
					setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
				}
				
			
			
			
			

			function listarPlana(select) {
				
				let codigoArea = select.value
				axios.get('../ServletPlana?Accion=cargarPlanaJson&codigoArea=' + codigoArea)
					.then(data => {
						let option = '<option value="">[SELECCIONE]</option>'
						data.data.forEach(v => {
							option += '<option value="' + v.cod_pla + '">' + v.nom_pla + '</option>'
						})
						document.querySelector('#cbPlana').innerHTML = option
						
						instances.init(elems)
						$("#btnBuscar").attr('enabled','enabled');
					})
			}
			
			function pintarTDRed(){
				//alert("holii");
				$(".red").text("X");
			}
			 
			function desactivarPrint(){
				$("#btnImprimir").attr('disabled','disabled');
			}
			function activarPrint(){
				$("#btnImprimir").attr('disabled',false);
			}
			
		
		</script>
		<script src="js/pages/webSocketHorario.js" type="text/javascript"></script>
	</body>
</html>
