Formulario Libre JS 2.0.N

De FlexiPymeDocs
Ir a la navegación Ir a la búsqueda

Formulario Libre JS

Código de Referencia

$(document).ready(function () {

  	apiServidor.CargarFormulario();
  
  	$('body').on('keydown', 'input, select', function(e) {
        if (e.key === "Enter") {
            var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
            focusable = form.find('input,a,select,button,textarea').filter(':visible');
            next = focusable.eq(focusable.index(this)+1);
            if (next.length) {
                next.focus();
              	next.select();
            } else {
                form.submit();
            }
            return false;
        }
    });
  
  	
  
  	$("#PaginaDL").change(function() {
      	
      apiServidor.ListarProductos(false);
      	
    });
  
  	$("#ListarCM").click(function() {
      	
      apiServidor.ListarProductos(true);
      	
    });
  
  	$("#PublicarCM").click(function() {
      	
      if (confirm('Seguro que desea Publicar ?'))
      	apiServidor.Publicar();
      	
    });
  
  
  	$("#guardarProductoCM").click(function() {
      	
      	$('#AgregarProductoMO').modal('hide');
      
      	
      	apiServidor.AgregarImagen();
      
    });
  
  	$("#imagenFC").change(function() {
      	imagenBase64 = '';
      
      	let archivo = document.getElementById("imagenFC").files[0];
          
            //console.log(archivo);
          	
          	const reader = new FileReader();
            reader.onloadend = () => {
              
              	console.log('Base 64 Format--' + reader.result);
              
              imagenBase64 = reader.result;
              
              	/*
                imagenBase64 = reader.result
                    .replace('data:', '')
                    .replace(/^.+,/, '');
				*/
                //console.log('Base 64 String--' + imagenBase64);
              
              	//alert('terminado');
            };
            reader.readAsDataURL(archivo);
    });
  
  
  	
});

let imagenBase64 = '';

function agregarProducto(id, nombre)
{
  	$('#nombreProductoFC').text(nombre);
  	$('#idProductoFC').val(id);
	$('#AgregarProductoMO').modal();
  
  	
}

function mostrarImagen(id)
{
	$('#ImagenMO').modal();
  
  
  	var url = window.location.href.split('?')[0];

	url = url + '?codigo=frmMicrositioApi&fp_api_metodo=ObtenerImagen&fp_api_parametro_idMicrositioProducto=' + id;

  	document.getElementById('imagenIM').src = url;
  
  	
}

function quitarProducto(id)
{
	
  	if (confirm('Seguro que desea quitar el producto?'))
      apiServidor.QuitarProducto(id);
  	
}

