jQuery(function($){
	window.initRupI18nPromise.then(function () {
		$.rup_date({
			yearRange: 'c-100:c+100',
	        from: "fecrecep51desde_filter_table",
	        to: "fecrecep51hasta_filter_table",
	        mask: 'dd/mm/yyyy'
	    });
		
		// TODO: cargarlo en función de l sentido de la comunicación
		$("#tipoMensaje51_erroresTelevida_filter_table").rup_combo({
			//parent: ["tipoInforme_informes_filter_table"],
			sourceGroup: $.rup.CTX_PATH + 'combo/tiposMensajes?sentido='+$("input[name='sentido51']:checked").val(),
			sourceParam: {label: "label", value:"value"},
			rowStriping: true,
			ordered: false,
			blank: '',
			customClasses: ['select-material'],
			//loadFromSelect:true,
			loadFromSelect: false,
			width: 'auto',
			height: 'auto'
		});
		
		
		$("input[name='sentido51']").on("change", () => {
			const value = $("input[name='sentido51']:checked").val();
			if(value == 2) {
				let combo = $("#tipoMensaje51_erroresTelevida_filter_table");
				combo.data().settings.sourceGroup = $.rup.CTX_PATH + 'combo/tiposMensajes?sentido='+value;				
				combo.data().settings.source = "";				
				$("#tipoMensaje51_erroresTelevida_filter_table").rup_combo("reload");
			}else {
				$("#tipoMensaje51_erroresTelevida_filter_table").rup_combo("setSource", $.rup.CTX_PATH + 'combo/tiposMensajes?sentido='+value); 
			}
		});
		
		function htmlEntities(str) {
			        return String(str).replaceAll('<', '&lt;').replaceAll('>', '&gt');
			    }
		function entitiesHtml(str) {
		    return String(str).replaceAll('&lt;', '<').replaceAll('&gt', '>').replaceAll('\t','');
		}
		
		function prettifyXml(sourceXml){
		    sourceXml = entitiesHtml(sourceXml);
		  var xmlDoc = new DOMParser().parseFromString(sourceXml, 'application/xml');
		  var xsltDoc = new DOMParser().parseFromString([           
		    '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">',
		    '<xsl:output omit-xml-declaration="yes" indent="yes"/>',
		    '    <xsl:template match="node()|@*">',
		    '     <xsl:copy>',
		    '      <xsl:apply-templates select="node()|@*"/>',
		    '   </xsl:copy>',
		    '</xsl:template>',
		    '</xsl:stylesheet>',
		  ].join('\n'), 'application/xml');
		  var xsltProcessor = new XSLTProcessor();    
		  xsltProcessor.importStylesheet(xsltDoc);
		  var resultDoc = xsltProcessor.transformToDocument(xmlDoc);
		  var resultXml = new XMLSerializer().serializeToString(resultDoc);
		  resultXml = htmlEntities(resultXml);
		  return resultXml;
		};
		
		$.verMensaje = function(idError){
	        $('#verMensajeContent').html("");
	        $.rup_ajax({
	              url: $.rup.CTX_PATH +"televidaerrores/"+idError,
	              type: "GET",            
	              dataType: 'json',
	              contentType: 'application/json',
	              success: function (errorestelevida){
						console.log(errorestelevida);
	                    const xml = htmlEntities(errorestelevida.mensaje51Str);
						
						if(!errorestelevida.mensaje51Str.startsWith("#")) {
							const xmlPretty = prettifyXml(xml);
							$('#verMensajeContent').html(xmlPretty);
						}else {
							$('#verMensajeContent').html(errorestelevida.mensaje51Str);
						}
	                    
	                    
	                    $('#verMensaje').rup_dialog("open");
	                    
	              },
	              error: function(error){ 
	                    console.log(error);     
	              }
	        });
	};
	
	//Dialog
	$('#verMensaje').rup_dialog({
	    type: $.rup.dialog.DIV,
	    autoOpen: false,
	    resizable: true,
	    /*minHeight:200,       
	    maxHeight:600,
	    minWidth:850,*/
	    height:600,
		dialogClass: 'custom_mid_dialog',       
	    title: $.rup.i18n.app.erroresTelevida.dialogoMsg,
	    modal: true,
	    buttons: [
	    {
	        text: $.rup.i18n.app.botonera.aceptar,
	        click: function () { 
	            $('#verMensaje').rup_dialog('close'); 

	        }
	        
	    }

	    ] 
	});	

let tableColModels = [			
	{ 	name: "idError51",
		index: "idError51",
		editable: true, 
		hidden: false
	},
	{ 	name: "error51",
		index: "error51",
		editable: true, 
		hidden: false
	},
	{ 	name: "errormsg51",
		index: "errormsg51",
		editable: true, 
		hidden: false,
		orderable: false
	},
	{ 	name: "fecrecep51",
		index: "fecrecep51",
		editable: true, 
		hidden: false
	},
	{ 	name: "mensaje51Str",
		index: "mensaje51Str",
		editable: true, 
		sortorder:"desc",
		hidden: false
	},
	{ 	name: "sentido51",
		index: "sentido51",
		editable: true, 
		hidden: false
	},
	{ 	name: "tipomensaje51",
		index: "tipomensaje51",
		editable: true, 
		hidden: false
	},	
	{ 	name: "estado51",
		index: "estado51",
		editable: true, 
		hidden: true
	},
	
	];
	let columnDefs = [
		{
			"targets": [0, 1],                   
		    "width":'8%',
		},
		{
			"targets": 4, 
			"orderable":false,                  
		    "width":'4%',
		    "className": "text-center",
			"render": function ( data, type, row, meta ) {
				return "<a href='javascript:$.verMensaje(\"" + row.idError51 + "\");'><i class='mdi mdi-xml' style='margin-right:5px;'></i></a>";               
			}
		},
		{
			"targets": 5, 
			"orderable":false,                  
		    "width":'10%',
		    "className": "text-center",
			"render": function ( data, type, row, meta ) {
				if( data == 0) {
					return "PS \u21E8 AD74A"; 
				}else if( data == 1) {
					return "AD74A \u21E8 PS";
				}
				return '';               
			}
		},
		{
			"targets": [3, 6],                   
		    "width":'10%',
		}
	];
	

	$("#ErroresTelevida").rup_table({
		colReorder: {
		 fixedColumnsLeft: 1
		}
		,colModel: tableColModels
		,columnDefs : columnDefs
		,primaryKey: "idError51"
		,filter:{
  	  		id:"ErroresTelevida_filter_form",
  	  		filterToolbar:"ErroresTelevida_filter_toolbar",
  	  		collapsableLayerId:"ErroresTelevida_filter_fieldset",
  	  		showHidden: true
     	}
     	/*,formEdit:{
        	detailForm: "#ErroresTelevida_detail_div"
        	,fillDataMethod: "clientSide"
         	,validate:{ 
    			rules:{}
    		   	}
    		   	,titleForm: jQuery.rup.i18nParse(jQuery.rup.i18n.base,'rup_table.edit.editCaption')  
    		}*/
			,createTooltipBody: false
       		,select: {
           		activate: true
       		}
    		,seeker: {
    			activate: false
			}
			,buttons: {
				activate: true,
				blackListButtons: ['addButton', 'editButton', 'cloneButton', 'copyButton','deleteButton','pdfButton', 'odsButton', 'csvButton', 'reportsButton'],
				myButtons:[
					{
						text: function () {
							return $.rup.i18n.app.errores.btnReintentar;
						},
						id: 'reintentarErrores', // Campo obligatorio si se
													// quiere usar desde el
													// contextMenu
						className: 'btn-material-primary-high-emphasis table_toolbar_btnView',
						icon: "mdi-play",
						displayRegex: /^[1-9][0-9]*$/, // Se muestra siempre
														// que sea un numero
														// mayor a 0
						insideContextMenu: true, // Independientemente de
													// este valor, sera 'false'
													// si no tiene un id
													// definido
						type: 'view',
						action : function(e, dt, node, config) {			
							$.rup_ajax({
					              url: $.rup.CTX_PATH +"televidaerrores/relanzar/"+$('#ErroresTelevida').rup_table('getSelectedRows')['idError51'],
					              type: "POST",            
					              dataType: 'json',
					              contentType: 'application/json',
									beforeSend: function() {
										Ad74aUtils.bloquearInterfaz();
					                },
					                complete: function() {
					                	Ad74aUtils.desBloquearInterfaz();
					                },
					              success: function (){
					                   $('#rup_feedback_ErroresTelevida').rup_feedback("option", "delay", 3000);
										$('#rup_feedback_ErroresTelevida').rup_feedback("set", $.rup.i18n.app.erroresTelevida.operExito, "ok");
										
										$('#ErroresTelevida').rup_table("reload");
					                    
					              },
					              error: function(error){ 
									$('#rup_feedback_ErroresTelevida').rup_feedback("option", "delay", null);
									$('#rup_feedback_ErroresTelevida').rup_feedback("set", error.responseText/*$.rup.i18n.app.errores.errorReintentar*/, "error");

					              }
					        });				
						}
					}
				]
			},
			drawCallback: function( ctx ) {				
				//Evento doble click deshabilitado
				const rowsBody = $(ctx.nTBody);
				rowsBody.off('dblclick', 'tr');
				rowsBody.on('dblclick', 'tr', function (e) {
					const row = ctx.json.rows[this._DT_RowIndex];
					console.log(row);
					//if(row.observaciones20 != null){ 
						Ad74aUtils.openConfirmDialog(
							'dialogConfirm', 
							`Error: ${row.fecrecep51} - ${row.tipomensaje51}`, 
							row.errormsg51.replaceAll('\n', '<br/>'),  
							[
					        	{
					                text: $.rup.i18n.app.botonera.cerrar,
					                click: function () { 
					                    $('#dialogConfirm').rup_dialog('close'); 
					                },
					                btnType: $.rup.dialog.LINK
					                
					            }
					        ],
					        'custom_mid_dialog rup-message rup-message-ok overflow-y-auto'
						);
					//}
	            });
			}
			,columnOrderArrows: {
			    showOnlyActive: false,
			    display: 'inline'
			}
			,order: [[0, "desc"]]
	});
	
	$("#ErroresTelevida_filter_form").rup_validate({
	    liveCheckingErrors: false,
	    showFieldErrorAsDefault: true,
	    showErrorsInFeedback: true,
	    showFieldErrorsInFeedback: true,
	    rules:{
	    	"fecrecep51desde":{date:true},
	    	"fecrecep51hasta":{date:true},
	    }
	});
	
	$("#ErroresTelevida_filter_form [ruptype='date']").blur(function(elem) { 

		if(!$(elem.target).valid()){
            $(elem.target).val('')
        }

	})
	});
});