<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org">

<head th:replace="~{layouts/common.html :: head}"></head>

<body id="page-top">

	<!-- Navigation -->
	<nav th:replace="~{layouts/common.html :: navbar}"></nav>
 
 	<!-- Content -->
	<div class="content uv-content d-flex" id="uv-wrapper">
		<div class="bg-light border-right" id="uv-sidebar-wrapper" th:replace="~{layouts/sidebar.html :: sidebar}"></div>
		
		<div class="container uv-home-section navVisible" id="uv-content-wrapper">
			<div class="uv-loading-spinner" th:text="#{global.loading}"></div>
			<div class="col-sm-12"></div>
			<div class="uv-container">
				<div class="uv-table-group-procedure-info">
					<h6 class="uv-table-header-h6" th:text="#{supervision.procedures.title}"></h6>
					<hr class="uv-procedure-hr">
					<div class="col">
						<span class="legend-active" style="cursor:pointer;" onclick="filter('active');"><span th:text="#{procedures.list.legend.active}">Activo</span></span>
						<span class="legend-active-other" style="cursor:pointer;" onclick="filter('active-other');"><span th:text="#{procedures.list.legend.other}">No corresponde</span></span>
						<span class="legend-expired" style="cursor:pointer;" onclick="filter('expired');"><span th:text="#{procedures.list.legend.expired}">Atrasado</span></span>
						<span class="legend-done" style="cursor:pointer;" onclick="filter('done');"><span th:text="#{procedures.list.legend.done}">Finalizado</span></span>
						<span class="legend-none" style="cursor:pointer;float:right;margin-top:-8px;margin-left:5px;" onclick="download();" th:title="#{supervision.filter.download1}"><i style="width:20px;height:20px;" class="fas fa-file-csv"></i></span>
						<span class="legend-none" style="cursor:pointer;float:right;margin-top:-8px;margin-left:5px;" onclick="downloadReport();" th:title="#{supervision.filter.download2}"><i style="width:20px;height:20px;" class="fas fa-file-excel"></i></span>
						<span class="legend-none" style="cursor:pointer;float:right;margin-top:-8px;margin-left:5px;" onclick="reset();" th:title="#{supervision.filter.none}"><svg style="width:20px;height:20px;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" width="122.88px" height="110.668px" viewBox="0 0 122.88 110.668" enable-background="new 0 0 122.88 110.668" xml:space="preserve"><g><path fill-rule="evenodd" clip-rule="evenodd" d="M91.124,15.645c12.928,0,23.406,10.479,23.406,23.406 c0,12.927-10.479,23.406-23.406,23.406c-12.927,0-23.406-10.479-23.406-23.406C67.718,26.125,78.197,15.645,91.124,15.645 L91.124,15.645z M2.756,0h117.322c1.548,0,2.802,1.254,2.802,2.802c0,0.848-0.368,1.622-0.996,2.139l-10.667,13.556 c-1.405-1.375-2.95-2.607-4.614-3.672l6.628-9.22H9.43l37.975,46.171c0.59,0.516,0.958,1.254,0.958,2.102v49.148l21.056-9.623 V57.896c1.651,1.9,3.548,3.582,5.642,4.996v32.133c0,1.105-0.627,2.064-1.586,2.506l-26.476,12.758 c-1.327,0.773-3.023,0.332-3.798-1.033c-0.258-0.441-0.368-0.92-0.368-1.4V55.02L0.803,4.756c-1.07-1.106-1.07-2.839,0-3.945 C1.355,0.258,2.056,0,2.756,0L2.756,0z M96.93,28.282c1.328-1.349,3.489-1.355,4.825-0.013c1.335,1.342,1.341,3.524,0.013,4.872 l-5.829,5.914l5.836,5.919c1.317,1.338,1.299,3.506-0.04,4.843c-1.34,1.336-3.493,1.333-4.81-0.006l-5.797-5.878l-5.807,5.889 c-1.329,1.349-3.489,1.355-4.826,0.013c-1.335-1.342-1.341-3.523-0.013-4.872l5.83-5.913l-5.836-5.919 c-1.317-1.338-1.3-3.507,0.04-4.843c1.339-1.336,3.492-1.333,4.81,0.006l5.796,5.878L96.93,28.282L96.93,28.282z"/></g></svg></span>
						<span class="legend-none" style="cursor:pointer;float:right;margin-top:-8px;margin-left:5px;" onclick="sort('date');" th:title="#{supervision.filter.date}"><i style="width:20px;height:20px;" class="sort-btn-date fas fa-sort-numeric-up"></i></span>
						<span class="legend-none" style="cursor:pointer;float:right;margin-top:-8px;margin-left:5px;" onclick="sort('alpha');" th:title="#{supervision.filter.apha}"><i style="width:20px;height:20px;" class="sort-btn-alpha fas fa-sort-alpha-up"></i></span>
					</div>
				</div>
				<hr class="uv-procedure-hr">
				<div id="uv-procedure-container">
					<div class="uv-table-group-procedure" th:each="item,id : ${procedure_list}" th:attr="onclick='openProcedure('+${item.idInstancia}+')', data-id=${item.idInstancia}, data-alpha=${item.nomProces}, data-name=${item.titolCas}, data-date=${item.dataTascaActiva == null ? '0' : #dates.format(item.dataTascaActiva, 'yyyy-MM-dd')}" 
					th:classappend="${(item.estat == 'A' and item.tascaActivaAssignedToUser?'procedure-active ':'') + (item.estat == 'A' and not item.tascaActivaAssignedToUser?'procedure-active-other ':'') + (item.estat == 'C'?'procedure-cancelled ':'') + (item.estat == 'C' or item.estat == 'F'?'procedure-done ':'') + (item.tascaActivaExpired == true?'procedure-expired ':'')}">
						<div class="uv-table-title procedure">
							<input type="hidden" proc_val="id" th:value="${item.idInstancia}">
							<input type="hidden" proc_val="code" th:value="${item.nomProces}">
							<input type="hidden" proc_val="name" th:value="${#locale.language} == 'es' ? ${item.titolCas}:${item.titolVal}">
							<input type="hidden" proc_val="year" th:value="${item.cursAvaluat-1}+' - '+${item.cursAvaluat}">
							<input type="hidden" proc_val="center" th:value="${#locale.language} == 'es' ? ${item.centreCas}:${item.centreVal}">
							<input type="hidden" proc_val="tit" th:value="${#locale.language} == 'es' ? ${item.titulacioCas}:${item.titulacioVal}">
							<input type="hidden" proc_val="status" th:value="${item.estat}">
							<input type="hidden" proc_val="datelim" th:value="${#dates.format(item.dataLimTascaActiva, 'dd-MM-yyyy')}">
							<input type="hidden" proc_val="date" th:value="${#dates.format(item.dataTascaActiva, 'dd-MM-yyyy')}">
							<input type="hidden" proc_val="t_active" th:value="${#locale.language} == 'es' ? ${item.nomTascaActivaCas}:${item.nomTascaActivaVal}">
							<div class="row">
								<div class="col-md-12">
								<span style="float:right;font-size: 21px; margin-top: -10px;"><i class="fas fa-caret-down"></i></span>
									<span>  
										<strong th:text="${item.nomProces}"></strong>
										<span th:text="${#locale.language} == 'es' ? ${item.titolCas}:${item.titolVal}"></span>
									</span>
								</div>
								<div class="w-100"></div>
								<div class="col-md-7">
									<span><strong th:text="#{procedures.center}"></strong>: <span class="proc_name" th:text="${#locale.language} == 'es' ? ${item.centreCas}:${item.centreVal}"></span></span>
									<br>
									<span><strong th:text="#{procedures.titulation}"></strong>: <span class="proc_tit" th:text="${#locale.language} == 'es' ? ${item.titulacioCas}:${item.titulacioVal}"></span></span>
									<br>
									<span class="proc_year"><strong th:text="#{procedures.year.eval}"></strong>: <span th:text="${item.cursAvaluat-1}"></span> - <span th:text="${item.cursAvaluat}"></span></span>
									(<span th:text="#{procedures.year.act}"></span> 
									<span><span th:text="${item.cursActivacio-1}"></span> - <span th:text="${item.cursActivacio}"></span></span>)
								</div>	
								<div class="col-md-5" th:if="${item.estat == 'A'}">
									<span>
										<span th:text="#{procedures.activeTask}"></span>: <span th:text="${#locale.language} == 'es' ? ${item.nomTascaActivaCas}:${item.nomTascaActivaVal}"></span>
										<br>
										<span><span th:text="#{procedures.dateInstance}"></span>: <span th:text="${#dates.format(item.dataTascaActiva, 'dd-MM-yyyy')}"></span></span>
										<br>
										<span><span th:text="#{procedures.dateLimit}"></span>: <span th:text="${#dates.format(item.dataLimTascaActiva, 'dd-MM-yyyy')}"></span></span>
									</span>
								</div>
								<div class="col-md-auto" th:if="${item.estat != 'A'}">
									<strong class="float-right" th:if="${item.estat == 'F'}" th:text="#{procedures.closed}" style="margin-top:25px;"></strong>
									<strong class="float-right" th:if="${item.estat == 'C'}" th:text="#{procedures.cancelled}" style="margin-top:25px;"></strong>
								</div>
								<div class="w-100"></div>
								<div class="col">
									<p th:text="${#locale.language} == 'es' ? ${item.descripcioCas}:${item.descripcioVal}"></p>
								</div>
							</div>
						</div>
						<hr class="uv-procedure-hr">
					</div>
				</div>
				<div class="uv-table-group procedure-status">
					<a href="/supervision" class="btn btn-primary pointer" th:text="#{procedures.back}">Volver</a>
				</div>
			</div>
		</div>
	</div>
	
	<!-- contactModal -->
	<div th:replace="~{layouts/common.html :: contactModal}"></div>
	
	<!-- Footer -->
	<footer class="uv-footer uv-footer-text" th:replace="~{layouts/common.html :: footer}"></footer>
	
	<script th:src="@{/js/jquery/jquery.min.js}"></script>
	<script th:src="@{/js/bootstrap/bootstrap.min.js}"></script>
	<script th:src="@{/js/fa/all.js}"></script>
	<script th:src="@{/js/jquery/jquery.dataTables.min.js}"></script>
	<script th:src="@{/js/jquery/jquery.dataTables.responsive.min.js}"></script>
	<script th:src="@{/js/jquery/jquery.dataTables.rowReorder.min.js}"></script>
	<script th:src="@{/js/bootstrap/dataTables.bootstrap4.min.js}"></script>
	<script th:src="@{/js/jquery-easing/jquery.easing.min.js}"></script>
	<script th:src="@{/js/saic.js}"></script>
	<script th:src="@{/js/datepicker/bootstrap-datepicker.min.js}"></script>
	<!-- <script th:src="@{/js/csv-to-xls/xlsx-0.20.0.min.js}"></script> -->
	<script th:src="@{/js/sheetjs/xlsx.min.js}"></script>
  
	<script type="text/javascript">
	
		var sort_key = getCookie('sort_key');
		var sort_typ = getCookie('sort_typ');
		var filter_act = getCookie('filter');
		var req = new XMLHttpRequest();

		$( document ).ready(function(){ 
			layout = new Layout("");
			layout.initTableLayout({paging:false});
			layout.closeLoadingSpinner(".uv-loading-spinner");
			if(sort_key != '' && sort_typ != ''){
				sort_initial(sort_key, sort_typ);
			}
			if(filter_act != ''){
				filter(filter_act);
			}
			
		});
		
		function openProcedure(id){
			window.location.replace('/procedure/'+id);
		}
		
		function filter(t){
			if(t != 'none'){
				$('.uv-table-group-procedure').hide();
				$('.procedure-'+t).show();
				setCookie('filter', t, 1);
			}
		}
		
		function download(){
			var rows = [];
			$('.uv-table-group-procedure:visible').each(function(i, d){
				rows.push({"Instancia":$(d).find("input[proc_val='id']").first().val(),
							"Código":$(d).find("input[proc_val='code']").first().val(),
							"Procedimiento":$(d).find("input[proc_val='name']").first().val(),
							"Curso":$(d).find("input[proc_val='year']").first().val(),
							"Centro":$(d).find("input[proc_val='center']").first().val(),
							"Titulación":$(d).find("input[proc_val='tit']").first().val(),
							"Estado":translateStatus($(d).find("input[proc_val='status']").first().val()),
							"Tarea activa":$(d).find("input[proc_val='t_active']").first().val(),
							"Fecha":$(d).find("input[proc_val='date']").first().val(),
							"Vencimiento":$(d).find("input[proc_val='datelim']").first().val()});
			});
			
			var col_sizes = [{wpx:80}, {wpx:70}, {wpx:250}, {wpx:70}, {wpx:250}, {wpx:250}, {wpx:90}, {wpx:150}, {wpx:70}, {wpx:70}];
			var row_sizes = [{hpx: 25}];
			rows.forEach(function(v, k){
				row_sizes.push({hpx: 25});
			});
			
			const sheet = XLSX.utils.json_to_sheet(rows);
			sheet["!cols"] = col_sizes;
			sheet["!rows"] = row_sizes;
			const book = XLSX.utils.book_new();
			XLSX.utils.book_append_sheet(book, sheet, "datos");
			XLSX.writeFile(book, "export.xlsx", { compression: true });
		}
		
		function downloadReport(){
			var rows = [];
			var cols = [];
			const DEF_BORDER = {top: {style: 'thin', color: {rgb: 'FF000000'}}, 
			          right: {style: 'thin', color: {rgb: 'FF000000'}}, 
			          bottom: {style: 'thin', color: {rgb: 'FF000000'}}, 
			          left: {style: 'thin', color: {rgb: 'FF000000'}}};
			const DEF_ALIGNMENT = {horizontal: "center", 
						 	 	   vertical: "center", 
						 		   wrapText: true};
			$('.uv-table-group-procedure:visible').each(function(i, d){
				if(rows.find(o => o['Código'] === $(d).find("input[proc_val='code']").first().val()+' '+$(d).find("input[proc_val='year']").first().val()) === undefined){
					rows.push({"Código":$(d).find("input[proc_val='code']").first().val()+' '+$(d).find("input[proc_val='year']").first().val()});
				}
				if(!cols.includes($(d).find("input[proc_val='tit']").first().val())){
					cols.push($(d).find("input[proc_val='tit']").first().val());
				}
				var t = rows.find(o => o['Código'] === $(d).find("input[proc_val='code']").first().val()+' '+$(d).find("input[proc_val='year']").first().val());
				t[$(d).find("input[proc_val='tit']").first().val()] = translateStatus($(d).find("input[proc_val='status']").first().val());
			});
			
			rows.forEach(function(d){
				cols.forEach(function(z){
					if(!d.hasOwnProperty(z)){
						d[z] = '';
					}
				});
			});
			
			var col_sizes = [{wpx:120}];
			var row_sizes = [{hpx: 40}, {hpx: 40}];
			cols.forEach(function(v, k){
				col_sizes.push({wpx:v.length*5});
			});
			
			var sheet = XLSX.utils.json_to_sheet(rows, {origin: "A2"});
			
			sheet["!merges"] = [{s: {r: 0, c: 0}, e: {r: 0, c: cols.length}}];
			XLSX.utils.sheet_add_aoa(sheet, [ ["PROCESOS SAIC"] ], {origin: "A1", skipHeader:true});
			sheet['A1'].t = 's';
			sheet['A1'].s = {font: {bold:true}, 
							  fill: {patternType:"solid", 
								     bgColor:{rgb:"FFA1A1A1"}, 
								     fgColor:{rgb:"FFA1A1A1"}},
							  alignment: DEF_ALIGNMENT,
					 	 	  border: DEF_BORDER};						
			
			for(var i = 0; i<=cols.length; i++){
				sheet[String.fromCharCode('A'.charCodeAt()+i)+'2'].t = 's';
				sheet[String.fromCharCode('A'.charCodeAt()+i)+'2'].s = {font: {bold:true}, 
								  fill: {patternType:"solid", 
									     bgColor:{rgb:"FFBDD7EE"}, 
									     fgColor:{rgb:"FFBDD7EE"}},
								  alignment: DEF_ALIGNMENT,
								  border: DEF_BORDER};	
			}
			for(var i = 3; i<=rows.length+2; i++){
				sheet['A'+i].t = 's';
				sheet['A'+i].s = {font: {bold:true}, 
								  fill: {patternType:"solid", 
									     bgColor:{rgb:"FFA1A1A1"}, 
									     fgColor:{rgb:"FFA1A1A1"}},
								  alignment: DEF_ALIGNMENT,
						 	 	  border: DEF_BORDER};	
				row_sizes.push({hpx: 25});
			}
			for(var i = 3; i<=rows.length+2;i++){
				for(var j = 1; j<=cols.length; j++){
					sheet[String.fromCharCode('A'.charCodeAt()+j)+i].t = 's';
					sheet[String.fromCharCode('A'.charCodeAt()+j)+i].s = {
									  fill: {patternType:"solid", 
										     bgColor:{rgb:"FFD4D4D4"}, 
										     fgColor:{rgb:"FFD4D4D4"}},
									  alignment: DEF_ALIGNMENT,
									  border: DEF_BORDER};
				}
			}
			sheet["!cols"] = col_sizes;
			sheet["!rows"] = row_sizes;
			const book = XLSX.utils.book_new();
			XLSX.utils.book_append_sheet(book, sheet, "datos");
			XLSX.writeFile(book, "export.xlsx");
		}
		
		function downloadBlob(content, filename, contentType) {
			var blob = new Blob([content], { type: contentType });
			var url = URL.createObjectURL(blob);
			var pom = document.createElement('a');
			pom.href = url;
			pom.setAttribute('download', filename);
			pom.click();
		}
		
		function reset(){
			$('.uv-table-group-procedure').show();
			sort_initial('name', 'asc');
			setCookie('filter', 'none', 1);
			setCookie('sort_key', 'name', 1);
			setCookie('sort_typ', 'asc', 1);
		}
		
		function translateStatus(d){
			if(d == 'A'){
				return 'Activo/Pendiente';	
			}
			else if(d == 'F'){
				return 'Finalizado';	
			}
			else{
				return d;	
			}
		}
		
		function comparator_desc(a, b) {
			if (a.dataset[sort_key] == null || a.dataset[sort_key] == undefined)
				return -1;
            if (a.dataset[sort_key] > b.dataset[sort_key])
                return -1;
            if (a.dataset[sort_key] < b.dataset[sort_key])
                return 1;
            return 0;
        }
        
        function comparator_asc(a, b) {
			if (a.dataset[sort_key] == null || a.dataset[sort_key] == undefined)
				return 1;
            if (a.dataset[sort_key] < b.dataset[sort_key])
                return -1;
            if (a.dataset[sort_key] > b.dataset[sort_key])
                return 1;
            return 0;
        }
        
        function sort_initial(k, t){
        	var subjects = document.querySelectorAll(".uv-table-group-procedure");
            var subjectsArray = Array.from(subjects);
            if(t == 'asc'){
				sorted = subjectsArray.sort(comparator_asc);
            }
            else{
            	sorted = subjectsArray.sort(comparator_desc);
            }
            sorted.forEach(e =>
            document.querySelector("#uv-procedure-container")
            		.appendChild(e));
            sort_change_icons(sort_key, sort_typ);
        }
          
        function sort(k) {
        	sort_key = k;
        	var subjects = document.querySelectorAll(".uv-table-group-procedure");
            var subjectsArray = Array.from(subjects);
            let sorted;
        	if(sort_typ === '' || sort_typ == 'desc'){
				sort_typ = 'asc';
				sorted = subjectsArray.sort(comparator_asc);
			}
			else{
				sort_typ = 'desc';
				sorted = subjectsArray.sort(comparator_desc);
			}
            sorted.forEach(e =>
                document.querySelector("#uv-procedure-container")
                		.appendChild(e));
                    
            sort_change_icons(sort_key, sort_typ);
			
			setCookie('sort_key', sort_key, 1);
			setCookie('sort_typ', sort_typ, 1);
        }
        
        function sort_change_icons(k, t){
        	if(k == 'alpha'){
				$('.sort-btn-alpha').removeClass('fa-sort-alpha-down');
				$('.sort-btn-alpha').removeClass('fa-sort-alpha-up');
				if(t == 'asc'){
					$('.sort-btn-alpha').addClass('fa-sort-alpha-up');
				}
				else{
					$('.sort-btn-alpha').addClass('fa-sort-alpha-down');
				}	
			}
			else if(k == 'date'){
				$('.sort-btn-date').removeClass('fa-sort-numeric-down');
				$('.sort-btn-date').removeClass('fa-sort-numeric-up');
				if(t == 'asc'){
					$('.sort-btn-date').addClass('fa-sort-numeric-up');
				}
				else{
					$('.sort-btn-date').addClass('fa-sort-numeric-down');
				}
			}
        }
        
		function setCookie(cname, cvalue, exdays) {
			const d = new Date();
			d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
			let expires = "expires="+d.toUTCString();
			document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
		}
		
		function getCookie(cname) {
			let name = cname + "=";
			let ca = document.cookie.split(';');
			for(let i = 0; i < ca.length; i++) {
				let c = ca[i];
				while (c.charAt(0) == ' ') {
					c = c.substring(1);
				}
				if (c.indexOf(name) == 0) {
					return c.substring(name.length, c.length);
				}
			}
			return "";
		}
		
		
	</script>

</body>

</html>