var apiServidor = function () {

    return {
      	
      	CargarFormulario: function(){
        	var fnSuccess = function (data) {
                //alert(JSON.stringify(data));
              
              	$('#productosPublicados').html('');
              
              	html = '';
              	data.lista.forEach(rub => {
                  html = html + '<div class="row">';
                  html = html + '<fieldset class="for-panel micrositioRecuadroRubro">';
                  html = html + '<legend><strong>' + rub.nombre + '</strong></legend>';
                  
                  rub.productos.forEach(prod => {
                    html = html + '<div class="row">';
                    html = html + '<div class="col-md-1"></div>';
                    html = html + '<div class="col-md-9">' + prod.nombre + '</div>';
                    html = html + '<div class="col-md-1"><button type="button" class="btn btn-info" onclick="javascript: mostrarImagen(' + prod.id + ');">Img.</button></div>';
                    html = html + '<div class="col-md-1"><button type="button" class="btn btn-danger" onclick="javascript: quitarProducto(' + prod.id +  ');">X</button></div>';
                    html = html + '</div>';
                  });
                  
                  html = html + '</fieldset>';
                  html = html + '</div>';
                  
				});
              
              	$('#productosPublicados').append(html);
              
				$('#VersitioCM').attr("href", data.micrositioUrl);
            }

            var fnError = function (strError) {
                alert(strError);
            }
          
            flexiApi.ejecutarMetodo('frmMicrositioApi', 'CargarFormulario', [], fnSuccess, fnError);
        },
      
      	ListarProductos: function (resetearPaginador) {

            var fnSuccess = function (data) {
                //alert(JSON.stringify(data));
              	
              	$('#registros').html('');
              
              	html = '';
              	data.lista.forEach(prod => {
                  
                  html = html + '<tr>';
                  html = html + '<td class="celdaCampo">' + prod.codigo + '</td>';
                  html = html + '<td class="celdaCampo">' + prod.nombre + '</td>';
                  html = html + '<td class="celdaCampo">' + prod.codigoBarras + '</td>';
                  html = html + '<td class="celdaCampo">' + prod.unidadCompra + '</td>';
                  html = html + '<td class="celdaCampo">' + prod.stock + '</td>';
                  html = html + '<td class="celdaCampo"><a href="javascript: agregarProducto(' + prod.id + ', \'' + prod.nombre + '\');">agregar</a></td>';
                  html = html + '</tr>';
              
				});
              
              	$('#registros').append(html);
              
              	//alert(data.cantidadFilas + ' - ' + data.cantidadPaginas);
              
                // Cargar combo paginas
              	if (resetearPaginador)
                {
                	dropdown = document.getElementById('PaginaDL');
                    dropdown.length = 0;

                    for (let i = 1; i <= data.cantidadPaginas; i++) {
                      option = document.createElement('option');
                      option.text = i;
                      option.value = i;
                      dropdown.add(option);
                    }

                    dropdown.selectedIndex = 0;
                }
              
            }

            var fnError = function (strError) {
                alert(strError);
            }
          
          	
          	var PaginaDL = document.getElementById("PaginaDL");
			var pagina = 1;
          
          	if (PaginaDL.selectedIndex >= 0)
          		pagina = PaginaDL.options[PaginaDL.selectedIndex].value;

          	var texto = $("#TextoTX").val();
          
          	const queryString = window.location.search;
			const urlParams = new URLSearchParams(queryString);
          	let nwflowId = urlParams.get('nwflowId');

            flexiApi.ejecutarMetodo('frmMicrositioApi', 'ListarProductos', [{ nombre: 'texto', valor: texto }, 
                                                                           { nombre: 'pagina', valor: pagina },
                                                                          { nombre: 'nwflowId', valor: nwflowId }], 
                                    										fnSuccess, fnError);


        },
      	AgregarImagen: function ()
        {
          	
          	
        	var fnSuccess = function (data) {
              	//alert(JSON.stringify(data));
              
              	if (data.estado == 'OK')
                {
                	apiServidor.CargarFormulario();
                  
                  	alert("Producto agregado correctamente.");
                }
              	else
              		alert('Error: ' + data.mensaje);	
              
            }

            var fnError = function (strError) {
                alert(strError);
            }
          
          	let idProducto = $('#idProductoFC').val();
          	//let archivo = document.getElementById("imagenFC").files[0];
          

            //flexiApi.ejecutarMetodo('frmMicrositioApi', 'AgregarImagen', [{ nombre: 'idProducto', valor: idProducto }, 
            //                                                               { nombre: 'imagenBase64', valor: imagenBase64}], 
            //                        										fnSuccess, fnError);
  
          	
          	var url = window.location.href.split('?')[0];

            url = url + '?codigo=frmMicrositioApi&fp_api_metodo=AgregarProducto&fp_api_parametro_idProducto=' + idProducto;

            

            $.ajax({
              	type: 'POST',
                url: url,
                data: imagenBase64,
              	dataType: "json",
                cache: false,
                success: function (data) {
                    console.log("Obteniendo Resultado: " + data + "\nStatus: " + status);

                    fnSuccess(data);
                },
                
                error: function (xhr, ajaxOptions, thrownError) {
                    
                    console.log('Error: ' + xhr.responseText);

                    fnError(xhr.responseText);
                }
            });
          
        },
      
      	QuitarProducto: function (id) {

            var fnSuccess = function (data) {
                apiServidor.CargarFormulario();
            }

            var fnError = function (strError) {
                alert(strError);
            }
          
          	

            flexiApi.ejecutarMetodo('frmMicrositioApi', 'QuitarProducto', [{ nombre: 'idMicrositioProducto', valor: id }], 
                                    										fnSuccess, fnError);


        },
      	Publicar: function(){
        	var fnSuccess = function (data) {
                alert(JSON.stringify(data));
            }

            var fnError = function (strError) {
                alert(strError);
            }
          
            flexiApi.ejecutarMetodo('frmMicrositioApi', 'Publicar', [], fnSuccess, fnError);
        },
    }

}();