
jQuery(function($) {
	
	initRupI18nPromise.then(function () {
		initFilter();
		initTable();
	});
	
	const initFilter = () => {
		
		var properties={
				feedback:$("#maestromotanulacion_detail_feedback"),
				liveCheckingErrors: false,
				showFieldErrorAsDefault: true,
				showErrorsInFeedback: true,
				showFieldErrorsInFeedback: true,
			  rules:{
			      "codAnulacion57":{required:true},
			      "descEs57":{required:true},
			      "descEu57":{required:true}
			 }
		};
		$("#maestromotanulacion_detail_form").rup_validate(properties);
		
		let maestromotanulacion_dialog = $("#maestromotanulacion_detail_div");
		let maestromotanulacion_dialog_feedback = $("#maestromotanulacion_detail_feedback");
		
		try {
			maestromotanulacion_dialog.rup_dialog("destroy");
		} catch (error) {}
		
		maestromotanulacion_dialog = $("#maestromotanulacion_detail_div");
		maestromotanulacion_dialog_feedback = $("#maestromotanulacion_detail_feedback");
		
		maestromotanulacion_dialog_feedback.rup_feedback (
			{
			  type: "ok",
			  block: false,
			}
		);	
		
		maestromotanulacion_dialog.rup_dialog( {
			type: $.rup.dialog.DIV,
			autoOpen: false,
			modal: true,
			closeOnEscape: true,
			resizable: true,
			//width:600,
			//height:600,
			dialogClass: 'custom_small_dialog',
			title: $.rup.i18n.app.botonera.add,
			buttons : [ 
                {
                    text:$.rup.i18n.app.botonera.aceptar,
                    id:"maestromotanulacion_aceptar_btn",
                    class: 'btn-material btn-material-primary-high-emphasis',
                    click:  () => {
                    	if ($("#maestromotanulacion_detail_form").valid()){
                    		const maestromotanulacion = $("#maestromotanulacion").rup_table("getSelectedRows");

                    		let data =  $('#maestromotanulacion_detail_form').rup_form("formToJson");
                    		delete data["_ctaErronea57"];
                    		
                    		let url = $('#maestromotanulacion_detail_form').attr("action") + "/";
                    		url += data["idMotivoAnul57"] != null && data["idMotivoAnul57"] != "" ? "edit" : "add";
                    		let type = data["idMotivoAnul57"] != null && data["idMotivoAnul57"] != "" ? "PUT" : "POST";
                    		
                        	$.rup_ajax({
        			            url: url,
                        	    type: type,
        			            contentType: "application/json",
        			            data: JSON.stringify(data),             	
        			            success: function (data){    			            	
        			            	$("#maestromotanulacion").rup_table("reload");
        			            	maestromotanulacion_dialog.rup_dialog("close");
        			            	Ad74aUtils.desBloquearInterfaz();
        			            	$("#rup_feedback_maestromotanulacion").rup_feedback('set', $.rup.i18n.app.feedback.operacionOK, "ok"); 
        			            },
        			            beforeSend: function(){
        			            	Ad74aUtils.cerrarFeedbacks();
        			            	Ad74aUtils.bloquearInterfaz();
        						},
        			            error:function(data){
        			            	Ad74aUtils.desBloquearInterfaz();
        			            	maestromotanulacion_dialog_feedback.rup_feedback('set', data.responseText, "error");
        			            }
        			        });
                    	}
 					}
                 },
				{
					text : $.rup.i18n.app.botonera.cancelar,
					click : () => {
						maestromotanulacion_dialog.rup_dialog("close");
					},
					btnType : $.rup.dialog.LINK
				}
			],
			open: function(){
				const maestromotanulacion = $("#maestromotanulacion").rup_table("getSelectedRows");  
			},
			close: function(){
				$("#maestromotanulacion_detail_form").rup_form("clearForm");
				$("#maestromotanulacion_detail_form").rup_validate("resetElements");
				maestromotanulacion_dialog_feedback.rup_feedback("close");
			}		    
		});
	}
	
	const initTable = () => {
		
		let maestromotanulacion_dialog = $("#maestromotanulacion_detail_div");
		let maestromotanulacion_dialog_feedback = $("#maestromotanulacion_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("idMotivoAnul57", "idMotivoAnul57", false, true, false));
			columnsModel.push(getColumnModel("codAnulacion57", "codAnulacion57", true, false));
			columnsModel.push(getColumnModel("descEs57", "descEs57", true, false));
			columnsModel.push(getColumnModel("descEu57", "descEu57", true, false));
			columnsModel.push(getColumnModel("ctaErronea57", "ctaErronea57", true, false));
			columnsModel.push(getColumnModel("fAlta57", "fAlta57", false, true));
			columnsModel.push(getColumnModel("usuAlta57", "usuAlta57", false, true));
			columnsModel.push(getColumnModel("fModif57", "fModif57", false, true));
			columnsModel.push(getColumnModel("usuModif57", "usuModif57", false, true));
			return columnsModel;
		};

		const getColumnsDefs = function () {
			return [ 
				{
					"targets": 4,
					"render": function ( data, type, row, meta ) {
						if(row.ctaErronea57 == VALOR_NO){
							return '<span class="mdi mdi-check"></span>'
						}else if (row.ctaErronea57 == VALOR_SI){
							return '<span class="mdi mdi-close"></span>'
						}else{
							return data;
						}
					}
				}
			];
		};
		
		const getCustomButtons = function () {
			let customButons = [];	
			
			const FN_editarBorrar = {};
			FN_editarBorrar.test  = function(){
				const selectedRows  = $("#maestromotanulacion").rup_table("getSelectedRows");	
				// 1 seleccionado
				if ( selectedRows.length == undefined) {
					return true;
				}
				return false;
			};
			const anadirButton = {
					text: function () {
						return $.rup.i18n.app.botonera.add;
					},
					id: 'anadirmaestromotanulacion', // 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) {
						maestromotanulacion_dialog.rup_dialog("open");
						const divTitleDialog = $("div[aria-describedby='maestromotanulacion_detail_div'] .ui-dialog-title");
						divTitleDialog.html('<i>'+$.rup.i18n.base.rup_table.toolbar.add+'</i>');
						$("#idMotivoAnul57_maestromotanulacion_detail_table").val("");
						maestromotanulacion_dialog_feedback.rup_feedback("close");
					}				
			};	
			customButons.push(anadirButton);
			
			const editButton = {
					text: function () {
						return $.rup.i18n.app.botonera.edit;
					},
					id: 'editarmaestromotanulacion', // 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 +"maestromotanulacion/"+ $('#maestromotanulacion').rup_table('getSelectedRows')['idMotivoAnul57'],
				              type: "GET",            
				              dataType: 'json',
				              contentType: 'application/json',
				              beforeSend: function() {
				            	  Ad74aUtils.bloquearInterfaz();
				              },
				              complete: function() {
				            	  Ad74aUtils.desBloquearInterfaz();
				              },
				              success: function (data){
				              	 maestromotanulacion_dialog.rup_dialog("open");
				              	 const divTitleDialog = $("div[aria-describedby='maestromotanulacion_detail_div'] .ui-dialog-title");
								 divTitleDialog.html('<i>'+$.rup.i18n.base.rup_table.toolbar.edit+'</i>');
				              	 $.rup_utils.populateForm($.rup_utils.jsontoarray(data), "#maestromotanulacion_detail_form");	
				              },
				              error: function(error){ 
				                  alert("error")
				              }
				        });
					}		
			};
			customButons.push(editButton);
			
			const eliminarButton = {
					text: function () {
						return $.rup.i18n.app.botonera.eliminar;
					},
					id: 'eliminarmaestromotanulacion', // 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.borrarMaestromotanulacion, 
							$.rup.i18n.app.dialog.label.borrarMaestromotanulacion,  
							[
					        	{
					                text: $.rup.i18n.app.botonera.cancelar,
					                click: function () { 
					                    $('#dialogConfirm').rup_dialog('close'); 
					                },
					                btnType: $.rup.dialog.LINK
					            },
						        {
						            text: $.rup.i18n.app.botonera.aceptar,
						            id: "btnEliminarmaestromotanulacion",
						            class: 'btn-material btn-material-primary-high-emphasis',
						            click: function () { 
						            	$.rup_ajax({
								              url: $.rup.CTX_PATH +"maestromotanulacion/"+ $('#maestromotanulacion').rup_table('getSelectedRows')['idMotivoAnul57'],
								              type: "DELETE",            
								              dataType: 'json',
								              contentType: 'application/json',
								              beforeSend: function() {
								            	  Ad74aUtils.bloquearInterfaz();
								              },
								              complete: function() {
								            	  Ad74aUtils.desBloquearInterfaz();
								            	  $('#dialogConfirm').rup_dialog('close');
								              },
								              success: function (data){
								              	  $('#rup_feedback_maestromotanulacion').rup_feedback("option", "delay", null);
								              	  $('#rup_feedback_maestromotanulacion').rup_feedback("set", $.rup.i18n.app.feedback.eliminadoOk, "ok");
								              	  $('#maestromotanulacion').rup_table("reload");
								              },
								              error: function(error){ 
								                  alert("error")
								              }
								        });
						            }
						        }
					        ]
						);
					}		
			};
			customButons.push(eliminarButton);
			
			return customButons;
		};

		$("#maestromotanulacion").rup_table({
			colReorder: {
				fixedColumnsLeft: 1
			},
			colModel: getColumnsModel(),
			columnDefs: getColumnsDefs(),
			primaryKey: "idMotivoAnul57",
	     	filter:{
	  	  		id:"maestromotanulacion_filter_form",
	  	  		filterToolbar:"maestromotanulacion_filter_toolbar",
	  	  		collapsableLayerId:"maestromotanulacion_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"]]
		});
		
	}
	
});
