//@ sourceURL=busquedaExpedientes.js
jQuery(function($){

	let loaded = false;
	initRupI18nPromise.then(function() {
		prepareData();		
	});
	
	function prepareData(){
		Ad74aUtils.hacerPlegable();
		
		$("input[name='_urgencia00']").remove();
		
		$.rup_date({
			yearRange: 'c-100:c+0',
	        from: "fResolDesde_filter_table",
	        to: "fResolHasta_filter_table",
	        mask: 'dd/mm/yyyy',
			showButtonPanel : true,
			showOtherMonths : true,
			noWeekend : true
	     });
		
		$.rup_date({
			yearRange: 'c-100:c+0',
	        from: "fRegistroDesde_filter_table",
	        to: "fRegistroHasta_filter_table",
	        mask: 'dd/mm/yyyy',
			showButtonPanel : true,
			showOtherMonths : true,
			noWeekend : true
	     });	
//		$("#fRegistroDesde_filter_table").rup_date({
//				yearRange: 'c-100:c+0',
//				mask: 'dd/mm/yyyy',
//				showButtonPanel : true,
//				showOtherMonths : true,
//				noWeekend : true
//		});
//		$("#fRegistroHasta_filter_table").rup_date({
//			 yearRange: 'c-100:c+0',
//			 mask: 'dd/mm/yyyy',
//			 showButtonPanel : true,
//			 showOtherMonths : true,
//			 noWeekend : true
//		});
//		
		$.rup_date({
			yearRange: 'c-100:c+0',
	        from: "fAperturaExpDesde_filter_table",
	        to: "fAperturaExpHasta_filter_table",
	        mask: 'dd/mm/yyyy',
			showButtonPanel : true,
			showOtherMonths : true,
			noWeekend : true
	     });		
		
		
		$.rup_date({
			yearRange: 'c-100:c+0',
	        from: "fUltimoTramiteDesde_filter_table",
	        to: "fUltimoTramiteHasta_filter_table",
	        mask: 'dd/mm/yyyy',
			showButtonPanel : true,
			showOtherMonths : true,
			noWeekend : true
	     });
		
		$("#idprovincia06_filter_table").rup_combo({
			source:  $.rup.CTX_PATH + 'nora/provincias',
			sourceParam: {label: "descProvincia", value:"codProvincia"},
			rowStriping: true,
			width: 'auto',
			blank: '',
			customClasses: ['select-material']
			
		});
		
		$("#idmunicipio06_filter_table").rup_combo({
			parent: ["idprovincia06_filter_table"],			
			source: $.rup.CTX_PATH + 'nora/municipioEnlazado',
			sourceParam: {label: "descripcion", value:"codMunicipio"},
			rowStriping: true,
			width: 'auto',
			blank: '',
			customClasses: ['select-material']
			
		});
		
		$("#busquedaExpedientes_filter_form").rup_validate({
		    feedback:$("#rup_feedback_emergencias"),
		    liveCheckingErrors: false,
		    showFieldErrorAsDefault: true,
		    showErrorsInFeedback: true,
		    showFieldErrorsInFeedback: true,
		    rules:{
		    	"fRegistroDesde":{date:true},
		    	"fRegistroHasta":{date:true},
		    	"fAperturaExpDesde":{date:true},
		    	"fAperturaExpHasta":{date:true},
		    	"fResolDesde":{date:true},
		    	"fResolHasta":{date:true},
		    	"fUltimoTramiteDesde":{date:true},
		    	"fUltimoTramiteHasta":{date:true}
		    }
		});
		
		$("#busquedaExpedientes_filter_form [ruptype='date']").blur(function(elem) { 

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

		})
		
		
		
		$("#idTipoNot00_filter_table").rup_combo({
			loadFromSelect:true,
			width: 'auto',
	        ordered: false,
			customClasses: ['select-material'],
			rowStriping: true,
			blank: '',
			selected: (function(){ try { return expedienteFilter.idTipoNot00} catch { return null}})()
		});
		$("#idTipoEntrada00_filter_table").rup_combo({
			loadFromSelect:true,
			width: 'auto',
	        ordered: false,
			customClasses: ['select-material'],
			rowStriping: true,
			blank: '',
			selected: (function(){ try { return expedienteFilter.idTipoEntrada00} catch { return null}})()
		});
		$("#idProcedimiento00_filter_table").rup_combo({
			loadFromSelect:true,
			width: 'auto',
	        ordered: false,
			customClasses: ['select-material'],
			rowStriping: true,
			blank: '',
			selected: (function(){ try { return expedienteFilter.idProcedimiento00} catch { return null}})()
		});
		$("#idEstado30_filter_table").rup_combo({
			loadFromSelect:true,
			width: 'auto',
	        ordered: false,
			customClasses: ['select-material'],
			rowStriping: true,
			blank: '',
			selected: (function(){ try { return expedienteFilter.estados.idEstado30} catch { return null}})(),
			onLoadSuccess:function(obj){ $(obj.parent().children(".ui-selectmenu-menu").children()[0]).css("height" ,"300px")}
		});
		
		
		

	}
	
			
	let tableColModels = [			
			{ 	name: "urgencia",
				index: "urgencia",
				editable: false, 
				hidden: false,
				orderable: false
				
			},
			{ 	name: "solicitantes.identificador01",
				index: "solicitantes.identificador01",
				editable: true, 
				hidden: false
			},
			{ 	name: "solicitantes.nombre01",
				index: "solicitantes.nombre01",
				editable: true, 
				hidden: false
			},
			{ 	name: "idTipoEntrada00",
				index: "idTipoEntrada00",
				editable: true, 
				hidden: false
			},
			{ 	name: "idProcedimiento00",
				index: "idProcedimiento00",
				editable: true, 
				hidden: false
			},
			{ 	name: locale=='Es'?"estados.descripcionEs30":'estados.descripcionEu30',
				index: locale=='Es'?"estados.descripcionEs30":'estados.descripcionEu30',
				editable: true, 
				hidden: false
			},
			{ 	name: "fRegistroOtro00",
				index: "fRegistroOtro00",
				editable: true, 
				hidden: false
			},
			{ 	name: "fRegistro00",
				index: "fRegistro00",
				editable: true, 
				hidden: false
			},
			{ 	name: "numRegistro00",
				index: "numRegistro00",
				editable: true, 
				hidden: false
			},
			{ 	name: "numExpediente00",
				index: "numExpediente00",
				editable: true, 
				hidden: false
			}
			];

	let columnDefs = [ 
		{ 
			"targets": 0,
			"className": "icons-column",
			"render": function(data, type, row, settings){	
				let iconUrgencia = "";
				if( row.urgencia00 >= 1 ){
					iconUrgencia = `
						<span class="mdi mdi-clock-fast naranja sol_urgente_icon " 
							style="float: right;">
						</span>
					`;
				}
				let iconError = "";
				if( row.errorExpediente00 != 0 && row.errorExpediente00 != null ){
					iconError = `
						<span class="mdi mdi-alert-outline rojo sol_error_icon" 
							style="float: right;" msg="${row.errorExpediente00_desc}">
						</span>
					`;
				}
				
				return iconError + iconUrgencia;	
			}
		},
		{
			"targets": 1,
			"render": function ( data, type, row, meta ) {
				if(row.solicitantes.identificador01 == IDENTIFICADOR_DEFECTO) {
					return '';
				}
				return row.solicitantes.identificador01;
			}
		},
		{
			"targets": 2,
			"render": function ( data, type, row, meta ) {
				return row.solicitantes.nombreCompleto;
			}
		},
		{
			"targets": 3,
			"render": function ( data, type, row, meta ) {
				if(IDTIPOENTRADA00_PAPEL0_VAL == data){
					return IDTIPOENTRADA00_PAPEL0_DESC;
				}else if(IDTIPOENTRADA00_PRESENCIAL_VAL == data){
					return IDTIPOENTRADA00_PRESENCIAL_DESC;
				}else if(IDTIPOENTRADA00_TELEMATICA_VAL == data){
					return IDTIPOENTRADA00_TELEMATICA_DESC;
				}else if(IDTIPOENTRADA00_OFICIO_VAL == data){
					return IDTIPOENTRADA00_OFICIO_DESC;
				}else {
					return '';
				}
			}
		},
		{
			"targets": 4,
			"render": function ( data, type, row, meta ) {
				return row.procedimientoDesc;
			}
		},
		{
			"targets": 9,
			"render": function ( data, type, row, meta ) {
				if ( data != null ) {						 
					const url = '../expedientes/detail/' + row.idExpediente00;
					return `<a href='javascript:window.open("${url}", "exp_${row.idExpediente00}");'>${data}</a>`;
				}						
				return "";
			}
		}
	];

	const getCustomButtons = function () {
		
		let customButons = [];

		const editarButton = {
			text: function () {
				return $.rup.i18n.app.botonera.edit;
			},
			id: 'editar', // Campo obligatorio si se quiere usar desde el contextMenu
			className: 'btn-material-primary-high-emphasis table_toolbar_btnView',
			icon: "mdi mdi-playlist-edit",
			displayRegex: /^[1]*$/,
			insideContextMenu: true,
			//type: 'view',
			action: function (e, dt) {
				const selectedRows  = $("#busquedaExpedientes").rup_table("getSelectedRows");	
				let url = '../expedientes/detail/' + selectedRows.idExpediente00;
				if(selectedRows.estados.idEstado30 == ESTADO_PEND_COMPLETAR_VAL) {
					url = '../bandejapapel0/solicitud/' + selectedRows.idExpediente00;
				}								
				window.open(url,"exp_"+selectedRows.idExpediente00)
			}
		};
		customButons.push(editarButton);
		
		return customButons;
	};

	
	$("#busquedaExpedientes").rup_table({
		colReorder: {
		 fixedColumnsLeft: 1
		}
		,colModel: tableColModels
		,columnDefs : columnDefs
		,primaryKey: "idExpediente00"
		
		,filter:{
  	  		id:"busquedaExpedientes_filter_form",
  	  		filterToolbar:"busquedaExpedientes_filter_toolbar",
  	  		collapsableLayerId:"busquedaExpedientes_filter_fieldset"
  	  		,showHidden: true
     	},
     	createTooltipBody: false // No muestra el tooltip automático de las columnas de la tabla
		,noEdit : true
		,select: {
	   		activate: true
		}
		,seeker: {
			activate: false
		},
		buttons: {
			activate: true,
			blackListButtons: ['addButton', 'editButton', 'cloneButton', 'copyButton','deleteButton','pdfButton', 'odsButton', 'csvButton'],
			myButtons: getCustomButtons()
		},	
		"rowCallback": function( row, data, index ) {
//			console.log(data);
			if ( data.urgencia00 >= 1 && (data.errorExpediente00 == 0 || data.errorExpediente00 == null)) {
				$(row).addClass('orange_row');
			} else if( data.errorExpediente00 != 0 && data.errorExpediente00 != null ) {
				$(row).addClass('red_row');					
			}			
		},
		drawCallback: function( settings ) {
			$(".sol_urgente_icon").rup_tooltip({
				content: {
					text: $.rup.i18n.app.tooltip.urgente
				}, 
				position: {
					my: 'bottom left',  // Position my top left...
					at: 'top left', // at the bottom right of...
				},   
				style: { 
					classes: 'qtip-orange' 
				}
			});
			
			$(".sol_error_icon").rup_tooltip({
				content: {
					 text: function(event, api) {
				            return $(this).attr('msg');
				        }
					}, 
				position: {
					my: 'bottom left',  // Position my top left...
					at: 'top left', // at the bottom right of...
				},   
				style: { 
					classes: 'qtip-red' 
				}
			});
		},
		columnOrderArrows: {
		    showOnlyActive: false,
		    display: 'inline'
		},
		order: [[0, "desc"],[7, "asc"]],
		"initComplete": function(settings, json) {
			
			$("#busquedaExpedientes_filter_cleanButton").click( (e) => {
				// Comprobar si hay parámetros en la URL. Si los hay, los quitamos y recargamos la página					
				const urlObj = new URL(window.location.href);
				if(urlObj.search != ''){				
					Ad74aUtils.bloquearInterfaz();
					urlObj.search = '';
					window.location.href = urlObj.toString();
				}
				
			});
		}
	});
});