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

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

<style>
	svg[id^="mermaid-"] { min-width: 100%; font-size: 10px;}
	polygon.label-container {
		max-height: 50px !important;
	}
	g.node{
		max-height: 50px !important;
	}

	svg[aria-roledescription="flowchart-v2"]{
		-moz-transform: scale(0.75);
		-webkit-transform: scale(0.75);
		transform: scale(0.75);
		transform-origin: top center;
		top:0;
		margin-top:0px;
		margin-bottom:0px;
	}

	div.mermaid {
		margin-left: 0 !important;
		text-align: center;
		resize:both;
		overflow:auto;
		margin-bottom: 2px;
		position:relative;
		max-height: 600px;
		max-width: 100%;
	}
</style>

<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" style="margin-bottom:20px;">
					<div class="uv-table-title">
						<h6 class="uv-table-header-h6" th:text="#{admin.procedures.title}"></h6>
						<hr class="uv-procedure-hr">
						<span th:text="#{admin.procedures.subtitle}"></span>
					</div>
				</div>
				<div class="uv-table-group">
					<h5></h5>
				</div>
				<form enctype='multipart/form-data' method="POST" action="" id="procedureForm">
					<div class="uv-table-group">
						<label th:text="#{admin.instances.selector.procedure}">Proces</label>
						<select class="selectpicker" id="proceduresSelector" name="procedure" data-live-search="true" data-width="100%" data-actions-box="true" th:attr="data-none-selected-text=#{global.selectors.noData}">
					        <option th:each="item : ${procedures}" th:text="${#locale.language} == 'es' ? ${item.text2}:${item.text3}" th:attr="value=${item.value}"></option>
					    </select>
					</div>
					<br>
					<span class="btn btn-secondary pointer" onclick="formNew()"><i class="fas fa-plus"></i> <span th:text="#{admin.procedures.action.new}">Nuevo</span></span>
					<span class="btn btn-primary pointer" onclick="formDuplicate()"><i class="fas fa-copy"></i> <span th:text="#{admin.procedures.action.duplicate}">Duplicar</span></span> 
					<span class="btn btn-info pointer" onclick="formEdit()"><i class="fas fa-edit"></i> <span th:text="#{admin.procedures.action.edit}">Editar</span></span>
					<span class="btn btn-danger pointer" onclick="formRemove()"><i class="fas fa-trash"></i> <span th:text="#{admin.procedures.action.remove}">Eliminar</span></span>
					<div class="uv-table-group" id="formFields" style="margin-top:20px;"></div>
				</form>
			</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/popper.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/bootstrap-select/bootstrap-select.js}"></script>
	<script th:src="@{/js/bootstrap-select/i18n/defaults-es_ES.js}" th:if="${#locale.language} == 'es'"></script>
	<script th:src="@{/js/bootstrap-select/i18n/defaults-ca_CA.js}" th:if="${#locale.language} != 'es'"></script>
	<script th:src="@{/js/datepicker/bootstrap-datepicker.min.js}"></script>
	<script th:src="@{/js/datepicker/locales/bootstrap-datepicker.es.min.js}"></script>
	<script th:src="@{/js/datepicker/locales/bootstrap-datepicker.ca.min.js}"></script>
	<script src="https://cdn.jsdelivr.net/npm/mermaid@11.3.0/dist/mermaid.min.js"></script>
  
	<script type="text/javascript">
	
	var locale = '[[${#locale.language}]]',
		locale_new = "[[#{admin.procedures.confirm.new}]]", 
		locale_copy = "[[#{admin.procedures.confirm.copy}]]", 
		locale_edit = "[[#{admin.procedures.confirm.edit}]]", 
		locale_remove = "[[#{admin.procedures.confirm.remove}]]";

	var graphDef = '';

	$( document ).ready(function(){ 
		layout = new Layout("");
		layout.initTableLayout({paging:false});
		$('#proceduresSelector').val('').trigger('change');
		$('#proceduresSelector').change(function(){$('#formFields').hide();});
		$('#formFields').hide();
		$('#actionFields').hide();
		layout.closeLoadingSpinner(".uv-loading-spinner");

		mermaid.initialize({ startOnLoad: false, theme: "default", flowchart: { diagramPadding: 5, useMaxWidth:false, htmlLabels:true, wrap: true, wrappingWidth: 750 } });
		
		$('#procedureForm').submit(function(e) {
			$("input[type=text]").each(function() {
				var element = $(this);
				if (element.val() == "" || element.val() == " ") {
					element.val(".");
				}
			});
			$("textarea").each(function() {
				var element = $(this);
				if (element.val() == "" || element.val() == " ") {
					element.val(".");
				}
			});
			$("textarea.task").each(function() {
				var element = $(this);
				element.val(element.val().replaceAll(',', "[comma]"));
			});
			$("input[type=text].task").each(function() {
				var element = $(this);
				element.val(element.val().replaceAll(',', "[comma]"));
			});
		    return true;
		});
		
		$('#procedureForm').on('submit', function() {
			$('.hiddenFields').show();
			return true;
		});
	});
	
	function formNew(){
		$.put("/find/procedure", {procedure:0, action:"new"}, function(rawData){ 
			$('#formFields').html(rawData);
			$('.selectpicker').selectpicker('refresh');
			$('#formFields').show();
		});
		$('#formFields').show();
		$('#procedureForm').attr('action', '/admin/procedures');
	}
	
	function formDuplicate(){
		$.put("/find/procedure", {procedure:$('#proceduresSelector').val(), action:"duplicate"}, function(rawData){ 
			$('#formFields').html(rawData);
			$('.selectpicker').selectpicker('refresh');
			$('#formFields').find('.datepicker').datepicker({
				language: locale,
			    autoclose: true,
			    todayHighlight: true,
			    orientation: "bottom center",
			    clearBtn: true
			});
			$('#formFields').show();
			$('#procedureForm').attr('action', '/admin/procedures');
		});
	}
	
	function formRemove(){
		$.delete("/find/procedure", {procedure:$('#proceduresSelector').val(), action:"remove"}, function(rawData){ 
			$('#formFields').html(rawData);
			$('.selectpicker').selectpicker('refresh');
			$('#formFields').show();
			$('#procedureForm').attr('action', '/admin/procedures');
		});
	}
		
	function formEdit(){
		$.post("/find/procedure", {procedure:$('#proceduresSelector').val(), action:"edit"}, function(rawData){ 
			$('#formFields').html(rawData);
			$('.selectpicker').selectpicker('refresh');
			$('#formFields').show();
			$('#procedureForm').attr('action', '/admin/procedures');
		});
	}
	
	function newTask(){
		$.get("/newTask/"+($('.card-task').length), function(d){
			var node = $.parseHTML(d); 
			$(node).find('.datepicker').datepicker({
				language: locale,
			    autoclose: true,
			    todayHighlight: true,
			    orientation: "bottom center",
			    clearBtn: true
			});
			$(node).appendTo($('#accordion'));
			$('.selectpicker').selectpicker('refresh');
		});
	}
	
	function removeTask(id){
		$('#heading'+id).parent().remove();
	}
	
	function changeType(e){
		console.log('type');
		$(e).parent().parent().parent().find('#evidence1Fields').hide();
		$(e).parent().parent().parent().find('#evidence11Fields').hide();		
		if(parseInt($(e).val()) == 11 || parseInt($(e).val()) == 15){	
			$(e).parent().parent().parent().find('#evidence11Fields').show();
		}
		else{
			$(e).parent().parent().parent().find('#evidence1Fields').show();
		}
	}

	function loadFlowDiagramDelayed(){
		setTimeout(loadFlowDiagram, 100);
	}

	function loadFlowDiagram(){
		var nodeDefs = 'graph TD';
		var nodeRels = '';
		$('.card-task').each(function(i, d){ 
			var type = $(d).find("select[name='tipus[]']").val();
			var date = $(d).find("input[name='dataLimit[]']").val();
			var title = locale == 'es' ? $(d).find("input[name='titolCas[]']").val() : $(d).find("input[name='titolVal[]']").val();
			var rol = $(d).find( "select[name='idRol[]'] option:selected" ).text();
			var id = $(d).find("input[name='idTascap[]']").val();
			var idSeg = $(d).find("input[name='idTascaSeg[]']").val();
			var idSeg2 = $(d).find("input[name='idTascaSeg2[]']").val();
			var shape = 'rect';
			if(type == 2 || type == 20){
				shape = 'hex';
			}
			else if(type == 21 || type == 22){
				shape = 'procs';
			}
			else if(type == 1 || type == 11 || type == 12 || type == 14 || type == 15){
				shape = 'lean-r'
			}
			nodeDefs += `
${id}@{shape: ${shape}, label: "${title}<br> <strong>Asignado a:</strong>  ${rol} <br> <strong>Fecha límite: ${date}</strong>"}`; 
			if(type == 2 || type == 20){
				nodeRels += `
${id}-->|SÍ|${idSeg}
${id}-->|NO|${idSeg2}`;
			}
			else if(idSeg != 9999){
				nodeRels += `
${id}-->${idSeg}`;
			}
		});
		if(graphDef != nodeDefs+nodeRels){
			$('.mermaid').removeAttr('data-processed');
			$('.mermaid').text('');
			$('.mermaid').text(nodeDefs+nodeRels);
			$('.mermaid').css({
				'margin-left': '0 !important',
				'text-align': 'center',
				'resize':'both',
				'overflow':'auto',
				'margin-bottom': '2px',
				'position':'relative',
				'max-height': '600px',
				'max-width': '100%'
			});
			$('svg[id^="mermaid-"]').css({ 'min-width': '100%', 'font-size': '10px'});
			$('polygon.label-container').css({ 'max-height': '50px !important' });
			$('g.node').css({ 'max-height': '50px !important' });
			$('svg[aria-roledescription="flowchart-v2"]').css({
				'-moz-transform': 'scale(0.75)',
				'-webkit-transform': 'scale(0.75)',
				'transform': 'scale(0.75)',
				'transform-origin': 'top center',
				'top':'0',
				'margin-top':'0px',
				'margin-bottom':'0px'
			});
			mermaid.run({querySelector:'.mermaid'});
		}
	}

	function downloadFlowDiagram() {
		const svgElement = document.querySelector('svg[aria-roledescription="flowchart-v2"]');
		const filename = 'flujo_procedimiento_'+$('#procedure_code').text();

		if(!svgElement) {
			console.error('No se encontró ningún SVG.');
			return;
		}

		const clonedSvg = svgElement.cloneNode(true);
		const width = parseInt(clonedSvg.getAttribute('width') || 800);
		const height = parseInt(clonedSvg.getAttribute('height') || 600);

		// Embebemos los estilos de Mermaid en el SVG
		const style = document.createElement('style');
		style.textContent = Array.from(document.styleSheets)
			.filter(s => !s.href || s.href.startsWith(window.location.origin))
			.map(sheet => {
				try {
					return Array.from(sheet.cssRules).map(rule => rule.cssText).join('\n');
				} catch (e) {
					return '';
				}
			})
			.join('\n');
		clonedSvg.insertBefore(style, clonedSvg.firstChild);
		const svgData = new XMLSerializer().serializeToString(clonedSvg);
		const svgBase64 = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)));

		const img = new Image();
		img.onload = function () {
			const canvas = document.createElement('canvas');
			canvas.width = width;
			canvas.height = height;
			const ctx = canvas.getContext('2d');
			ctx.fillStyle = '#ffffff';
			ctx.fillRect(0, 0, canvas.width, canvas.height);

			ctx.drawImage(img, 0, 0);

			const pngUrl = canvas.toDataURL('image/png');
			const link = document.createElement('a');
			link.href = pngUrl;
			link.download = filename;
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
		};
		img.src = svgBase64;
	}
			
	</script>

</body>

</html>
