
jQuery(function($) {
	
	initRupI18nPromise.then(function () {
		initFilter();
		initTable();
		
		$("#tarifas_filter_form").rup_validate({
		    liveCheckingErrors: false,
		    showFieldErrorAsDefault: true,
		    showErrorsInFeedback: true,
		    showFieldErrorsInFeedback: true,
		    rules:{
		    	"fVigenciaDesde76":{date:true},
		    	"fVigenciaHasta76":{date:true},
		    }
		});
		
		$("#tarifas_filter_form [ruptype='date']").blur(function(elem) { 

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

		})
	});
	
	const initFilter = () => {
		
		$("#idNivelSoporte58_tarifas_filter_table").rup_combo({
			source: $.rup.CTX_PATH + 'combo/nivSoporte',
			sourceParam: {label: "desc", value:"idNivelSoporte58"},
			loadFromSelect:false,
			width: 'auto',
	        ordered: true,
			blank: '',
			customClasses: ['select-material'],
			rowStriping: true
		});
		
		$.rup_date({
			//yearRange: 'c-100:c+0',
	        from: "fVigenciaDesde76_tarifas_filter_table",
	        to: "fVigenciaHasta76_tarifas_filter_table",
	        mask: 'dd/mm/yyyy',
			showButtonPanel : true,
			showOtherMonths : true,
			noWeekend : true,
	     });
		
		$("#idNivelSoporte58_tarifas_detail_table").rup_combo({
			source: $.rup.CTX_PATH + 'combo/nivSoporte',
			sourceParam: {label: "desc", value:"idNivelSoporte58"},
			loadFromSelect:false,
			width: 'auto',
	        ordered: true,
			blank: '',
			customClasses: ['select-material'],
			rowStriping: true
		});
		
		$.rup_date({
			//yearRange: 'c-100:c+0',
	        from: "fVigenciaDesde76_tarifas_detail_table",
	        to: "fVigenciaHasta76_tarifas_detail_table",
	        mask: 'dd/mm/yyyy',
			showButtonPanel : true,
			showOtherMonths : true,
			noWeekend : true,
	     });
		
		Ad74aUtils.number('#tarifaDesde_tarifas_filter_table',{
			"type": "decimal",
			"enteros":2,
			"decimals": 3
		});
		
		Ad74aUtils.number('#tarifaHasta_tarifas_filter_table',{
			"type": "decimal",
			"enteros":2,
			"decimals": 3
		});
		
		Ad74aUtils.number('#tarifa76_tarifas_detail_table',{
			"type": "decimal",
			"enteros":2,
			"decimals": 3
		});
		
		var properties={
				feedback:$("#tarifas_detail_feedback"),
				liveCheckingErrors: false,
				showFieldErrorAsDefault: true,
				showErrorsInFeedback: true,
				showFieldErrorsInFeedback: true,
			  rules:{
			      "fVigenciaDesde76":{required:true},
			      "tarifa76":{required:true}
			 }
		};
		$("#tarifas_detail_form").rup_validate(properties);
		
		let tarifas_dialog = $("#tarifas_detail_div");
		let tarifas_dialog_feedback = $("#tarifas_detail_feedback");
		
		try {
			tarifas_dialog.rup_dialog("destroy");
		} catch (error) {}
		
		tarifas_dialog = $("#tarifas_detail_div");
		tarifas_dialog_feedback = $("#tarifas_detail_feedback");
		
		tarifas_dialog_feedback.rup_feedback (
			{
			  type: "ok",
			  block: false,
			}
		);	
		
		tarifas_dialog.rup_dialog( {
			type: $.rup.dialog.DIV,
			autoOpen: false,
			modal: true,
			closeOnEscape: true,
			resizable: true,
			//width:600,
			//height:600,
			dialogClass: 'custom_mid_dialog',
			title: $.rup.i18n.app.botonera.add,
			buttons : [ 
                {
                    text:$.rup.i18n.app.botonera.aceptar,
                    id:"tarifas_aceptar_btn",
                    class: 'btn-material btn-material-primary-high-emphasis',
                    click:  () => {
                    	if ($("#tarifas_detail_form").valid()){
                    		const tarifas = $("#tarifas").rup_table("getSelectedRows");

                    		let data =  $('#tarifas_detail_form').rup_form("formToJson");
                    		
                    		let url = $('#tarifas_detail_form').attr("action") + "/";
                    		url += data["idTarifaNivSop76"] != null && data["idTarifaNivSop76"] != "" ? "edit" : "add";
                    		let type = data["idTarifaNivSop76"] != null && data["idTarifaNivSop76"] != "" ? "PUT" : "POST";
                    		
                        	$.rup_ajax({
        			            url: url,
                        	    type: type,
        			            contentType: "application/json",
        			            data: JSON.stringify(data),             	
        			            success: function (data){    			            	
        			            	$("#tarifas").rup_table("reload");
        			            	tarifas_dialog.rup_dialog("close");
        			            	Ad74aUtils.desBloquearInterfaz();
        			            	$('#rup_feedback_tarifas').rup_feedback("option", "delay", 3000);
        			            	$("#rup_feedback_tarifas").rup_feedback('set', $.rup.i18n.app.feedback.operacionOK, "ok"); 
        			            },
        			            beforeSend: function(){
        			            	Ad74aUtils.cerrarFeedbacks();
        			            	Ad74aUtils.bloquearInterfaz();
        						},
        			            error:function(data){
        			            	Ad74aUtils.desBloquearInterfaz();
        			            	tarifas_dialog_feedback.rup_feedback('set', data.responseText, "error");
        			            }
        			        });
                    	}
 					}
                 },
				{
					text : $.rup.i18n.app.botonera.cancelar,
					click : () => {
						tarifas_dialog.rup_dialog("close");
					},
					btnType : $.rup.dialog.LINK
				}
			],
			open: function(){
				const tarifas = $("#tarifas").rup_table("getSelectedRows");  
			},
			close: function(){
				$("#tarifas_detail_form").rup_form("clearForm");
				$("#tarifas_detail_form").rup_validate("resetElements");
				tarifas_dialog_feedback.rup_feedback("close");
			}		    
		});
	}
	
	const initTable = () => {
		
		let tarifas_dialog = $("#tarifas_detail_div");
		let tarifas_dialog_feedback = $("#tarifas_detail_feedback");
		
		const getColumnsModel = function(){
			const getColumnModel = function (name, index, editable, hidden, orderable) {
				return {
					name: name,
					index: index,
					editable: editable,
					hidden: hidden,
					orderable: orderable
				}
			};
			let columnsModel = [];
			columnsModel.push(getColumnModel("idTarifaNivSop76", "idTarifaNivSop76", true, false));
			columnsModel.push(getColumnModel("fVigenciaDesde76", "fVigenciaDesde76", true, false));
			columnsModel.push(getColumnModel("fVigenciaHasta76", "fVigenciaHasta76", true, false));
			columnsModel.push(getColumnModel("maestroNivSoporte.idNivelSoporte58", "maestroNivSoporte.idNivSoporte58", true, false));
			columnsModel.push(getColumnModel("tarifa76", "tarifa76", true, false));
			columnsModel.push(getColumnModel("fAlta76", "fAlta76", false, true));
			columnsModel.push(getColumnModel("usuAlta76", "usuAlta76", false, true));
			columnsModel.push(getColumnModel("fModif76", "fModif76", false, true));
			columnsModel.push(getColumnModel("usuModif76", "usuModif76", false, true));
			return columnsModel;
		};

		const getColumnsDefs = function () {
			return [ 
				{
					"targets": 3,
					"render": function ( data, type, row, meta ) {
						if( data == TipoNivelSoporteAltoVal ){
							return  TipoNivelSoporteAltoDesc;
						}else if( data == TipoNivelSoporteAltoRiesgoVal ){
							return TipoNivelSoporteAltoRiesgoDesc;
						}else if( data == TipoNivelSoporteIntensoVal ){
							return TipoNivelSoporteIntensoDesc;
						}else if( data == TipoNivelSoporteModeradoVal ){
							return TipoNivelSoporteModeradoDesc;
						}else if( data == TipoNivelSoporteSinValorarVal ){
							return TipoNivelSoporteSinValorarDesc;
						}
						return  '';
					}
				}
			];
		};
		
		const getCustomButtons = function () {
			let customButons = [];	
			
			const FN_editarBorrar = {};
			FN_editarBorrar.test  = function(){
				const selectedRows  = $("#tarifas").rup_table("getSelectedRows");	
				// 1 seleccionado
				if ( selectedRows.length == undefined) {
					return true;
				}
				return false;
			};
			const anadirButton = {
					text: function () {
						return $.rup.i18n.app.botonera.add;
					},
					id: 'anadirtarifas', // Campo obligatorio si se quiere usar desde el contextMenu
					className: 'btn-material-primary-high-emphasis table_toolbar_btnView',
					icon: "mdi-plus",
					displayRegex: /^\d+$/,			
					insideContextMenu: true, 
					//type: 'view',
					action: function (e, dt) {
						tarifas_dialog.rup_dialog("open");
						const divTitleDialog = $("div[aria-describedby='tarifas_detail_div'] .ui-dialog-title");
						divTitleDialog.html('<i>'+$.rup.i18n.base.rup_table.toolbar.add+'</i>');
						$("#idTarifaNivSop76_tarifas_detail_table").val("");
						tarifas_dialog_feedback.rup_feedback("close");
					}				
			};	
			customButons.push(anadirButton);
			
			const editButton = {
					text: function () {
						return $.rup.i18n.app.botonera.edit;
					},
					id: 'editartarifas', // Campo obligatorio si se quiere usar desde el contextMenu
					className: 'btn-material-primary-high-emphasis table_toolbar_btnView',
					icon: "mdi-playlist-edit",
					displayRegex: FN_editarBorrar,			
					insideContextMenu: true, 
					//type: 'view',
					action: function (e, dt) {
						$.rup_ajax({
				              url: $.rup.CTX_PATH +"tarifas/"+ $('#tarifas').rup_table('getSelectedRows')['idTarifaNivSop76'],
				              type: "GET",            
				              dataType: 'json',
				              contentType: 'application/json',
				              beforeSend: function() {
				            	  Ad74aUtils.bloquearInterfaz();
				              },
				              complete: function() {
				            	  Ad74aUtils.desBloquearInterfaz();
				              },
				              success: function (data){
				              	 tarifas_dialog.rup_dialog("open");
				              	 const divTitleDialog = $("div[aria-describedby='tarifas_detail_div'] .ui-dialog-title");
								 divTitleDialog.html('<i>'+$.rup.i18n.base.rup_table.toolbar.edit+'</i>');
				              	 $.rup_utils.populateForm($.rup_utils.jsontoarray(data), "#tarifas_detail_form");	
				              },
				              error: function(error){ 
				                  alert("error")
				              }
				        });
					}		
			};
			customButons.push(editButton);
			
			const eliminarButton = {
					text: function () {
						return $.rup.i18n.app.botonera.eliminar;
					},
					id: 'eliminartarifas', // Campo obligatorio si se quiere usar desde el contextMenu
					className: 'btn-material-primary-high-emphasis table_toolbar_btnView',
					icon: "mdi-delete",
					displayRegex: FN_editarBorrar,			
					insideContextMenu: true, 
					//type: 'view',
					action: function (e, dt) {
						Ad74aUtils.openConfirmDialog(
							'dialogConfirm', 
							$.rup.i18n.app.dialog.title.borrarTarifas, 
							$.rup.i18n.app.dialog.label.borrarTarifas,  
							[
					        	{
					                text: $.rup.i18n.app.botonera.cancelar,
					                click: function () { 
					                    $('#dialogConfirm').rup_dialog('close'); 
					                },
					                btnType: $.rup.dialog.LINK
					            },
						        {
						            text: $.rup.i18n.app.botonera.aceptar,
						            id: "btnEliminartarifas",
						            class: 'btn-material btn-material-primary-high-emphasis',
						            click: function () { 
						            	$.rup_ajax({
								              url: $.rup.CTX_PATH +"tarifas/"+ $('#tarifas').rup_table('getSelectedRows')['idTarifaNivSop76'],
								              type: "DELETE",            
								              dataType: 'json',
								              contentType: 'application/json',
								              beforeSend: function() {
								            	  Ad74aUtils.bloquearInterfaz();
								              },
								              complete: function() {
								            	  Ad74aUtils.desBloquearInterfaz();
								            	  $('#dialogConfirm').rup_dialog('close');
								              },
								              success: function (data){
								              	  $('#rup_feedback_tarifas').rup_feedback("option", "delay", 3000);
								              	  $('#rup_feedback_tarifas').rup_feedback("set", $.rup.i18n.app.feedback.eliminadoOk, "ok");
								              	  $('#tarifas').rup_table("reload");
								              },
								              error: function(error){ 
								                  alert("error")
								              }
								        });
						            }
						        }
					        ]
						);
					}		
			};
			customButons.push(eliminarButton);
			
			return customButons;
		};

		$("#tarifas").rup_table({
			colReorder: {
				fixedColumnsLeft: 1
			},
			colModel: getColumnsModel(),
			columnDefs: getColumnsDefs(),
			primaryKey: "idTarifaNivSop76",
	     	filter:{
	  	  		id:"tarifas_filter_form",
	  	  		filterToolbar:"tarifas_filter_toolbar",
	  	  		collapsableLayerId:"tarifas_filter_fieldset",
	  	  		showHidden: true
	     	},
	     	createTooltipBody: false,// No muestra el tooltip automático de las columnas de la tabla
	   		select: {
	       		activate: true,
	       		deleteDoubleClick:true
	   		},
			buttons: {
				activate: true,
				blackListButtons: ['reportsButton', 'addButton', 'editButton', 'cloneButton', 'deleteButton', 'copyButton'],
				myButtons: getCustomButtons()
			},
			columnOrderArrows: {
			    showOnlyActive: false,
			    display: 'inline'
			},
			order: [[1, "asc"]]
		});
		
	}
	
});
