Vue.component('listadoPedidos', function(resolve) {
	axios.get('listadoPedidos/').then((template)=> {
		resolve({
			template: template.data,
			delimiters : [ "{[{", "}]}" ],
			data: function () {return {
				impresora: new Impresora(), 
				vacios: [undefined, null, ''], 
				perPage: 20, currentPage: 1, buscador: '', camposVista: '', totalDatos:0, mensaje: '', limiteP: 0, 
				customizacion : [
					{key:'acciones', label:'Acciones', visible:false, sortable: false},
					{key:'pedidoId', label:'N° de Pedido', visible : false, sortable: true},
					{key:'consecutivo', label:'Consecutivo', visible : false, sortable: true},
					{key:'pedidoEstado', label:'Estado', visible : false, sortable: true, tdClass:['text-center']},
					{key:'pedidoSubTotal', label:'Sub Total', visible : false, sortable: true, tdClass:['text-right']},
					{key:'pedidoValorImpuesto', label:'Impuesto', visible : false, sortable: true, tdClass:['text-right']},
					{key:'pedidoTotalDescuento', label:'Descuento', visible : false, sortable: true, tdClass:['text-right']},
					{key:'pedidoPropinaValor', label:'Propina', visible : false, sortable: true, tdClass:['text-right']},
					{key:'pedidoTotalNeto', label:'Total', visible : false, sortable: true, tdClass:['text-right']},
					{key:'pedidoValorPagado', label:'Valor Pagado', visible : false, sortable: true, tdClass:['text-right']},
					{key:'clienteIdentificacion', label:'Identificacion del Cliente', visible : false, sortable: true},
					{key:'clienteNombre', label:'Cliente', visible : false, sortable: true},
					{key:'meseroNombre', label:'Mesero', visible : false, sortable: true},
					{key:'estructuraNombre', label:'Nombre de Mesa', visible : false, sortable: true},
					{key:'estructuraCodigo', label:'Código de Mesa', visible : false, sortable: true},
					{key:'salonNombre', label:'Salón', visible : false, sortable: true},
					{key:'pedidoMetodoPago', label:'Método de Pago', visible : false, sortable: true},
					{key:'pedidoCambioPago', label:'Cambio', visible : false, sortable: true},
					{key:'comensales', label:'Comensales', visible : false, sortable: true},
					{key:'totalPromedioConsumoCase', label:'Promedio de Consumo', visible : false, sortable: true},
					{key:'pedidoObservacion', label:'Observaciones', visible : false, sortable: true},
					{key:'cuponNombre', label:'Fideliación', visible : false, sortable: true},
					{key:'creacionNombre', label:'Responsable', visible : false, sortable: true},
					
					{key:'fechaPago', label:'Fecha de Pago', visible : false, sortable: true, tdClass:['text-center']},
					{key:'fechaAnulacion', label:'Fecha de Anulación', visible : false, sortable: true, tdClass:['text-center']},
					{key:'creacionFecha', label:'Creación', visible : false, sortable: true, tdClass:['text-center']},
					{key:'modificacionFecha', label:'Modificación', visible : false, sortable: true, tdClass:['text-center']},
					
					{key:'acciones2', label:'Acciones', visible:false, sortable: false},

				], opcionesDescarga: [],
				objSucursales: [], idSucursalGestion: '', 
				objPedidos: [], dicProducto: {}, idPedidoGestion: '', objDetalleProductosPedido: [], dicPedidoDetalle: {}, nombreClienteDetalle: '', 
				consultaDetalleInformacion : false, observacionCancelacio: '', 

				tipoFiltro: 'Diario', fechaInicio:'', fechaFin: '', mes: '', ano: '', estadoPedido: '', aplicarServicioPropina:false, 
				metodoPagoFiltro: '',
				aperturarEstructura: false, cambioRecienTocado: false,  cambioRecienTocadoDivision: false, 
				customizacionDetalle : [
					{key:'descuentoBtn', label:'', visible : true, sortable: true},
					{key:'productoNombre', label:'Descripción', visible : false, sortable: true},
					{key:'productoCantidad', label:'Cat', visible : false, sortable: true},
					{key:'productoTotalImpuesto', label:'Total Impuesto', visible : true, sortable: true},
					{key:'productoPrecionTotal', label:'Total', visible : false, sortable: true},
				],  
				informePedidos: {
					totalPedidos: 0, finalizados: 0, cancelados: 0, pendientes: 0, propinas: 0, totalPropinas: 0, 
					subTotalVentas: 0, totalVentasGeneal: 0, 
				}, 

				objImpuestos: [], objConfiguracionesVentas: [], dicConfiguracionVenta : {}, 
				objDetallePago: [], seleccionarMetodoPago: '', totalPagoMedios: 0, totalPagoMediosStr: '', dicCalculado: {}, 

				subtotalStr:'', descuentoStr:'', propinoStr:'', impuestolStr: '', totalNetoStr: '', 

				numeroPersonas: '', objDivicionCuenta: [], objDivicionCuentaCopia: [], 
				dicCalculadoDivicion: { total:'', totalStr:'', posicion:'', marcador: '', }, categoriaMasestraSeleccionar: '', 
				objQuitarProductoDetalle:[],
				objOpcionesObservaciones: [], seleccionadosObservaciones: [], 
				objGeneralObservaciones: [], dicDetallePedidoDescuento: {}, 
				dicCalculadoDescuentoDetalle: { total:'', totalStr:'', posicion:'', marcador: '', },
				detalleDescuentoRealizar: 0, detalleDescuentoRealizarStr: '', 
				detalleValorDescuentoRealizar: 0, detalleValorDescuentoRealizarStr: '', 

				objCategorias:[],  objProductos: [], objProductosCopia: [], categoriaFiltro: '', 
				perPageProducto: 10, currentPageProducto: 1, buscadorProducto: '', camposVistaProducto: '', totalDatosProducto:0,
				customizacionProducto : [
					{key:'productoNombre', label:'Producto', visible : true, sortable: true},
					{key:'productoPrecioVenta', label:'Precio de Venta', visible : true, sortable: true},
					{key:'acciones', label:'Acciones', visible : true, sortable: true},
				], 

				edicionCuenta: false, objDetalleProductosPedidoCopia: [], 
				dicAgregarProducto: {
					categoriaDestino: '', categoriaId: '', categoriaNombre: '', detalleConsecutivoOrden: '', detalleDescuento: 0, detalleNota: '', 
					detalleObservacion: '', detalleValorDescuento: 0, productoCantidad: '', productoId: '', productoNombre: '', productoPrecioVenta: '', 
					productoPrecionTotal: '', referencia: '', 
				}, 

				detalleValorPrecioVentaRealizar: '', detalleValorPrecioVentaRealizarStr: '', objResponsables: [], idMeseroResponsable: '', 
				nombreCliente: '', idClientePedido: '', clienteExiste: false, metodosPagosSeleccionados: [], objPedidosRespaldo: [], 
				tituloModalDividirCuenta: '', totalComensales: 0, promedioConsumoComensales: 0, enviarFacturasAlma: false, hayPedidosSeleccionados: false, 
				subtotalDividirFactura: 0, totalImpuestoDividirFactura: 0, subtotalSinImpuestoDividirFactura: 0, totalNetoDividirFactura: 0, 
				totalServicioDividirFactura: 0, porcentajeServicioDividirFactura: 0, totalAPagarDividirFactura: 0, impuestoIncluidoDividirFactura: 0, 
				descuentoDividirFactura: 0, totalDescuentoDividirFactura: 0, subtotalSinDescuentoDividirFactura: 0, totalProductosSeleccionados: 0, 
				ajustarPedidoPrincipal: false, modoDividirFacturaPedido: false, recargarPedido: false, totalCantidadItemProductos: 0, 
				detalleCantidadRealizar: 0, hayProductosSeleccionados: false, vistaListadoPedidoPrincipal: false, buscadorPedido: '', 

				objPedidos: [], buscadorPedido: '', perPagePedido: 10, currentPagePedido: 1, camposVistaPedido: '', totalDatosPedido:0,
				filtroEstadoPedido:'', objPedidosCopia: [], tituloModal: '', objPedidosDetalle: [], 
				customizacionPedido : [
					{key:'acciones', label:'Acciones', visible:true, sortable: false},
					{key:'pedidoId', label:'N° de Pedido', visible : true, sortable: true, tdClass:['text-center']},
					{key:'consecutivo', label:'Consecutivo', visible : true, sortable: true, tdClass:['text-center']},
					{key:'pedidoEstado', label:'Estado', visible : true, sortable: true, tdClass:['text-center']},
					{key:'pedidoCantidad', label:'Cantidad', visible : true, sortable: true, tdClass:['text-center']},
					{key:'pedidoPrecioTotal', label:'Precio Total', visible : true, sortable: true, tdClass:['text-center']},
					{key:'clienteResponsable', label:'Cliente', visible : true, sortable: true},
					{key:'meseroNombre', label:'Mesero', visible : true, sortable: true},
					{key:'estructuraNombre', label:'Estructura', visible : true, sortable: true, tdClass:['text-center']},
					{key:'salonNombre', label:'Salon', visible : true, sortable: true},
					{key:'sucursalNombre', label:'Sucursal', visible : true, sortable: true},
					{key:'creacionFecha', label:'Creación', visible : true, sortable: true, tdClass:['text-center']},
				], 
				resumenPedido: {}, detalleMetodos: [], objDetalleProductosContendo: [], emailVerificacion: '', mensajeVerificacion: '', tokenVerificacion: '', 
				codigoVerificacion : '', tipoToken: '', idTipoAnulacion: '', objTiposAnulaciones : [], objCupones: [], idFidelizacion: [], 
				idFidelizacionFiltro:'', modificarFacturaPagada: false, 
				
				anuladosinformeImpresion: [], resumenMetodosPagosPropina: [], reporteImpresionCierre: [], nombreSedeImpresion: "", 
				fechaReporte: "", resumenPedidosImpresion: [], reporteMeserosImpresion: [], reporteAnulacionesMesero: [], objPedidosCierre: [], 
				informePedidosCierre: {}, reporteMeserosImpresionVentas: [], objUsuariosCierre: [], idUsuarioCierre:"", 
				activarCambioCliente : false, 

				tipoFiltroCierre: "Diario", fechaInicioCierre:"", fechaFinCierre: "", mesCierre: "", anoCierre: "", idSucursalGestionCierre: "", 
				objHistorialCierres: [], listaIdsHistorialesCierre: [], idHistorialCierre: '', tituloInformeVentasCierre: "", paraGeneracionCierre: false, 
				dicHistorialCierre: {}, mostrarInputsDetalleImpuestos: false, objDetalleImpuestosProducto: [], reporteDetalleImpuestos: [], 

				camposVistaResumenCierre: [], customizacionResumenCierre : [
					{key:'detalleVentas', label:'DETALLE DE VENTAS', visible : false},
					{key:'totales', label:'TOTALES', visible : false},
					{key:'resumenImpuestos', label:'RESUMEN DE IMPUESTOS', visible : false},
					{key:'resumenVentas', label:'RESUMEN DE VENTAS', visible : false},
					{key:'cantidadesEstado', label:'CANTIDADES POR ESTADO', visible : false},
					{key:'ventasMesero', label:'VENTAS POR MESERO', visible : false},
					{key:'reportePropinaMetodoPago', label:'REPORTE DE PROPINA POR METODOS DE PAGOS', visible : false},
					{key:'reeporteAnulaciones', label:'REPORTE ANULACIONES', visible : false},
				], 
			}}, 

			computed:{
				visibleCustomizacion() { return app.customizacion.filter(field => field.visible) }, 
				visibleCustomizacionDetallePedido(){ return this.customizacionDetalle.filter(field => field.visible) }, 
				visibleCustomizacionProductos(){ return this.customizacionProducto.filter(field => field.visible) }, 
				visibleCustomizacionPedido(){ return this.customizacionPedido.filter(field => field.visible) }, 
			}, 

			methods:{
				showModal( ventana ){ this.$refs[ventana].show(); },
				hideModal( ventana ){ this.$refs[ventana].hide(); },

				cargarVistaResumenCierre( nombre ) {
					this.camposVistaResumenCierre = []; 
					axios.post( "/Principal/cargarVista", 'nombre=' + nombre ).then((result) => {
						if ( result.data[0]["campos"]!='' ){
							this.camposVistaResumenCierre = result.data[0]["campos"].split(",");
							var temporal = this.camposVistaResumenCierre; 
							for ( var i = 0; i < this.customizacionResumenCierre.length; i++ ){
								if ( temporal.includes(this.customizacionResumenCierre[i]['key']) ){
									this.customizacionResumenCierre[i]['visible'] = true;
								}
							}
						}
					});
				}, 

				guardarVistaResumenCierre ( nombre, id ){
					this.camposVistaResumenCierre = alasql("select column key from ? where visible=true", [this.customizacionResumenCierre]);
					axios.post( "/Principal/guardarVista", 'campos='+this.camposVistaResumenCierre+'&&id='+id).then((result) => {
						console.log("Dato Guardado");						
					});
				},

				cargarDatosSeccion(){
					app.cargarVista('listadoPedidos');
					this.cargarVista('listadoDetallePedido');
					this.gestionarTipoFiltroFecha( '' );
					this.listadoImpuestos();
					this.listadoSucursales();
					this.listadoCategorias();
					this.listadoResponsables();
					this.listadoTiposAnulacionesSimple();
					this.listadoCuponesSimple();
					this.listadoResponsablesCierre();
				},

				gestionarTipoFiltroFecha( accion ){
					var fecha = app.fechaActual.split("-");
					if ( this.tipoFiltro == 'Diario' ){ this.fechaInicio = app.fechaActual; }
					if ( this.tipoFiltro == 'Mensual' ){ this.mes = fecha[0] + '-' + fecha[1]; }
					if ( this.tipoFiltro == 'Anual' ){ this.ano = fecha[0]; }
					if ( this.tipoFiltro == 'Rango' ){ this.fechaInicio = app.fechaActual; this.fechaFin = app.fechaActual; }

					if ( accion == 'actualizar' ){ this.listadoPedidos(); }
				}, 

				listadoResponsables () {
					axios.post( "/Estructura/listadoResponsables", ).then((result) => {
						this.objResponsables = result.data["responsables"];
					}).catch( error => app.erroServidor( '' ) );
				}, 

				listadoTiposAnulacionesSimple () {
					axios.post( "/Estructura/listadoTiposAnulacionesSimple", ).then((result) => {
						this.objTiposAnulaciones = result.data["tiposAnulaciones"];
					}).catch( error => app.erroServidor( '' ) );
				}, 

				listadoCuponesSimple () {
					axios.post( "/Estructura/listadoCuponesSimple", ).then((result) => {
						this.objCupones = result.data["copones"];
					}).catch( error => app.erroServidor( '' ) );
				}, 

				listadoPedidos () {
					app.loading = true; 
					if (this.enviarFacturasAlma){
						this.customizacion.splice(0, 1); 
					}
					this.enviarFacturasAlma = false; this.currentPage = 1; this.hayPedidosSeleccionados = false; 
					this.objPedidos = []; this.objPedidosRespaldo = []; 

					if ( this.tipoFiltro == 'Rango' && this.fechaInicio > this.fechaFin ){ this.fechaFin = JSON.parse( JSON.stringify( this.fechaInicio ) ); }
					axios.post( "/Estructura/listadoPedidos", 
						"sucursal=" + this.idSucursalGestion +
						"&&metodoPago=" + this.metodoPagoFiltro +
						"&&mesero=" + this.idMeseroResponsable +
						"&&cupon=" + this.idFidelizacionFiltro +
						"&&estado=" + this.estadoPedido +
						"&&tipoFiltro=" + this.tipoFiltro +
						"&&fechaFin=" + this.fechaFin +
						"&&mes=" + this.mes +
						"&&ano=" + this.ano +
						"&&fecha=" + this.fechaInicio,
					).then((result) => {
						this.objPedidos = result.data["pedidos"];
						this.objPedidosRespaldo = result.data["pedidos"];
						this.totalDatos = this.objPedidos.length;

						this.configuracionesVentasSucursal();
						this.filtrarDatosPedidosReporte();
						app.loading = false;
					}).catch( error => {
						console.log("error ", error);
						app.erroServidor( '' );
					});
				}, 

				gestionarEnvioFacturasAlma(){
					this.enviarFacturasAlma = this.enviarFacturasAlma ? false : true; this.hayPedidosSeleccionados = false; 
					if (this.enviarFacturasAlma){
						this.customizacion.unshift( {key:'seleccionar', label:'', visible : true, sortable: false} );

						this.objPedidos = alasql("select * from ? where pedidoFacturacionEstado=false and consecutivo>0 and pedidoEstado in ('Anulado', 'Pagado')", [this.objPedidosRespaldo]); 
					}else{
						this.customizacion.splice(0, 1); 
						this.objPedidos = JSON.parse(JSON.stringify(this.objPedidosRespaldo)); 
					}
					this.totalDatos = this.objPedidos.length;
					this.currentPage = 1;
				}, 

				validarPedidosSeleccionadosEnviarFacturasAlma(){
					var resultado = alasql("select * from ? where seleccionar=true", [this.objPedidos]); 
					this.hayPedidosSeleccionados = resultado.length>0 ? true : false;  
				}, 

				confirmarEnviarFacturasAlma(){
					Swal.fire({
						title: '¿Enviar Facturas?', type: 'warning', showCancelButton: true, allowOutsideClick: false,
						confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
					}).then((result) => {
						if (result.value) {
							this.generarEnvioFacturasAlma();
						}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
					});
				},

				generarEnvioFacturasAlma(){
					var resultado = alasql("select column pedidoId from ? where seleccionar=true", [this.objPedidos]); 

					axios.post( "/Principal/generarEnvioFacturasAlma", 
						"sucursal=" + this.idSucursalGestion +
						"&&pedidos=" + resultado + 
						"&&usuario=" + app.usuarioActual.usuario, 
					).then((result) => {
						if (result.data.mensaje=='consumo_iniciado'){
							Swal.fire( { title:'¡Facturas Enviadas!', type:'success', showConfirmButton: false, timer:2000 } );
							this.enviarFacturasAlma = false; this.currentPage = 1; this.hayPedidosSeleccionados = false; 
							this.customizacion.splice(0, 1); 
							this.listadoPedidos();
						}else{
							Swal.fire( { title:'Hay Cierre Activo!', type:'success', showConfirmButton: false, timer:2000 } );
							app.loading = false;
						}

					}).catch( error => {
						console.log("error ", error);
						app.erroServidor( '' );
					});
				}, 

				iniciarEnvioFacturasCierre(){
					Swal.fire({
						title: '¿Enviar Cierre?', type: 'warning', showCancelButton: true, allowOutsideClick: false,
						confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
					}).then((result) => {
						if (result.value) {
							this.iniciarEnvioFacturasCierreEnviar();
						}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
					});
				},
				
				confirmarIniciarConsumoCierreFacturas(){
					Swal.fire({
						title: '¿Enviar Cierre?', type: 'warning', showCancelButton: true, allowOutsideClick: false,
						confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
					}).then((result) => {
						if (result.value) {
							this.iniciarConsumoCierreFacturas();
						}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
					});
				},

				iniciarEnvioFacturasCierreEnviar () {
					app.loading = true;

					axios.post( 
						"/Principal/iniciarEnvioFacturasCierre", 
						"&&usuario=" + app.usuarioActual.usuario, 
					).then((result) => {
						Swal.fire( { title:'¡Registro Exitoso!', type:'success', showConfirmButton: false, timer:2000 } );
						app.loading = false;
					}).catch( error => {
						console.log("error ", error);
						app.erroServidor( '' );
					});
				}, 
				
				iniciarConsumoCierreFacturas () {
					app.loading = true;
					this.hideModal("modalResumenVentasCierre"); 
					axios.post( "/Principal/iniciarConsumoCierreFacturas", 
						"sucursal=" + this.idSucursalGestion +
						"&&usuario=" + app.usuarioActual.usuario, 
					).then((result) => {
						if (result.data.mensaje=='consumo_iniciado'){
							Swal.fire( { title:'¡Cierre Enviado!', type:'success', showConfirmButton: false, timer:2000 } );
						}else{
							Swal.fire( { title:'Hay Cierre Activo!', type:'success', showConfirmButton: false, timer:2000 } );
						}
						app.loading = false;
					}).catch( error => {
						console.log("error ", error);
						this.showModal("modalResumenVentasCierre"); 
						app.erroServidor( '' );
					});
				}, 

				generarInformeReporteVentasCierre (paraGeneracionCierre) {
					app.loading = true;

					if ( this.tipoFiltro == 'Rango' && this.fechaInicio > this.fechaFin ){ this.fechaFin = JSON.parse( JSON.stringify( this.fechaInicio ) ); }
					axios.post( "/Estructura/generarInformeReporteVentasCierre", 
						"sucursal=" + this.idSucursalGestion +
						"&&estado=" + this.estadoPedido +
						"&&paraGeneracionCierre=" + paraGeneracionCierre +
						"&&tipoFiltro=" + this.tipoFiltro +
						"&&fechaFin=" + this.fechaFin +
						"&&mes=" + this.mes +
						"&&ano=" + this.ano +
						"&&fecha=" + this.fechaInicio,
					).then((result) => {
						this.resumenPedido = result.data["resumenPedido"];
						this.detalleMetodos = result.data["detalleMetodos"];

						this.showModal("modalResumenVentasCierre"); 
						app.loading = false;
					}).catch( error => {
						console.log("error ", error);
						app.erroServidor( '' );
					});
				}, 

				abrirModalGestionarGenerarInformeReporteVentas(){
					this.idSucursalGestionCierre = JSON.parse(JSON.stringify(this.idSucursalGestion)); 
					this.tipoFiltroCierre = "Diario"; this.idHistorialCierre = ""; 
					this.fechaInicioCierre = JSON.parse(JSON.stringify(app.fechaActual)); ; 
					this.fechaFinCierre = ""; this.mesCierre = ""; this.anoCierre = ""; 
					this.objHistorialCierres = []; this.listaIdsHistorialesCierre = []; 
					this.paraGeneracionCierre = false; this.dicHistorialCierre = {}; 

					this.cargarVistaResumenCierre("vistaResumenCierre"); 
					this.listadoHistorialesCierres(); 
				}, 

				gestionarTipoFiltroFechaCierre( accion ){
					this.idHistorialCierre = ""; this.dicHistorialCierre = {}; 
					var fecha = app.fechaActual.split("-");
					if ( this.tipoFiltroCierre == 'Diario' ){ this.fechaInicioCierre = app.fechaActual; }
					if ( this.tipoFiltroCierre == 'Mensual' ){ this.mesCierre = fecha[0] + '-' + fecha[1]; }
					if ( this.tipoFiltroCierre == 'Anual' ){ this.anoCierre = fecha[0]; }
					if ( this.tipoFiltroCierre == 'Rango' ){ this.fechaInicioCierre = app.fechaActual; this.fechaFinCierre = app.fechaActual; }

					this.listadoHistorialesCierres(); 
				}, 

				listadoHistorialesCierres(){
					app.loading = true; this.objHistorialCierres = []; this.listaIdsHistorialesCierre = []; this.idHistorialCierre = ""; 

					this.resumenMetodosPagosPropina = []; this.anuladosinformeImpresion = []; this.reporteImpresionCierre = []; 
					this.objPedidosCierre = []; this.informePedidosCierre = {}; this.reporteMeserosImpresionVentas = []; 
					this.resumenPedidosImpresion = []; this.reporteMeserosImpresion = []; this.reporteAnulacionesMesero = []; 

					if ( this.tipoFiltroCierre == 'Rango' && this.fechaInicioCierre>this.fechaFinCierre ){ this.fechaFinCierre=JSON.parse(JSON.stringify(this.fechaInicioCierre)); }
					axios.post( "/Principal/listadoHistorialesCierres", 
						"sucursal=" + this.idSucursalGestion + 
						"&&usuario=" + this.idUsuarioCierre + 
						"&&tipoFiltro=" + this.tipoFiltroCierre +
						"&&fechaFin=" + this.fechaFinCierre +
						"&&mes=" + this.mesCierre +
						"&&ano=" + this.anoCierre +
						"&&fecha=" + this.fechaInicioCierre,
					).then((result) => {
						this.objHistorialCierres = result.data["historialesCierres"];
						if (this.objHistorialCierres.length>0){
							this.gestionarVerResumenVentasHistorialCierres(); 
							this.generarInformeReporteVentas(0); 
						}else{
							this.showModal("modalResumenImpresionCierre"); 
							app.loading = false;
						}
					}).catch( error => {
						console.log("error ", error);
						app.erroServidor( '' );
					});
				}, 

				listadoResponsablesCierre(){
					this.objUsuariosCierre = []; 

					axios.post( "/Estructura/listadoResponsablesCierre" ).then((result) => {
						this.objUsuariosCierre = result.data["usuarios"];
					}).catch( error => {
						console.log("error ", error);
					});
				},

				gestionarVerResumenVentasHistorialCierres(){
					this.tituloInformeVentasCierre = ""; this.dicHistorialCierre = {}; 
					if (this.idHistorialCierre==""){
						this.listaIdsHistorialesCierre = alasql("select column id from ?", [this.objHistorialCierres]); 
						var fin = this.objHistorialCierres[0]; 
						var inicio = this.objHistorialCierres[this.objHistorialCierres.length-1]; 
						this.tituloInformeVentasCierre = "INFORME GENERAL DE CIERRE"; 
						this.dicHistorialCierre = {
							fechaInicio: inicio.fechaInicio + " " + inicio.horaInicio.substr(0,5), 
							fechaFin: fin.fechaFin + " " + fin.horaFin.substr(0,5), 
							responsableNombre: "", 
						}; 
						this.generarInformeReporteVentas(0); 
					}else{
						this.listaIdsHistorialesCierre = [this.idHistorialCierre]; 
						var inicio = alasql("select * from ? where id="+this.idHistorialCierre, [this.objHistorialCierres])[0]; 
						this.tituloInformeVentasCierre = "INFORME DE CIERRE N° " + inicio.codigo; 
						this.dicHistorialCierre = {
							fechaInicio: inicio.fechaInicio + " " + inicio.horaInicio.substr(0,5), 
							fechaFin: inicio.fechaFin + " " + inicio.horaFin.substr(0,5), 
							responsableNombre: inicio.responsableNombre + " " + inicio.responsableApellido, 
						}; 
						this.generarInformeReporteVentas(0); 
					}
				}, 

				imprimirInformeCierreReporteVentas(paraGeneracionCierre){
					this.tituloInformeVentasCierre = ""; this.idHistorialCierre = ""; this.objHistorialCierres = []; 
					this.listaIdsHistorialesCierre = []; this.dicHistorialCierre = {}; 
					this.paraGeneracionCierre = true; 

					this.idSucursalGestionCierre = JSON.parse(JSON.stringify(this.idSucursalGestion)); 
					this.tipoFiltroCierre = JSON.parse(JSON.stringify(this.tipoFiltro)); 
					this.fechaInicioCierre = JSON.parse(JSON.stringify(this.fechaInicio)); 
					this.fechaFinCierre = JSON.parse(JSON.stringify(this.fechaFin)); 
					this.mesCierre = JSON.parse(JSON.stringify(this.mes)); 
					this.anoCierre = JSON.parse(JSON.stringify(this.ano)); 
					this.generarInformeReporteVentas(paraGeneracionCierre); 
				}, 

				generarInformeReporteVentas (paraGeneracionCierre) {
					app.loading = true; this.resumenMetodosPagosPropina = []; this.anuladosinformeImpresion = []; this.reporteImpresionCierre = []; 
					this.objPedidosCierre = []; this.informePedidosCierre = {}; this.reporteMeserosImpresionVentas = []; this.reporteDetalleImpuestos = []; 

					if ( this.tipoFiltroCierre == 'Rango' && this.fechaInicioCierre>this.fechaFinCierre ){ this.fechaFinCierre=JSON.parse(JSON.stringify(this.fechaInicioCierre)); }
					var listaIdsHistorialesCierre = this.listaIdsHistorialesCierre.length>0 ? this.listaIdsHistorialesCierre : ""; 
					axios.post( "/Estructura/generarInformeReporteVentas", 
						"sucursal=" + this.idSucursalGestion + 
						"&&estado=" + this.estadoPedido + 
						"&&paraGeneracionCierre=" + paraGeneracionCierre + 
						"&&listaIdsHistorialesCierre=" + listaIdsHistorialesCierre + 
						
						"&&tipoFiltro=" + this.tipoFiltroCierre +
						"&&fechaFin=" + this.fechaFinCierre +
						"&&mes=" + this.mesCierre +
						"&&ano=" + this.anoCierre +
						"&&fecha=" + this.fechaInicioCierre,
					).then((result) => {
						this.objPedidosCierre = result.data["pedidosCierre"];
						this.reporteImpresionCierre = result.data["reporte"];
						this.anuladosinformeImpresion = result.data["anulados"];
						this.resumenMetodosPagosPropina = result.data["resumenMetodosPagos"];
						this.reporteDetalleImpuestos = result.data["detalleImpuestos"];
						
						if(this.paraGeneracionCierre){
							this.dicHistorialCierre = result.data["historialCierre"];
							this.tituloInformeVentasCierre = "INFORME DE CIERRE N°" + this.dicHistorialCierre.codigo; 
						}

						/* this.imprimirReporte( '' ); */
						this.filtrarDatosPedidosReporteCierre();
						this.verResumenImpresionCierre();
						app.loading = false;
					}).catch( error => {
						console.log("error ", error);
						app.erroServidor( '' );
					});
				}, 

				descargarReportePdf (){
					this.ocultarDatosDescargarPdf = true; 
					setTimeout(()=>{
						var opt = {
							margin:2,
							filename: 'reporteVentas.pdf',
							jsPDF: { format: 'letter' }
						}; 
						var elemento = document.getElementById("reporteResumenCierreImpresion"); 
						html2pdf(elemento, opt); 
						this.hideModal("modalResumenImpresionCierre"); 
					}, 500); 
				}, 

				filtrarDatosPedidosReporte(){
					var totalPedidos = this.objPedidos.length;
					var finalizados = alasql("select column pedidoId from ? where pedidoEstado='Finalizado'", [ this.objPedidos ] ).length;
					var pagados = alasql("select column pedidoId from ? where pedidoEstado='Pagado'", [ this.objPedidos ] ).length;
					var anulados = alasql("select column pedidoId from ? where pedidoEstado='Anulado'", [ this.objPedidos ] ).length;
					var cancelados = alasql("select column pedidoId from ? where pedidoEstado='Cancelado'", [ this.objPedidos ] ).length;
					var pendientes = alasql("select column pedidoId from ? where pedidoEstado='Pendiente'", [ this.objPedidos ] ).length;
					
					var totalPropinas = alasql("select column pedidoId from ? where pedidoEstado='Pagado' and pedidoPropinaValor>0", [ this.objPedidos ] ).length;
					var propinas = alasql("select SUM( pedidoPropinaValor ) as totalSuma from ? where pedidoEstado='Pagado' and pedidoPropinaValor>0", [ this.objPedidos ] )[0].totalSuma;

					var totalIva = alasql("select SUM( pedidoValorImpuesto ) as totalSuma from ? where pedidoEstado='Pagado'", [ this.objPedidos ] )[0].totalSuma;
					var subTotalVentas = alasql("select SUM( pedidoSubTotal ) as totalSuma from ? where pedidoEstado='Pagado'", [ this.objPedidos ] )[0].totalSuma;
					var descuento = alasql("select SUM( pedidoTotalDescuento ) as totalSuma from ? where pedidoEstado='Pagado'", [ this.objPedidos ] )[0].totalSuma;
					var totalVentasGeneal = alasql("select SUM( pedidoTotalNeto ) as totalSuma from ? where pedidoEstado='Pagado'", [ this.objPedidos ] )[0].totalSuma;					
					var totalPromedioConsumo = alasql("select SUM( totalPromedioConsumoCase ) as totalSuma from ? where pedidoEstado='Pagado'", [ this.objPedidos ] )[0].totalSuma;					
					
					var totalEfectivo = alasql("select SUM( pedidoTotalNeto ) as totalSuma from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Efectivo'", [ this.objPedidos ] )[0].totalSuma;					
					var cantidadEfectivo = alasql("select * from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Efectivo'", [ this.objPedidos ] ).length;
					var totalTarjeta = alasql("select SUM( pedidoTotalNeto ) as totalSuma from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Tarjeta'", [ this.objPedidos ] )[0].totalSuma;					
					var cantidadTarjeta = alasql("select * from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Tarjeta'", [ this.objPedidos ] ).length;
					var totalTransferencia = alasql("select SUM( pedidoTotalNeto ) as totalSuma from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Transferencia'", [ this.objPedidos ] )[0].totalSuma;					
					var cantidadTransferencia = alasql("select * from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Transferencia'", [ this.objPedidos ] ).length;
					var totalMixto = alasql("select SUM( pedidoTotalNeto ) as totalSuma from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Mixto'", [ this.objPedidos ] )[0].totalSuma;					
					var cantidadMixto = alasql("select * from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Mixto'", [ this.objPedidos ] ).length;

					this.informePedidos = {
						totalPedidos: totalPedidos, 
						pagados: pagados, 
						anulados: anulados, 
						finalizados: finalizados, 
						cancelados: cancelados, 
						pendientes: pendientes, 
						propinas: propinas, 
						descuento: descuento, 
						totalIva: totalIva, 
						totalPropinas: totalPropinas, 
						subTotalVentas: subTotalVentas, 
						totalVentasGeneal: totalVentasGeneal, 
						totalPromedioConsumo: totalPromedioConsumo, 
						
						totalEfectivo: totalEfectivo, 
						cantidadEfectivo: cantidadEfectivo, 
						totalTarjeta: totalTarjeta, 
						cantidadTarjeta: cantidadTarjeta, 
						totalTransferencia: totalTransferencia, 
						cantidadTransferencia: cantidadTransferencia, 
						totalMixto: totalMixto, 
						cantidadMixto: cantidadMixto, 
					};
				},

				filtrarDatosPedidosReporteCierre(){
					var totalPedidos = this.objPedidosCierre.length;
					var finalizados = alasql("select column pedidoId from ? where pedidoEstado='Finalizado'", [ this.objPedidosCierre ] ).length;
					var pagados = alasql("select column pedidoId from ? where pedidoEstado='Pagado'", [ this.objPedidosCierre ] ).length;
					var anulados = alasql("select column pedidoId from ? where pedidoEstado='Anulado'", [ this.objPedidosCierre ] ).length;
					var cancelados = alasql("select column pedidoId from ? where pedidoEstado='Cancelado'", [ this.objPedidosCierre ] ).length;
					var pendientes = alasql("select column pedidoId from ? where pedidoEstado='Pendiente'", [ this.objPedidosCierre ] ).length;
					
					var totalPropinas = alasql("select column pedidoId from ? where pedidoEstado='Pagado' and pedidoPropinaValor>0", [ this.objPedidosCierre ] ).length;
					var propinas = alasql("select SUM( pedidoPropinaValor ) as totalSuma from ? where pedidoEstado='Pagado' and pedidoPropinaValor>0", [ this.objPedidosCierre ] )[0].totalSuma;

					var totalIva = alasql("select SUM( pedidoValorImpuesto ) as totalSuma from ? where pedidoEstado='Pagado'", [ this.objPedidosCierre ] )[0].totalSuma;
					var subTotalVentas = alasql("select SUM( pedidoSubTotal ) as totalSuma from ? where pedidoEstado='Pagado'", [ this.objPedidosCierre ] )[0].totalSuma;
					var descuento = alasql("select SUM( pedidoTotalDescuento ) as totalSuma from ? where pedidoEstado='Pagado'", [ this.objPedidosCierre ] )[0].totalSuma;
					var totalVentasGeneal = alasql("select SUM( pedidoTotalNeto ) as totalSuma from ? where pedidoEstado='Pagado'", [ this.objPedidosCierre ] )[0].totalSuma;					
					var totalPromedioConsumo = alasql("select SUM( totalPromedioConsumoCase ) as totalSuma from ? where pedidoEstado='Pagado'", [ this.objPedidosCierre ] )[0].totalSuma;					
					
					var totalEfectivo = alasql("select SUM( pedidoTotalNeto ) as totalSuma from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Efectivo'", [ this.objPedidosCierre ] )[0].totalSuma;					
					var cantidadEfectivo = alasql("select * from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Efectivo'", [ this.objPedidosCierre ] ).length;
					var totalTarjeta = alasql("select SUM( pedidoTotalNeto ) as totalSuma from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Tarjeta'", [ this.objPedidosCierre ] )[0].totalSuma;					
					var cantidadTarjeta = alasql("select * from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Tarjeta'", [ this.objPedidosCierre ] ).length;
					var totalTransferencia = alasql("select SUM( pedidoTotalNeto ) as totalSuma from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Transferencia'", [ this.objPedidosCierre ] )[0].totalSuma;					
					var cantidadTransferencia = alasql("select * from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Transferencia'", [ this.objPedidosCierre ] ).length;
					var totalMixto = alasql("select SUM( pedidoTotalNeto ) as totalSuma from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Mixto'", [ this.objPedidosCierre ] )[0].totalSuma;					
					var cantidadMixto = alasql("select * from ? where pedidoEstado='Pagado' and pedidoMetodoPago='Mixto'", [ this.objPedidosCierre ] ).length;

					this.informePedidosCierre = {
						totalPedidos: totalPedidos, 
						pagados: pagados, 
						anulados: anulados, 
						finalizados: finalizados, 
						cancelados: cancelados, 
						pendientes: pendientes, 
						propinas: propinas, 
						descuento: descuento, 
						totalIva: totalIva, 
						totalPropinas: totalPropinas, 
						subTotalVentas: subTotalVentas, 
						totalVentasGeneal: totalVentasGeneal, 
						totalPromedioConsumo: totalPromedioConsumo, 
						
						totalEfectivo: totalEfectivo, 
						cantidadEfectivo: cantidadEfectivo, 
						totalTarjeta: totalTarjeta, 
						cantidadTarjeta: cantidadTarjeta, 
						totalTransferencia: totalTransferencia, 
						cantidadTransferencia: cantidadTransferencia, 
						totalMixto: totalMixto, 
						cantidadMixto: cantidadMixto, 
					};
				},

				verResumenImpresionCierre(){
					var sede  = alasql("select * from ? where id =" + parseInt( this.idSucursalGestion ), [ this.objSucursales ]);
					this.nombreSedeImpresion = sede[0].nombre;

					this.resumenPedidosImpresion = alasql("select * from ?", [ this.objPedidosCierre ] );
					
					if ( this.tipoFiltro == 'Diario' ){ this.fechaReporte = this.fechaInicio; }
					if ( this.tipoFiltro == 'Mensual' ){ this.fechaReporte = this.mes; }
					if ( this.tipoFiltro == 'Anual' ){ this.fechaReporte = this.ano; }
					if ( this.tipoFiltro == 'Rango' ){ this.fechaReporte = this.fechaInicio + " a " + this.fechaFin; }

					var meserosIds = alasql("select column meseroId from ? where pedidoEstado='Pagado'", [this.objPedidosCierre]); 
					this.reporteMeserosImpresion = []; meserosIds = [...new Set(meserosIds)];
					meserosIds.forEach((elemento)=>{
						if (!app.vacios.includes(elemento)){
							var pedidosMesero = alasql("select * from ? where pedidoEstado='Pagado' and meseroId="+elemento, [this.objPedidosCierre]); 
							var totalPedidosMesero = alasql("select * from ? where meseroId="+elemento, [this.objPedidosCierre]).length; 
							var nameMesero = pedidosMesero[0].meseroNombre + " " + pedidosMesero[0].meseroApellido;  
							var totalPropinasMesero = alasql("select SUM( pedidoPropinaValor ) as totalSuma from ? where pedidoPropinaValor>0", [pedidosMesero] )[0].totalSuma;
							this.reporteMeserosImpresion.push({
								nameMesero:nameMesero, totalPropinasMesero:totalPropinasMesero, 
								pedidosMesero:totalPedidosMesero, 
							}); 
						}
					}); 

					var meserosIds = alasql("select column meseroId from ? where pedidoEstado='Pagado'", [this.objPedidosCierre]); 
					this.reporteMeserosImpresionVentas = []; meserosIds = [...new Set(meserosIds)];
					meserosIds.forEach((elemento)=>{
						if (!app.vacios.includes(elemento)){
							var pedidosMesero = alasql("select * from ? where pedidoEstado='Pagado' and meseroId="+elemento, [this.objPedidosCierre]); 
							/* var totalPedidosMesero = pedidosMesero.length;  */
							var totalPedidosMesero = alasql("select * from ? where meseroId="+elemento, [this.objPedidosCierre]).length; 
							var nameMesero = pedidosMesero[0].meseroNombre + " " + pedidosMesero[0].meseroApellido;  
							var totalGenerado = alasql("select SUM( pedidoTotalNeto ) as totalSuma from ? where pedidoTotalNeto>0", [pedidosMesero] )[0].totalSuma;
							var totalPropinasMesero = alasql("select SUM( pedidoPropinaValor ) as totalSuma from ? where pedidoPropinaValor>0", [pedidosMesero] )[0].totalSuma;
							this.reporteMeserosImpresionVentas.push({
								nameMesero:nameMesero, 
								totalGenerado:totalGenerado, 
								totalPropinasMesero:totalPropinasMesero, 
								pedidosMesero:totalPedidosMesero, 
							}); 
						}
					}); 

					var meserosIds2 = alasql("select column meseroId from ?", [this.anuladosinformeImpresion]); 
					this.reporteAnulacionesMesero = []; meserosIds2 = [...new Set(meserosIds2)];
					meserosIds2.forEach((elemento2)=>{
						if (!app.vacios.includes(elemento2)){
							var pedidosMesero2 = alasql("select * from ? where meseroId="+elemento2, [this.anuladosinformeImpresion]); 
							var nameMesero = "Sin Asignar"; 
							nameMesero = pedidosMesero2[0].meseroNombre + " " + pedidosMesero2[0].meseroApellido;  
							this.reporteAnulacionesMesero.push({nameMesero:nameMesero, pedidosMesero:pedidosMesero2, }); 
						}
					});  

					this.showModal("modalResumenImpresionCierre"); 
				}, 

				imprimirReporte(  ventana ){
					this.impresora.operaciones = [];

					this.impresora.setAlign( C.AlineacionCentro );
					this.impresora.write( "REPORTE DE VENTAS" + "\n");
					this.impresora.write( app.procesarAcentos(this.nombreSedeImpresion) + "\n");
					this.impresora.write( "INFORME: " + this.fechaReporte + "\n");
					this.impresora.write( "................................................\n");
					this.impresora.write( "DETALLE DE VENTAS" + "\n");
					this.impresora.setAlign( C.AlineacionIzquierda );
					this.impresora.write( "................................................\n");
					this.impresora.write( " Pedido       Metodo de Pago          Total  \n");
					this.impresora.write( "................................................\n");

					this.resumenPedidosImpresion.forEach( elemento => {
						this.impresora.write(" " + this.agregarEspacioCantidad(elemento.pedidoId) + "            " + 
							this.validarCaracteresEstado(app.procesarAcentos( elemento.pedidoMetodoPago )) + " " + 
							this.validarCaracteresCantidadInforme(this.moneda(elemento.pedidoTotalNeto)) + "\n");
					});

					this.impresora.write( "\n");
					this.impresora.write( "................................................\n");
					this.impresora.setAlign( C.AlineacionCentro );
					this.impresora.write( "TOTALES" + "\n");
					this.impresora.setAlign( C.AlineacionIzquierda );
					this.impresora.write( "................................................\n");
					this.impresora.write( "Subtotal:                       " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.subTotalVentas)) + "\n");
					this.impresora.write( "Impoconsumo:                    " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.totalIva)) + "\n");
					this.impresora.write( "Descuento:                      " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.descuento)) + "\n");
					this.impresora.write( "Propinas:                       " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.propinas)) + "\n");
					this.impresora.write( "Total Neto:                     " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.totalVentasGeneal)) + "\n");
					this.impresora.write( "................................................\n");
					
					if (this.reporteImpresionCierre.length>0){
						this.impresora.write( "\n");
						this.impresora.write( "................................................\n");
						this.impresora.setAlign( C.AlineacionCentro );
						this.impresora.write( "RESUMEN DE VENTAS" + "\n");
						this.impresora.setAlign( C.AlineacionIzquierda );
						this.impresora.write( "................................................\n");
						this.impresora.write( " Metodo           Cantidad            Total  \n");
						this.impresora.write( "................................................\n");
						this.reporteImpresionCierre.forEach((elemento)=>{
							this.impresora.write( this.validarCaracteresProductoDinamico(elemento.metodoName, 20) + "    " + this.validarCaracteresProductoDinamico(this.agregarEspacioCantidad(elemento.cantidad), 3) + 
								"       " + this.validarCaracteresProductoDinamico(this.moneda(elemento.total), 15) + "\n");
						});
					}

					this.impresora.write( "\n");
					this.impresora.write( "................................................\n");
					this.impresora.setAlign( C.AlineacionCentro );
					this.impresora.write( "CANTIDADES POR ESTADO" + "\n");
					this.impresora.setAlign( C.AlineacionIzquierda );
					this.impresora.write( "................................................\n");
					this.impresora.write( "Pendientes:                    " + this.procesarTotalPagarImpresionInforme(this.cantidadC(this.informePedidos.pendientes)) + "\n");
					this.impresora.write( "Finalizados:                   " + this.procesarTotalPagarImpresionInforme(this.cantidadC(this.informePedidos.finalizados)) + "\n");
					this.impresora.write( "Pagados:                       " + this.procesarTotalPagarImpresionInforme(this.cantidadC(this.informePedidos.pagados)) + "\n");
					this.impresora.write( "Anulados:                      " + this.procesarTotalPagarImpresionInforme(this.cantidadC(this.informePedidos.anulados)) + "\n");
					this.impresora.write( "Cancelados:                    " + this.procesarTotalPagarImpresionInforme(this.cantidadC(this.informePedidos.cancelados)) + "\n");

					if (this.reporteMeserosImpresion.length>0){
						this.impresora.write( "\n");
						this.impresora.write( "................................................\n");
						this.impresora.setAlign( C.AlineacionCentro );
						this.impresora.write( "REPORTE DE PROPINAS POR MESERO" + "\n");
						this.impresora.setAlign( C.AlineacionIzquierda );
						this.impresora.write( "................................................\n");
						this.impresora.write( " Mesero                         Propina  \n");
						this.impresora.write( "................................................\n");
						this.reporteMeserosImpresion.forEach((elemento)=>{
							this.impresora.write(" "+ this.validarCaracteresProductoDinamico(app.procesarAcentos(elemento.nameMesero), 29) +
							"     " + this.validarCaracteresProductoDinamicoI(this.moneda(elemento.totalPropinasMesero), 13) + "\n");
						});
					}

					if (this.resumenMetodosPagosPropina.length>0){
						this.impresora.write( "\n");
						this.impresora.write( "................................................\n");
						this.impresora.setAlign( C.AlineacionCentro );
						this.impresora.write( "REPORTE DE PROPINAS POR METODOS DE PAGOS" + "\n");
						this.impresora.setAlign( C.AlineacionIzquierda );
						this.impresora.write( "................................................\n");
						this.impresora.write( " Metodo                           Total  \n");
						this.impresora.write( "................................................\n");
						this.resumenMetodosPagosPropina.forEach((elemento)=>{
							this.impresora.write(this.validarCaracteresProductoDinamico(app.procesarAcentos(elemento.metodoName), 28) +
							"     " + this.validarCaracteresProductoDinamicoI(this.moneda(elemento.valorPagado), 15) + "\n");
						});
					}

					if (this.reporteAnulacionesMesero.length>0){
						this.impresora.write( "\n");
						this.impresora.write( "................................................\n");
						this.impresora.setAlign( C.AlineacionCentro );
						this.impresora.write( "REPORTE ANULACIONES" + "\n");
						this.impresora.setAlign( C.AlineacionIzquierda );
						this.impresora.write( "................................................\n");
						/* this.impresora.write( "123456789012345678901234567890123456789012345678\n"); */
						this.impresora.write( " Mesero           Producto         Mesa  \n");
						this.impresora.write( "................................................\n");
						this.impresora.setAlign( C.AlineacionIzquierda );
						this.reporteAnulacionesMesero.forEach((elemento2)=>{
							this.impresora.write( elemento2.nameMesero + "\n");
							elemento2.pedidosMesero.forEach((elemento3)=>{
								this.impresora.write(" "+this.validarCaracteresProductoDinamico(app.procesarAcentos(elemento3.productoNombre), 29) + 
								"     " + this.validarCaracteresProductoDinamicoI(elemento3.mesaNombre, 13) + "\n");
							});		
						});	
					}
					
					/* this.impresora.write( "\n");
					this.impresora.write( "................................................\n");
					this.impresora.setAlign( C.AlineacionCentro );
					this.impresora.write( "TOTALES" + "\n");
					this.impresora.setAlign( C.AlineacionIzquierda );
					this.impresora.write( "................................................\n");
					this.impresora.write( "Subtotal:                       " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.subTotalVentas)) + "\n");
					this.impresora.write( "Impoconsumo:                    " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.totalIva)) + "\n");
					this.impresora.write( "Descuento:                      " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.descuento)) + "\n");
					this.impresora.write( "Propinas:                       " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.propinas)) + "\n");
					this.impresora.write( "Total Neto:                     " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.totalVentasGeneal)) + "\n");
					this.impresora.write( "................................................\n"); */

					this.impresora.feed(1);
					this.impresora.cut();
					this.impresora.imprimirEnImpresora( app.globalEmpresa.impresoraFacturacion );
					if ( ventana!='' ){
						this.hideModal( ventana );
					}
				}, 

				imprimirReporteV3(  ventana ){
					var conector = new ConectorPluginV3(); 
					conector.Iniciar(); 
					conector.serial = app.globalEmpresa.licenciaPluginImpresoraV3; 
					conector.operaciones = [];
					
					conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
					if(!app.vacios.includes(this.dicConfiguracionVenta.imagenImpresion)){
						var urlImagen = window.location.origin + "/media/configuraciones/puntoventa/" + this.dicConfiguracionVenta.imagenImpresion; 
						conector.DescargarImagenDeInternetEImprimir(urlImagen, 250, 0, false); 
						conector.Feed(1); 
					}

					conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "REPORTE DE VENTAS" + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", this.nombreSedeImpresion + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "INFORME: " + this.fechaReporte + "\n");
					conector.EscribirTexto( "................................................\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "DETALLE DE VENTAS" + "\n");
					conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_IZQUIERDA); 
					conector.EscribirTexto( "................................................\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", " Pedido       Metodo de Pago          Total  \n");
					conector.EscribirTexto( "................................................\n");

					this.resumenPedidosImpresion.forEach( elemento => {
						conector.TextoSegunPaginaDeCodigos(2, "cp850"," " + this.agregarEspacioCantidad(elemento.pedidoId) + "            " + 
							this.validarCaracteresEstado(elemento.pedidoMetodoPago) + " " + 
							this.validarCaracteresCantidadInforme(this.moneda(elemento.pedidoTotalNeto)) + "\n");
					});

					conector.TextoSegunPaginaDeCodigos(2, "cp850", "\n");
					conector.EscribirTexto( "................................................\n");
					conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "TOTALES" + "\n");
					conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_IZQUIERDA); 
					conector.EscribirTexto( "................................................\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Subtotal:                       " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.subTotalVentas)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Impoconsumo:                    " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.totalIva)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Descuento:                      " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.descuento)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Propinas:                       " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.propinas)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Total Neto (Sin Propina):       " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.totalVentasGeneal-this.informePedidos.propinas)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Total Neto:                     " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.totalVentasGeneal)) + "\n");
					conector.EscribirTexto( "................................................\n");
					
					if (this.reporteImpresionCierre.length>0){
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "\n");
						conector.EscribirTexto( "................................................\n");
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "RESUMEN DE VENTAS" + "\n");
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_IZQUIERDA); 
						conector.EscribirTexto( "................................................\n");
						conector.TextoSegunPaginaDeCodigos(2, "cp850", " Metodo           Cantidad            Total  \n");
						conector.EscribirTexto( "................................................\n");
						this.reporteImpresionCierre.forEach((elemento)=>{
							conector.TextoSegunPaginaDeCodigos(2, "cp850", this.validarCaracteresProductoDinamico(elemento.metodoName, 20) + "    " + this.validarCaracteresProductoDinamico(this.agregarEspacioCantidad(elemento.cantidad), 3) + 
							"       " + this.validarCaracteresProductoDinamico(this.moneda(elemento.total), 15) + "\n");
						});
					}

					conector.TextoSegunPaginaDeCodigos(2, "cp850", "\n");
					conector.EscribirTexto( "................................................\n");
					conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "CANTIDADES POR ESTADO" + "\n");
					conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_IZQUIERDA); 
					conector.EscribirTexto( "................................................\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Pendientes:                    " + this.procesarTotalPagarImpresionInforme(this.cantidadC(this.informePedidos.pendientes)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Finalizados:                   " + this.procesarTotalPagarImpresionInforme(this.cantidadC(this.informePedidos.finalizados)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Pagados:                       " + this.procesarTotalPagarImpresionInforme(this.cantidadC(this.informePedidos.pagados)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Anulados:                      " + this.procesarTotalPagarImpresionInforme(this.cantidadC(this.informePedidos.anulados)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Cancelados:                    " + this.procesarTotalPagarImpresionInforme(this.cantidadC(this.informePedidos.cancelados)) + "\n");

					if (this.reporteMeserosImpresionVentas.length>0){
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "\n");
						conector.EscribirTexto( "................................................\n");
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "VENTAS POR MESERO" + "\n");
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_IZQUIERDA); 
						conector.EscribirTexto( "................................................\n");
						conector.TextoSegunPaginaDeCodigos(2, "cp850", " Mesero        Cantidad            Total  \n");
						conector.EscribirTexto( "................................................\n");
						this.reporteMeserosImpresionVentas.forEach((elemento)=>{
							conector.TextoSegunPaginaDeCodigos(2, "cp850"," "+ this.validarCaracteresProductoDinamico(elemento.nameMesero, 23) +
							" "+ this.validarCaracteresProductoDinamicoI(elemento.pedidosMesero, 4) +
							"     " + this.validarCaracteresProductoDinamicoI(this.moneda(elemento.totalGenerado), 13) + "\n");
						});
					}

					if (this.reporteMeserosImpresion.length>0){
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "\n");
						conector.EscribirTexto( "................................................\n");
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "REPORTE DE PROPINAS POR MESERO" + "\n");
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_IZQUIERDA); 
						conector.EscribirTexto( "................................................\n");
						conector.TextoSegunPaginaDeCodigos(2, "cp850", " Mesero                         Propina  \n");
						conector.EscribirTexto( "................................................\n");
						this.reporteMeserosImpresion.forEach((elemento)=>{
							conector.TextoSegunPaginaDeCodigos(2, "cp850"," "+ this.validarCaracteresProductoDinamico(elemento.nameMesero, 29) +
							"     " + this.validarCaracteresProductoDinamicoI(this.moneda(elemento.totalPropinasMesero), 13) + "\n");
						});
					}

					if (this.resumenMetodosPagosPropina.length>0){
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "\n");
						conector.EscribirTexto( "................................................\n");
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "REPORTE DE PROPINAS POR METODOS DE PAGOS" + "\n");
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_IZQUIERDA); 
						conector.EscribirTexto( "................................................\n");
						conector.TextoSegunPaginaDeCodigos(2, "cp850", " Metodo                           Total  \n");
						conector.EscribirTexto( "................................................\n");
						this.resumenMetodosPagosPropina.forEach((elemento)=>{
							conector.TextoSegunPaginaDeCodigos(2, "cp850",this.validarCaracteresProductoDinamico(elemento.metodoName, 28) +
							"     " + this.validarCaracteresProductoDinamicoI(this.moneda(elemento.valorPagado), 15) + "\n");
						});
					}

					if (this.reporteAnulacionesMesero.length>0){
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "\n");
						conector.EscribirTexto( "................................................\n");
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "REPORTE ANULACIONES" + "\n");
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_IZQUIERDA); 
						conector.EscribirTexto( "................................................\n");
						/* conector.TextoSegunPaginaDeCodigos(2, "cp850", "123456789012345678901234567890123456789012345678\n"); */
						conector.TextoSegunPaginaDeCodigos(2, "cp850", " Mesero           Producto         Mesa  \n");
						conector.EscribirTexto( "................................................\n");
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_IZQUIERDA); 
						this.reporteAnulacionesMesero.forEach((elemento2)=>{
							conector.TextoSegunPaginaDeCodigos(2, "cp850", elemento2.nameMesero + "\n");
							elemento2.pedidosMesero.forEach((elemento3)=>{
								conector.TextoSegunPaginaDeCodigos(2, "cp850"," "+this.validarCaracteresProductoDinamico(elemento3.productoNombre, 29) + 
								"     " + this.validarCaracteresProductoDinamicoI(elemento3.mesaNombre, 13) + "\n");
							});		
						});	
					}
					
					/* conector.TextoSegunPaginaDeCodigos(2, "cp850", "\n");
					conector.EscribirTexto( "................................................\n");
					conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "TOTALES" + "\n");
					conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_IZQUIERDA); 
					conector.EscribirTexto( "................................................\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Subtotal:                       " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.subTotalVentas)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Impoconsumo:                    " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.totalIva)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Descuento:                      " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.descuento)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Propinas:                       " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.propinas)) + "\n");
					conector.TextoSegunPaginaDeCodigos(2, "cp850", "Total Neto:                     " + this.procesarTotalPagarImpresionInforme(this.moneda(this.informePedidos.totalVentasGeneal)) + "\n");
					conector.EscribirTexto( "................................................\n"); */

					conector.Feed(1);
					conector.Corte(1);
					conector.imprimirEn( app.globalEmpresa.impresoraFacturacion );
					if ( ventana!='' ){
						this.hideModal( ventana );
					}
				}, 

				validarCaracteresProductoDinamico( valor, limete ){
					if ( String(valor).length == limete ){ return valor; }
					if ( String(valor).length < limete ){ 
						var caracteres = (limete-1) - String(valor).length;
						for ( var i = 0; i < caracteres; i++ ){ valor = valor + " "; }
						return valor;
					}
					if ( String(valor).length > limete ){ return valor.substr( 0, (limete-1) ); }
				}, 
				validarCaracteresProductoDinamicoI( valor, limete ){
					if ( String(valor).length == limete ){ return valor; }
					if ( String(valor).length < limete ){ 
						var caracteres = (limete-1) - String(valor).length;
						for ( var i = 0; i < caracteres; i++ ){ valor = " " + valor; }
						return valor;
					}
					if ( String(valor).length > limete ){ return valor.substr( 0, (limete-1) ); }
				}, 

				validarCaracteresEstado( valor ){
					if ( String(valor).length == 10 ){ return valor; }
					if ( String(valor).length < 10 ){ 
						var caracteres = 10 - String(valor).length;
						for ( var i = 0; i < caracteres; i++ ){ valor = valor + " "; }
						return valor;
					}
					if ( String(valor).length > 10 ){ return valor.substr( 0, 9 ); }
				}, 	

				validarCaracteresCantidadInforme( valor ){
					if ( String(valor).length == 20 ){ return valor; }
					if ( String(valor).length < 20 ){ 
						var caracteres = 20 - String(valor).length;
						for ( var i = 0; i < caracteres; i++ ){ valor =  " " + valor; }
						return valor;
					}
					if ( String(valor).length > 20 ){ return String(valor).substr( 0, 20 ); }
				}, 

				procesarTotalPagarImpresionInforme(valor){
					if ( String(valor).length == 15 ){ return valor; }
					if ( String(valor).length < 15 ){ 
						var caracteres = 15 - String(valor).length;
						for ( var i = 0; i < caracteres; i++ ){ valor =  " " + valor; }
						return valor;
					}
					if ( String(valor).length > 15 ){ return String(valor).substr( 0, 15 ); }
				},	

				filtrando( datos ){
					this.totalDatos = datos.length;
					this.currentPage = 1;
				},

				multibusquedaPedido( valor, filtro ){
					console.log("filtro ---", filtro);
					console.log("valor ---", valor);
					encontrados = 0;
					contador = 0;
					if( ["", undefined, null ].includes( filtro ) ){
						return true;
					}else{
					
						palabras = filtro.split(" ");
						palabras.forEach( ( elemento )=>{
							if( 
								!["", undefined, null ].includes( elemento ) && 
								app.$options.methods.filterBy( [valor], elemento ).length > 0 
							){
								encontrados += 1;
							}
							if( !["", undefined, null ].includes( elemento ) ){
								contador += 1;
							}
						});				
						return (encontrados > 0) && ( encontrados == contador );
					}
				},

				cambiarPerPage( valor ){ console.log(valor); this.perPage = valor; },

				calcularLimiteP : function(){
					this.limiteP = Math.ceil( this.opcionesDescarga.length / 2 );
				}, 

				gestionarMarcadoCamposDescarga( accion ){
					this.opcionesDescarga.forEach(( element )=>{
						element.descargar = ( accion === 1 ) ? true : false;
					});
				}, 

				abrirModalDescarga ( ventana ) {
					this.opcionesDescarga = [];
					this.opcionesDescarga.push(
						{ "clave": "pedidoId AS [N° de Pedido]", "alias": "N° de Pedido", "descargar": true, },
						{ "clave": "consecutivo AS [Consecutivo]", "alias": "Consecutivo", "descargar": true, },
						{ "clave": "pedidoEstado AS [Estado]", "alias": "Estado", "descargar": true, },
						{ "clave": "pedidoSubTotal AS [Sub Total]", "alias": "Sub Total", "descargar": true, },
						
						{ "clave": "pedidoValorImpuesto AS [Impuesto]", "alias": "Impuesto", "descargar": true, },
						{ "clave": "pedidoTotalDescuento AS [Descuento]", "alias": "Descuento", "descargar": true, },
						{ "clave": "pedidoPropinaValor AS [Propina]", "alias": "Propina", "descargar": true, },
						{ "clave": "pedidoTotalNeto AS [Total]", "alias": "Total", "descargar": true, },
						{ "clave": "pedidoValorPagado AS [Valor Pagado]", "alias": "Valor Pagado", "descargar": true, },
						{ "clave": "clienteIdentificacion AS [Identificacion del Cliente]", "alias": "Identificacion del Cliente", "descargar": true, },
						{ "clave": "clienteNombre AS [Cliente]", "alias": "Cliente", "descargar": true, },
						{ "clave": "meseroNombre AS [Mesero]", "alias": "Mesero", "descargar": true, },

						{ "clave": "estructuraNombre AS [Nombre de Mesa]", "alias": "Nombre de Mesa", "descargar": true, },
						{ "clave": "estructuraCodigo AS [Codigo de Mesa]", "alias": "Codigo de Mesa", "descargar": true, },
						{ "clave": "salonNombre AS [Salon]", "alias": "Salon", "descargar": true, },
						{ "clave": "pedidoMetodoPago AS [Método de Pago]", "alias": "Método de Pago", "descargar": true, },
						{ "clave": "pedidoCambioPago AS [Cambio]", "alias": "Cambio", "descargar": true, },
						{ "clave": "comensales AS [Comensales]", "alias": "Comensales", "descargar": true, },
						{ "clave": "totalPromedioConsumoCase AS [Promedio de Consumo]", "alias": "Promedio de Consumo", "descargar": true, },
						{ "clave": "pedidoObservacion AS [Observaciones]", "alias": "Observaciones", "descargar": true, },
						{ "clave": "creacionNombre + ' ' + creacionApellido AS [Responsable]", "alias": "Responsable", "descargar": true, },
						{ "clave": "fechaPago + ' ' + horaPago AS [Fecha de Pago]", "alias": "Fecha de Pago", "descargar": true, },
						{ "clave": "fechaAnulacion + ' ' + horaAnulacion AS [Fecha de Anulación]", "alias": "Fecha de Anulación", "descargar": true, },
						{ "clave": "creacionFecha + ' ' + creacionHora AS [Creación]", "alias": "Creación", "descargar": true, },
						{ "clave": "modificacionFecha + ' ' + modificacionHora AS [Modificación]", "alias": "Modificación", "descargar": true, },
					);
					this.calcularLimiteP(); 
					this.showModal( ventana );
				}, 

				descargarOpcionesXlsx( ventana ) {
					var opciones = "";
					seleccionadas = alasql('SELECT * FROM ? WHERE descargar',[this.opcionesDescarga])
					var tamano = seleccionadas.length - 1;
					if (seleccionadas.length > 0) {
						seleccionadas.forEach(function (el, pos) {
							opciones += el.clave;
							if (pos < tamano) { opciones += ", "; }
						});
						alasql('SELECT '+opciones+' INTO XLSX("pedidos.xlsx",{headers:true}) FROM ?',[ this.objPedidos ]);
					}
					this.hideModal( ventana );
				},
				/**/
					confirmarLiberarEstructuraPedido( ventana ){
						Swal.fire({
							title: '¿Liberar Estructura?', type: 'warning', showCancelButton: true, allowOutsideClick: false,
							confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
						}).then((result) => {
							if (result.value) {
								// this.dicMesa.estado = 'Disponible';
								this.editarEstadoEstructuraPedido( ventana );
							}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
						});
					},

					editarEstadoEstructuraPedido( ventana ){
						this.consultaDetalleInformacion = true;
						axios.post( 
							"/Estructura/editarEstadoEstructuraPedido" , 
							"salon=" + this.dicPedidoDetalle.salonId +
							"&&pedido=" + this.dicPedidoDetalle.pedidoId +
							"&&estructura=" + this.dicPedidoDetalle.estructuraId +
							"&&estado=" + 'Disponible' +

							"&&usuario=" + app.usuarioActual.usuario, 
						).then((result) => {
							// this.consultaDetalleInformacion = false;
							// this.hideModal( ventana );
							this.verDetallePedido();
							this.listadoPedidos(  );
						}).catch( error => { app.erroServidor( '' ); });
					},

				/*EDICION DE PEDIDO DESPUES DE PAGADO*/
					editarPedidoPagado(){

						this.edicionCuenta = ( this.edicionCuenta ) ? false : true;
						if ( this.edicionCuenta ){
							this.objDetalleProductosPedidoCopia = JSON.parse( JSON.stringify( this.objDetalleProductosPedido ) );
						}else{
							this.objDetalleProductosPedido = JSON.parse( JSON.stringify( this.objDetalleProductosPedidoCopia ) );
							this.objDetalleProductosPedidoCopia = [];

							this.calcularSubtotalDetallePedidoV2();
							this.gestionarServicioPropinaV2();
							this.convertirValoresPedidoMonedaCurrency();
						}
					}, 

					quitarProductoDeatallePedido( producto, data, posicion ){
						Swal.fire({
							title: '¿Quitar Producto?', type: 'warning', showCancelButton: true, allowOutsideClick: false,
							confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
						}).then((result) => {
							if (result.value) {
								this.objDetalleProductosPedido.splice( posicion, 1 );
								this.calcularSubtotalDetallePedidoV2();
								this.gestionarServicioPropinaV2();
								this.convertirValoresPedidoMonedaCurrency();
							}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
						});
					},

					verListadoProductos( ventana ){
						this.categoriaFiltro = '';
						this.filtrandoProductoCategotia('');
						this.showModal( ventana );
					}, 

					agregarProductoDetallePedido( producto, ventana ){
						this.dicAgregarProducto = {
							categoriaDestino: producto.categoriaDestino, 
							categoriaId: producto.categoriaId, 
							categoriaNombre: '', 

							detalleConsecutivoOrden: '', 
							detalleDescuento: 0, 
							detalleNota: '', 
							detalleObservacion: '', 
							detalleValorDescuento: 0, 
							productoCantidad: 1, 
							productoId: producto.productoId, 
							productoNombre: producto.productoNombre, 
							productoPrecioVenta: producto.productoPrecioVenta, 
							productoPrecionTotal: producto.productoPrecioVenta * 1, 
							referencia: '', 
						};

						this.showModal( ventana );
					}, 

					confirmarAgregarProductoDetallePedido( ventana ){
						this.dicAgregarProducto.productoPrecionTotal = this.dicAgregarProducto.productoPrecioVenta * this.dicAgregarProducto.productoCantidad;
						this.objDetalleProductosPedido.push( this.dicAgregarProducto );

						this.calcularSubtotalDetallePedidoV2();
						this.gestionarServicioPropinaV2();
						this.convertirValoresPedidoMonedaCurrency();
						this.hideModal( ventana );
					}, 


					verPedidoModal(item){
						console.log("item ", item)
						this.verModalDetallePedidoListadoPedidos( 'modalDetallePedidoV2', item) ;
					},

					abrirModalVerPedidosHijos(){
						this.consultaDetalleInformacion = true; this.objPedidosDetalle = []; 
						this.vistaListadoPedidoPrincipal = true; this.buscadorPedido = ''; 
					
						axios.post( "/Estructura/listadoPedidosSalones", 
							"sucursal=" + this.idSucursalGestion + 
							"&&pedido=" + this.idPedidoGestion + 
							"&&fecha=" + app.fechaActual,
						).then((result) => {
							setTimeout(()=>{
								this.objPedidosDetalle = result.data["pedidos"];
								this.objPedidosCopia = JSON.parse(JSON.stringify(result.data["pedidos"]));
								this.totalDatosPedidos = this.objPedidosDetalle.length;

								this.showModal("modalListadoPedidos"); 
								this.consultaDetalleInformacion = false;
							});
						}).catch( error => {
							this.consultaDetalleInformacion = false;
							app.erroServidor( '' ); 
						});
					}, 

					abrirModalObservacionesPedido( ventana ){ this.showModal( ventana ); }, 
				
				/*  */
					llenarDatosDespachoPedido(){
						this.idClientePedido = JSON.parse(JSON.stringify(app.clienteId)); 
						this.clienteExiste = true; this.mensajeExistenciaCliente = ''; this.activarCambioCliente = false; 
						this.nombreCliente = app.identificacionCliente + " " + app.nombreCliente + " " + app.apellidoCliente; 
						this.verCliente(); 
						app.loading = false; 
					}, 

					validarDatosCampoClientePedido(){
						this.modificacionCliente = true; 
						if (!app.vacios.includes(this.nombreCliente) && !app.vacios.includes(this.idClientePedido)){
							this.idClientePedido = ''; this.dicClientePedido = {}; this.clienteExiste = false; 
							this.mensajeExistenciaCliente = ''; 
						}
					},

					buscarClienteIdentificacion(){
						this.dicClientePedido = {}; this.clienteExiste = false; this.mensajeExistenciaCliente = ''; 
						if (!app.vacios.includes(this.nombreCliente) && app.vacios.includes(this.idClientePedido)){
							this.dicPedidoDetalle.clienteId = ""; 
							this.dicPedidoDetalle.clienteIdentificacion = ""; 
							this.dicPedidoDetalle.clienteNombre = ""; 
							this.dicPedidoDetalle.clienteApellido = ""; 
							this.dicPedidoDetalle.clienteDireccion = ""; 
							this.dicPedidoDetalle.clienteCiudadNombre = ""; 
							axios.post( "/Principal/buscarClienteIdentificacion" , 
								"cliente=" + this.idClientePedido + "&&identificacion=" + this.nombreCliente, 
							).then((result) => {
								if (result.data.clientes.length==1){
									this.dicClientePedido = result.data.clientes[0]; 
									this.idClientePedido = result.data.clientes[0].id; 
									this.nombreCliente = result.data.clientes[0].identificacion + ' ' + result.data.clientes[0].nombre + ' ' + result.data.clientes[0].apellido; 
									this.dicPedidoDetalle.clienteId = result.data.clientes[0].id; 
									
									this.dicPedidoDetalle.clienteIdentificacion = result.data.clientes[0].identificacion; 
									this.dicPedidoDetalle.clienteNombre = result.data.clientes[0].nombre; 
									this.dicPedidoDetalle.clienteApellido = result.data.clientes[0].apellido; 
									this.dicPedidoDetalle.clienteDireccion = result.data.clientes[0].direccion; 
									this.dicPedidoDetalle.clienteCiudadNombre = result.data.clientes[0].ciudadNombre; 

									this.clienteExiste = true; 
								}else if (result.data.clientes.length>1){
									this.idClientePedido = ''; this.mensajeExistenciaCliente = "";  this.dicClientePedido = {}; 
									app.objClientesBuscador = result.data.clientes; 
									app.gestionarlistadoClientesbusqueda('resumen_ventas'); 
								}else{
									this.idClientePedido = ''; this.mensajeExistenciaCliente = "no-existe"; 
								}
							}).catch( error => {
								console.log("ERROR", error);
								app.erroServidor( '' );
							});
						}
					},

					abrirestionEdicionCliente(){
						axios.post( "/Principal/buscarClienteGeneral" , 
							"cliente=" + this.idClientePedido, 
						).then((result) => {
							this.dicClientePedido = result.data.cliente; 
							app.abrirModalGlobalGestonCliente('editar', this.dicClientePedido, 'inicio_salon_despacho_pedido_editar', 'modalGestionClienteGlobal', '');
						}).catch( error => {
							console.log("ERROR", error);
							app.erroServidor( '' );
						}); 
					},
					
					verCliente(){
						axios.post( "/Principal/buscarClienteGeneral" ,  "cliente=" + this.idClientePedido, ).then((result) => {
							this.dicClientePedido = result.data.cliente; 
							this.dicPedidoDetalle.clienteId = result.data.cliente.id; 
							this.dicPedidoDetalle.clienteIdentificacion = result.data.cliente.identificacion; 
							this.dicPedidoDetalle.clienteNombre = result.data.cliente.nombre; 
							this.dicPedidoDetalle.clienteApellido = result.data.cliente.apellido; 
							this.dicPedidoDetalle.clienteDireccion = result.data.cliente.direccion; 
							this.dicPedidoDetalle.clienteCiudadNombre = result.data.cliente.ciudadNombre; 
						}).catch( error => {
							console.log("ERROR", error);
							app.erroServidor( '' );
						}); 
					},

					gestionarCambioCliente(){
						this.activarCambioCliente = this.activarCambioCliente ? false : true; 
						this.nombreCliente = ''; this.mensajeExistenciaCliente = ''; this.clienteExiste = false; 
						this.idClientePedido = ''; this.dicClientePedido = {}; 
						
						this.dicPedidoDetalle.clienteId = ""; 
						this.dicPedidoDetalle.clienteIdentificacion = ""; 
						this.dicPedidoDetalle.clienteNombre = ""; 
						this.dicPedidoDetalle.clienteApellido = ""; 
						this.dicPedidoDetalle.clienteDireccion = ""; 
						this.dicPedidoDetalle.clienteCiudadNombre = ""; 
					}, 
					
				/*gestion de estrucutrar con pedido finalizado*/
					verUltimoDetallePedidoEstructuraV2(){
						this.consultaDetalleInformacion = true;
						this.aperturarEstructura = false; this.modoDividirFacturaPedido = false; 
						var vacios = [undefined, null, '', 'undefined', 'null', 'None'];
						this.idClientePedido = ''; this.nombreCliente = ''; this.clienteExiste = false; this.totalCantidadItemProductos = 0; 
						axios.post( 
							"/Estructura/verUltimoDetallePedidoEstructura", 
							"estructura=" + this.dicMesa.id + 
							"&&fecha=" + app.fechaActual,
						).then((result) => {
							this.objDetalleProductosPedido = result.data.detalle;
							this.objDetallePago = result.data.pagos;
							this.objDivicionCuenta = result.data.division;
							this.objDivicionCuentaCopia = result.data.division;
							this.seleccionarMetodoPago = '';
							this.dicPedidoDetalle = result.data.pedido;
							this.nombreClienteDetalle = this.dicPedidoDetalle.clienteResponsable;
							this.idPedidoGestion = this.dicPedidoDetalle.pedidoId;
							this.totalPagoMedios = 0;
							this.numeroPersonas = ( this.objDivicionCuenta.length > 0 ) ? String(this.objDivicionCuenta.length) : '';
							this.totalCantidadItemProductos = this.objDetalleProductosPedido.length; 
							this.modoDividirFacturaPedido = this.dicPedidoDetalle.modoDividirFactura; 

							if (!app.vacios.includes(this.dicPedidoDetalle.clienteId)){
								this.nombreCliente = this.dicPedidoDetalle.clienteIdentificacion + ' ' + this.dicPedidoDetalle.clienteNombre + ' ' + this.dicPedidoDetalle.clienteApellido; 
								this.idClientePedido = this.dicPedidoDetalle.clienteId; 
								this.clienteExiste = true; 
							}

							if ( result.data.pedido.pedidoEstado != 'Pagado' ){
								if ( this.objConfiguracionesVentas.length > 0 ){
									this.calcularSubtotalDetallePedidoV2();
									if ( !vacios.includes( this.dicPedidoDetalle.impuestoId ) ){
										console.log("PEDIDO YA TIENE IMPUESTO",);
										if ( this.dicPedidoDetalle.impuestoIncluido == 0 ){
											this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.pedidoSubTotal - (this.dicPedidoDetalle.pedidoSubTotal / ( 1 + ( this.dicPedidoDetalle.impuestoPorcentaje / 100 ) ));
											this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 
											
											this.dicPedidoDetalle.pedidoSubTotal = this.dicPedidoDetalle.pedidoSubTotal - this.dicPedidoDetalle.pedidoValorImpuesto;
											this.dicPedidoDetalle.pedidoSubTotal = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubTotal, "").replaceAll(",", "")); 
										}else if ( this.dicPedidoDetalle.impuestoIncluido == 1 ){
											this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.pedidoSubTotal * ( this.dicPedidoDetalle.impuestoPorcentaje / 100 );
											this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 
										}
									}else{
										console.log("PEDIDO NO TIENE IMPUESTO",);
										if ( this.dicConfiguracionVenta.idImpuesto__incluido == 0 ){
											this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.pedidoSubTotal - (this.dicPedidoDetalle.pedidoSubTotal / ( 1 + ( this.dicConfiguracionVenta.idImpuesto__impuesto / 100 ) ));
											this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 
											
											this.dicPedidoDetalle.pedidoSubTotal = this.dicPedidoDetalle.pedidoSubTotal - this.dicPedidoDetalle.pedidoValorImpuesto;
											this.dicPedidoDetalle.pedidoSubTotal = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubTotal, "").replaceAll(",", "")); 
										}else if ( this.dicConfiguracionVenta.idImpuesto__incluido == 1 ){
											this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.pedidoSubTotal * ( this.dicConfiguracionVenta.idImpuesto__impuesto / 100 );
											this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 
										}
									}

									this.aplicarServicioPropina = this.dicPedidoDetalle.propina; 
									if ( !this.dicPedidoDetalle.propinaModificada ){
										this.dicPedidoDetalle.pedidoMetodoPago = 'Tarjeta';
										if ( this.aplicarServicioPropina ){
											console.log("clacular propina");
											this.dicPedidoDetalle.pedidoPropinaValor = ( (this.dicPedidoDetalle.pedidoSubTotal) * (this.dicConfiguracionVenta.porcentajeServicio/100) );
											this.dicPedidoDetalle.pedidoPropinaValor = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoPropinaValor, "").replaceAll(",", "")); 
											this.dicPedidoDetalle.porcentajePropina = this.dicConfiguracionVenta.porcentajeServicio; 
										}
									}

									this.dicPedidoDetalle.pedidoCambioPagoGuardado = this.dicPedidoDetalle.pedidoCambioPago;
									this.dicPedidoDetalle.pedidoCambioPagoGuardado = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoCambioPagoGuardado, "").replaceAll(",", "")); 
									this.calcularTotalAPagarPedido();
									this.convertirValoresPedidoMonedaCurrency();

									if ( this.objDetallePago.length == 0 ){
										this.agregarMetodoPagoPedidoInicialV2();
									}else{
										// this.marcarCalculadora( this.objDetallePago[0], 0, 'metodo_pago' );
										this.dicCalculado = { total: 0, totalStr: this.cantidadC( 0 ), posicion: '', marcador: '', };
										this.validarTotalMediosPagosV2();
									}
								}
							}else{
								this.calcularDatosRestanteVer();
								this.convertirValoresPedidoMonedaCurrencyVerSolamente();
							}

							if (this.dicPedidoDetalle.modoDividirFactura){
								this.activarDividirFactura(); 
							}
							this.consultaDetalleInformacion = false;
						}).catch( error => {
							console.log("error", error);
							this.consultaDetalleInformacion = false;
							app.erroServidor( '' );
						});
					}, 

					verDetallePedidoV2(){
						this.consultaDetalleInformacion = true;
						this.aperturarEstructura = false; this.modoDividirFacturaPedido = false; this.modificarFacturaPagada = false; 
						var vacios = [undefined, null, '', 'undefined', 'null', 'None']; this.activarCambioCliente = false; 
						this.idClientePedido = ''; this.nombreCliente = ''; this.clienteExiste = false; this.totalCantidadItemProductos = 0; 
						this.mostrarInputsDetalleImpuestos = false; this.objDetalleImpuestosProducto = []; 
						axios.post( "/Estructura/verDetallePedido", "pedido=" + this.idPedidoGestion, ).then((result) => {
							this.objDetalleProductosPedido = result.data.detalle;
							this.objDetallePago = result.data.pagos;
							this.objDivicionCuenta = result.data.division;
							this.objDivicionCuentaCopia = result.data.division;
							this.seleccionarMetodoPago = '';
							this.dicPedidoDetalle = result.data.pedido;
							this.nombreClienteDetalle = this.dicPedidoDetalle.clienteResponsable;
							this.idPedidoGestion = this.dicPedidoDetalle.pedidoId;
							this.totalPagoMedios = 0;
							this.numeroPersonas = ( this.objDivicionCuenta.length > 0 ) ? String(this.objDivicionCuenta.length) : '';
							this.totalCantidadItemProductos = this.objDetalleProductosPedido.length; 
							this.modoDividirFacturaPedido = this.dicPedidoDetalle.modoDividirFactura; 
							
							if (!app.vacios.includes(this.dicPedidoDetalle.clienteId)){
								this.nombreCliente = this.dicPedidoDetalle.clienteIdentificacion + ' ' + this.dicPedidoDetalle.clienteNombre + ' ' + this.dicPedidoDetalle.clienteApellido; 
								this.idClientePedido = this.dicPedidoDetalle.clienteId; 
								this.clienteExiste = true; 
							}

							if ( this.objConfiguracionesVentas.length > 0 ){
								/* this.calcularSubtotalDetallePedidoV2();
								this.calcularImpuestoDetallePedidoV2(); */
								if (!this.dicPedidoDetalle.ivaProducto){
									this.calcularSubtotalDetallePedidoV2();
									this.calcularImpuestosDetallePedido();
								}else{
									this.calcularSubtotalDetallePedidoV2IvaProducto(); 
									this.calcularImpuestosDetallePedidoIvaProducto(); 
									this.calcularIMpuestoDetallePedidoProducto(); 
								}

								this.aplicarServicioPropina = this.dicPedidoDetalle.propina; 
								if ( !this.dicPedidoDetalle.propinaModificada && this.dicPedidoDetalle.pedidoEstado!='Pagado' ){
									this.dicPedidoDetalle.pedidoMetodoPago = 'Tarjeta';
									if ( this.aplicarServicioPropina ){
										this.dicPedidoDetalle.pedidoPropinaValor = ( (this.dicPedidoDetalle.pedidoSubTotal) * (this.dicConfiguracionVenta.porcentajeServicio/100) );
										this.dicPedidoDetalle.pedidoPropinaValor = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoPropinaValor, "").replaceAll(",", "")); 
										this.dicPedidoDetalle.porcentajePropina = this.dicConfiguracionVenta.porcentajeServicio; 
									}
								}

								this.dicPedidoDetalle.pedidoCambioPagoGuardado = this.dicPedidoDetalle.pedidoCambioPago;
								this.dicPedidoDetalle.pedidoCambioPagoGuardado = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoCambioPagoGuardado, "").replaceAll(",", "")); 
								this.calcularTotalAPagarPedido();
								this.convertirValoresPedidoMonedaCurrency();

								if ( this.objDetallePago.length == 0 ){
									this.agregarMetodoPagoPedidoV2();
								}else{
									// this.marcarCalculadora( this.objDetallePago[0], 0, 'metodo_pago' );
									this.dicCalculado = { total: 0, totalStr: this.cantidadC( 0 ), posicion: '', marcador: '', };
									this.validarTotalMediosPagosV2();
								}
								this.cargarMetodosPagosSeleccionados();
							}

							if (this.recargarPedido){
								this.recargarPedido = false; 
								this.verDetallePedidoV2(); 
							}else{
								if (this.dicPedidoDetalle.modoDividirFactura){
									this.activarDividirFactura(); 
								}
								this.consultaDetalleInformacion = false;
							}
						}).catch( error => {
							console.log("error", error);
							app.erroServidor( '' );
						});
					}, 

					calcularSubtotalDetallePedidoV2Copia(){
						// var subtotal = alasql( "select sum( cast( productoPrecionTotal as floart ) ) as totalSuma from ?", [ this.objDetalleProductosPedido ] )[0].totalSuma;
						// var subtotalV = alasql( "select sum( cast( productoPrecioVenta as floart )*cast( productoCantidad as floart ) ) as totalSuma from ?", [ this.objDetalleProductosPedido ] )[0].totalSuma;
						// var subtotal = alasql( "select sum( cast( productoPrecioVenta as float ) * cast( productoCantidad as integer ) ) as totalSuma from ?", [ this.objDetalleProductosPedido ] )[0].totalSuma;
						if (this.modoDividirFacturaPedido){
							var subtotal = alasql( 
								"select sum( cast( productoPrecionTotal as floart ) ) as totalSuma from ? where seleccionar=true", 
								[ this.objDetalleProductosPedido ] 
							)[0].totalSuma;
						}else{
							var subtotal = alasql( "select sum( cast( productoPrecionTotal as floart ) ) as totalSuma from ?", [ this.objDetalleProductosPedido ] )[0].totalSuma;
						}

						subtotal = parseFloat(app.$options.filters.currency(subtotal, "").replaceAll(",", "")); 
						this.dicPedidoDetalle.pedidoSubTotal = subtotal;
						// this.dicPedidoDetalle.pedidoPrecioTotalProductos = subtotalV;
						this.dicPedidoDetalle.pedidoPrecioTotalProductos = subtotal;

						this.dicPedidoDetalle.pedidoTotalDescuento = ( this.dicPedidoDetalle.pedidoSubTotal * (this.dicPedidoDetalle.pedidoDescuento/100) );
						this.dicPedidoDetalle.pedidoTotalDescuento = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoTotalDescuento, "").replaceAll(",", "")); 

						this.dicPedidoDetalle.pedidoSubTotalConDescuento = this.dicPedidoDetalle.pedidoSubTotal - this.dicPedidoDetalle.pedidoTotalDescuento;
						this.dicPedidoDetalle.pedidoSubTotalConDescuento = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubTotalConDescuento, "").replaceAll(",", "")); 

						this.dicPedidoDetalle.pedidoSubTotal = this.dicPedidoDetalle.pedidoSubTotal - this.dicPedidoDetalle.pedidoTotalDescuento;
						this.dicPedidoDetalle.pedidoSubTotal = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubTotal, "").replaceAll(",", "")); 
					}, 

					calcularSubtotalDetallePedidoV2(){
						var consulta1 = "where productoNoAplicaImpuesto=false"; 
						var consulta2 = "where productoNoAplicaImpuesto=true"; 
						if (this.modoDividirFacturaPedido){
							consulta1 = consulta1 + " and seleccionar=true"; 
							consulta2 = consulta2 + " and seleccionar=true"; 
							/* var subtotal = alasql( "select sum( cast( productoPrecionTotal as floart ) ) as totalSuma from ? where seleccionar=true", [ this.objDetalleProductosPedido ] )[0].totalSuma; */
						}/* else{
							var subtotal = alasql( "select sum( cast( productoPrecionTotal as floart ) ) as totalSuma from ?", [ this.objDetalleProductosPedido ] )[0].totalSuma;
						} */

						// nuevo
						var subtotalImpuestos = alasql("select sum(cast(productoPrecionTotal as floart)) as totalSuma from ? "+consulta1, [this.objDetalleProductosPedido])[0].totalSuma;
						var subtotalSinImpuestos = alasql("select sum(cast(productoPrecionTotal as floart)) as totalSuma from ? "+consulta2, [this.objDetalleProductosPedido])[0].totalSuma;
						this.dicPedidoDetalle.subtotalImpuestos = subtotalImpuestos;
						this.dicPedidoDetalle.subtotalSinImpuestos = subtotalSinImpuestos;
						this.dicPedidoDetalle.subtotalImpuestos = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.subtotalImpuestos, "").replaceAll(",", "")); 
						this.dicPedidoDetalle.subtotalSinImpuestos = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.subtotalSinImpuestos, "").replaceAll(",", "")); 
						
						subtotal = this.dicPedidoDetalle.subtotalImpuestos + this.dicPedidoDetalle.subtotalSinImpuestos; 
						subtotal = parseFloat(app.$options.filters.currency(subtotal, "").replaceAll(",", "")); 
						this.dicPedidoDetalle.pedidoPrecioTotalProductos = subtotal;
						this.dicPedidoDetalle.pedidoSubTotal = subtotal;
						
						/* this.dicPedidoDetalle.pedidoTotalDescuento = ( this.dicPedidoDetalle.pedidoSubTotal * (this.dicPedidoDetalle.pedidoDescuento/100) );
						this.dicPedidoDetalle.pedidoTotalDescuento = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoTotalDescuento, "").replaceAll(",", ""));  */
						
						// nuevo
						this.dicPedidoDetalle.totalDescuentoImpuesto = ( this.dicPedidoDetalle.subtotalImpuestos * (this.dicPedidoDetalle.pedidoDescuento/100) );
						this.dicPedidoDetalle.totalDescuentoImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.totalDescuentoImpuesto, "").replaceAll(",", "")); 
						this.dicPedidoDetalle.totalDescuentoSinImpuesto = ( this.dicPedidoDetalle.subtotalSinImpuestos * (this.dicPedidoDetalle.pedidoDescuento/100) );
						this.dicPedidoDetalle.totalDescuentoSinImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.totalDescuentoSinImpuesto, "").replaceAll(",", "")); 
						
						this.dicPedidoDetalle.pedidoTotalDescuento = this.dicPedidoDetalle.totalDescuentoImpuesto + this.dicPedidoDetalle.totalDescuentoSinImpuesto; 
						this.dicPedidoDetalle.pedidoTotalDescuento = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoTotalDescuento, "").replaceAll(",", "")); 

						/* this.dicPedidoDetalle.pedidoSubTotalConDescuento = this.dicPedidoDetalle.pedidoSubTotal - this.dicPedidoDetalle.pedidoTotalDescuento; */
						
						// nuevo
						this.dicPedidoDetalle.subtotalConDescuentoImpuesto = this.dicPedidoDetalle.subtotalImpuestos - this.dicPedidoDetalle.totalDescuentoImpuesto;
						this.dicPedidoDetalle.subtotalConDescuentoImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.subtotalConDescuentoImpuesto, "").replaceAll(",", "")); 
						this.dicPedidoDetalle.subtotalConDescuentoSinImpuesto = this.dicPedidoDetalle.subtotalSinImpuestos - this.dicPedidoDetalle.totalDescuentoSinImpuesto;
						this.dicPedidoDetalle.subtotalConDescuentoSinImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.subtotalConDescuentoSinImpuesto, "").replaceAll(",", "")); 
						
						this.dicPedidoDetalle.pedidoSubTotalConDescuento = this.dicPedidoDetalle.subtotalConDescuentoImpuesto + this.dicPedidoDetalle.subtotalConDescuentoSinImpuesto;
						this.dicPedidoDetalle.pedidoSubTotalConDescuento = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubTotalConDescuento, "").replaceAll(",", "")); 
						
						/* this.dicPedidoDetalle.pedidoSubTotal = this.dicPedidoDetalle.subtotalConDescuentoImpuesto - this.dicPedidoDetalle.pedidoTotalDescuento;
						this.dicPedidoDetalle.pedidoSubTotal = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubTotal, "").replaceAll(",", ""));  */						
					}, 

					calcularImpuestosDetallePedido(){
						if ( !app.vacios.includes( this.dicPedidoDetalle.impuestoId ) ){
							if ( this.dicPedidoDetalle.impuestoIncluido == 0 ){
								this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto - (this.dicPedidoDetalle.subtotalConDescuentoImpuesto / ( 1 + ( this.dicPedidoDetalle.impuestoPorcentaje / 100 ) ));
								this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 
																
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto - this.dicPedidoDetalle.pedidoValorImpuesto;
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubtotalConImpuesto, "").replaceAll(",", "")); 
								console.log("this.dicPedidoDetalle.pedidoSubtotalConImpuesto", this.dicPedidoDetalle.pedidoSubtotalConImpuesto); 
							}else if ( this.dicPedidoDetalle.impuestoIncluido == 1 ){
								this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto * ( this.dicPedidoDetalle.impuestoPorcentaje / 100 );
								this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 
								
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto;
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubtotalConImpuesto, "").replaceAll(",", "")); 
							}
						}else{
							if ( this.dicConfiguracionVenta.idImpuesto__incluido == 0 ){
								this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto - (this.dicPedidoDetalle.subtotalConDescuentoImpuesto / ( 1 + ( this.dicConfiguracionVenta.idImpuesto__impuesto / 100 ) ));
								this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 
																
								this.dicPedidoDetalle.impuestoIncluido = 0;
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto - this.dicPedidoDetalle.pedidoValorImpuesto;
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubtotalConImpuesto, "").replaceAll(",", "")); 
							}else if ( this.dicConfiguracionVenta.idImpuesto__incluido == 1 ){
								this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto * ( this.dicConfiguracionVenta.idImpuesto__impuesto / 100 );
								this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 
								this.dicPedidoDetalle.impuestoIncluido = 1;
								
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto;
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubtotalConImpuesto, "").replaceAll(",", "")); 
							}
						}

						this.dicPedidoDetalle.pedidoSubTotal = this.dicPedidoDetalle.pedidoSubtotalConImpuesto + this.dicPedidoDetalle.subtotalConDescuentoSinImpuesto; 
					}, 
					
					calcularSubtotalDetallePedidoV2IvaProducto(){
						var consulta1 = ""; var consulta2 = ""; 
						if (this.modoDividirFacturaPedido){
							consulta1 = consulta1 + "where seleccionar=true"; 
						}

						var subtotalImpuestos = alasql("select sum(cast(productoPrecionTotal as floart)) as totalSuma from ? "+consulta1, [this.objDetalleProductosPedido])[0].totalSuma;
						var subtotalSinImpuestos = 0;
						this.dicPedidoDetalle.subtotalImpuestos = subtotalImpuestos;
						this.dicPedidoDetalle.subtotalImpuestos = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.subtotalImpuestos, "").replaceAll(",", "")); 
						this.dicPedidoDetalle.subtotalSinImpuestos = 0; 
						
						subtotal = this.dicPedidoDetalle.subtotalImpuestos + this.dicPedidoDetalle.subtotalSinImpuestos; 
						subtotal = parseFloat(app.$options.filters.currency(subtotal, "").replaceAll(",", "")); 
						this.dicPedidoDetalle.pedidoPrecioTotalProductos = subtotal;
						this.dicPedidoDetalle.pedidoSubTotal = subtotal;

						this.dicPedidoDetalle.totalDescuentoImpuesto = ( this.dicPedidoDetalle.subtotalImpuestos * (this.dicPedidoDetalle.pedidoDescuento/100) );
						this.dicPedidoDetalle.totalDescuentoImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.totalDescuentoImpuesto, "").replaceAll(",", "")); 
						this.dicPedidoDetalle.totalDescuentoSinImpuesto = 0; 
						
						this.dicPedidoDetalle.pedidoTotalDescuento = this.dicPedidoDetalle.totalDescuentoImpuesto + this.dicPedidoDetalle.totalDescuentoSinImpuesto; 
						this.dicPedidoDetalle.pedidoTotalDescuento = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoTotalDescuento, "").replaceAll(",", "")); 

						this.dicPedidoDetalle.subtotalConDescuentoImpuesto = this.dicPedidoDetalle.subtotalImpuestos - this.dicPedidoDetalle.totalDescuentoImpuesto;
						this.dicPedidoDetalle.subtotalConDescuentoImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.subtotalConDescuentoImpuesto, "").replaceAll(",", "")); 
						this.dicPedidoDetalle.subtotalConDescuentoSinImpuesto = 0; 
						
						this.dicPedidoDetalle.pedidoSubTotalConDescuento = this.dicPedidoDetalle.subtotalConDescuentoImpuesto + this.dicPedidoDetalle.subtotalConDescuentoSinImpuesto;
						this.dicPedidoDetalle.pedidoSubTotalConDescuento = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubTotalConDescuento, "").replaceAll(",", "")); 
					}, 

					calcularImpuestosDetallePedidoIvaProducto(){
						var consulta1 = ""; var consulta2 = ""; 
						if (this.modoDividirFacturaPedido){
							consulta1 = consulta1 + "where seleccionar=true"; 
						}

						var totalImpuesto = alasql("select sum(cast(productoTotalImpuesto as floart)) as totalSuma from ? "+consulta1, [this.objDetalleProductosPedido])[0].totalSuma;
						var descuentoImpuestos = totalImpuesto* (this.dicPedidoDetalle.pedidoDescuento/100); 
						this.dicPedidoDetalle.pedidoValorImpuesto = totalImpuesto-descuentoImpuestos; 
						this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 

						this.dicPedidoDetalle.pedidoSubtotalConImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto - this.dicPedidoDetalle.pedidoValorImpuesto;
						// this.dicPedidoDetalle.pedidoSubtotalConImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto ;
						this.dicPedidoDetalle.pedidoSubtotalConImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubtotalConImpuesto, "").replaceAll(",", "")); 

						this.dicPedidoDetalle.pedidoSubTotal = this.dicPedidoDetalle.pedidoSubtotalConImpuesto + this.dicPedidoDetalle.subtotalConDescuentoSinImpuesto; 
					},

					calcularDatosRestanteVer(){
						var subtotal = alasql( "select sum( cast( productoPrecionTotal as floart ) ) as totalSuma from ?", [ this.objDetalleProductosPedido ] )[0].totalSuma;
						var subtotalV = alasql( "select sum( cast( productoPrecioVenta as floart )*cast( productoCantidad as floart ) ) as totalSuma from ?", [ this.objDetalleProductosPedido ] )[0].totalSuma;
						/* this.dicPedidoDetalle.pedidoPrecioTotalProductos = subtotalV; */
						this.dicPedidoDetalle.pedidoPrecioTotalProductos = subtotal;
						this.dicPedidoDetalle.pedidoPrecioTotalProductos = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoPrecioTotalProductos, "").replaceAll(",", "")); 

						this.dicPedidoDetalle.pedidoSubTotalConDescuento = subtotal - this.dicPedidoDetalle.pedidoTotalDescuento;
						this.dicPedidoDetalle.pedidoSubTotalConDescuento = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubTotalConDescuento, "").replaceAll(",", "")); 
					}, 

					calcularTotalAPagarPedido(){
						var total = this.dicPedidoDetalle.pedidoSubTotal + this.dicPedidoDetalle.pedidoValorImpuesto;
						this.dicPedidoDetalle.pedidoPrecioTotal = total;
						this.dicPedidoDetalle.pedidoPrecioTotal = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoPrecioTotal, "").replaceAll(",", "")); 
						this.calcularTotalNetoAPagarPedido();
					},

					calcularTotalNetoAPagarPedido(){
						this.dicPedidoDetalle.pedidoTotalNeto = this.dicPedidoDetalle.pedidoPrecioTotal + this.dicPedidoDetalle.pedidoPropinaValor;
						this.dicPedidoDetalle.pedidoTotalNeto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoTotalNeto, "").replaceAll(",", "")); 
					},

					validarTotalMediosPagosV2(){
						this.totalPagoMedios = alasql("select SUM( cast ( valor as float ) ) as sumaPagos from ? where valor>0", [this.objDetallePago])[0].sumaPagos;
						this.dicPedidoDetalle.totalPagoMedios = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.totalPagoMedios, "").replaceAll(",", "")); 
						
						this.dicPedidoDetalle.pedidoValorPagado = this.totalPagoMedios;
						this.dicPedidoDetalle.pedidoValorPagado = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorPagado, "").replaceAll(",", "")); 
						/*console.log( this.dicPedidoDetalle.pedidoValorPagado );*/
						this.convertirValoresPedidoMonedaCurrency();
						this.calcularCambioPagoV2();
					}, 

					cargarMetodosPagosSeleccionados(){
						this.metodosPagosSeleccionados = alasql("select column metodoPago__id from ?", [this.objDetallePago]); 
					}, 

					cambiarEstadoPropinaPedido(){
						this.aplicarServicioPropina = ( this.aplicarServicioPropina ) ? false : true;
						this.gestionarServicioPropinaV2();
					}, 

					gestionarServicioPropinaV2(){
						if ( !this.dicPedidoDetalle.propinaModificada ){
							if ( this.aplicarServicioPropina ){
								/* this.dicPedidoDetalle.pedidoPropinaValor = ( (this.dicPedidoDetalle.pedidoSubTotal + this.dicPedidoDetalle.pedidoValorImpuesto) * (this.dicConfiguracionVenta.porcentajeServicio/100) ); */
								this.dicPedidoDetalle.pedidoPropinaValor = ( (this.dicPedidoDetalle.pedidoSubTotal) * (this.dicConfiguracionVenta.porcentajeServicio/100) );
								this.dicPedidoDetalle.pedidoPropinaValor = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoPropinaValor, "").replaceAll(",", "")); 
								this.dicPedidoDetalle.porcentajePropina = this.dicConfiguracionVenta.porcentajeServicio;
							}else{
								/* this.dicPedidoDetalle.pedidoPropinaValor = ( (this.dicPedidoDetalle.pedidoSubTotal + this.dicPedidoDetalle.pedidoValorImpuesto) * 0 ); */
								this.dicPedidoDetalle.pedidoPropinaValor = ( (this.dicPedidoDetalle.pedidoSubTotal) * 0 );
								this.dicPedidoDetalle.pedidoPropinaValor = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoPropinaValor, "").replaceAll(",", "")); 
								this.dicPedidoDetalle.porcentajePropina = 0;
							}
						}

						if ( this.dicPedidoDetalle.propinaModificada && !this.aplicarServicioPropina ){
							this.dicPedidoDetalle.propinaModificada = false;
							/* this.dicPedidoDetalle.pedidoPropinaValor = ( (this.dicPedidoDetalle.pedidoSubTotal + this.dicPedidoDetalle.pedidoValorImpuesto) * 0 ); */
							this.dicPedidoDetalle.pedidoPropinaValor = ( (this.dicPedidoDetalle.pedidoSubTotal) * 0 );
							this.dicPedidoDetalle.porcentajePropina = 0;
						}

						this.calcularTotalAPagarPedido();
						this.reiniciarMetodosPagosCero();
						this.validarTotalMediosPagosV2();
						this.convertirValoresPedidoMonedaCurrency();
						this.calcularCambioPagoV2();

						this.marcarCalculadoraPropina('', 0, 'propina');
					}, 

					calcularCambioPagoV2(){
						setTimeout(()=>{
							if ( this.dicPedidoDetalle.pedidoValorPagado > 0 && this.dicPedidoDetalle.pedidoValorPagado >= this.dicPedidoDetalle.pedidoTotalNeto ){
								this.dicPedidoDetalle.pedidoCambioPago = this.dicPedidoDetalle.pedidoValorPagado - this.dicPedidoDetalle.pedidoTotalNeto;
								this.dicPedidoDetalle.pedidoCambioPago = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoCambioPago, "").replaceAll(",", "")); 
								
								this.dicPedidoDetalle.pedidoCambioPagoStr = this.moneda( this.dicPedidoDetalle.pedidoCambioPago );
							}else if ( this.dicPedidoDetalle.pedidoCambioPago < 0 || this.dicPedidoDetalle.pedidoValorPagado < this.dicPedidoDetalle.pedidoTotalNeto ){
								this.dicPedidoDetalle.pedidoCambioPago = 0;
								this.dicPedidoDetalle.pedidoCambioPago = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoCambioPago, "").replaceAll(",", "")); 
								
								this.dicPedidoDetalle.pedidoCambioPagoStr = this.moneda( this.dicPedidoDetalle.pedidoCambioPago );
							}else{
								this.dicPedidoDetalle.pedidoCambioPago = 0;
								this.dicPedidoDetalle.pedidoCambioPagoStr = this.moneda( this.dicPedidoDetalle.pedidoCambioPago );
							}
							
							if ( this.dicPedidoDetalle.pedidoTotalNeto >= this.dicPedidoDetalle.pedidoValorPagado ){
								this.dicPedidoDetalle.pedidoRestante = this.dicPedidoDetalle.pedidoTotalNeto - this.dicPedidoDetalle.pedidoValorPagado;
								this.dicPedidoDetalle.pedidoRestante = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoRestante, "").replaceAll(",", "")); 
								this.dicPedidoDetalle.pedidoRestanteStr = this.moneda( this.dicPedidoDetalle.pedidoRestante );
							}else{
								this.dicPedidoDetalle.pedidoRestante = 0;
								this.dicPedidoDetalle.pedidoRestanteStr = this.moneda( this.dicPedidoDetalle.pedidoRestante );
							}
						});
					},

					cambiarMetodoPagoPedido( datos, posicion, marcador ){ 
						if (this.dicPedidoDetalle.pedidoEstado!='Pagado' && !this.dicPedidoDetalle.pedidoFacturacionEstado){
							var metodo = alasql("select * from ? where id="+datos.metodoPago__id, [app.objGlobalMetodosPagos])[0]; 
							this.objDetallePago[posicion].metodo = metodo.tipo_pago; 
							this.marcarCalculadora( datos, posicion, marcador ); 
							this.cargarMetodosPagosSeleccionados();  
						}
					},

					quitarMetodPagoV2( datos, posicion ){
						this.objDetallePago.splice( posicion, 1 );
						if ( this.objDetallePago.length > 0 ){
							/* this.llenarValorTotalMetodoPagoPedido( this.objDetallePago[0], 0, 'metodo_pago' ); */
							this.validarTotalMediosPagosV2();
							this.marcarCalculadora( datos, this.objDetallePago.length-1, 'metodo_pago' );
						}else{
							this.validarTotalMediosPagosV2();
						}
						this.cargarMetodosPagosSeleccionados(); 
					}, 

					llenarValorTotalMetodoPagoPedido( datos, posicion, marcador ){
						var divicionFacturaMetodosPagos = this.dicPedidoDetalle.pedidoTotalNeto / this.objDetallePago.length;
						var totalDivision = 0;
						this.objDetallePago.forEach(( elemento, posicion )=>{
							totalDivision = totalDivision + divicionFacturaMetodosPagos;
							if ( ( posicion + 1 ) == this.objDetallePago.length ){
								console.log("ultima posicion", divicionFacturaMetodosPagos * posicion);
								divicionFacturaMetodosPagos = this.dicPedidoDetalle.pedidoTotalNeto - divicionFacturaMetodosPagos * posicion;
							}
							this.objDetallePago[ posicion ].valor = divicionFacturaMetodosPagos;
							this.objDetallePago[ posicion ].valor = parseFloat(app.$options.filters.currency(divicionFacturaMetodosPagos, "").replaceAll(",", ""));
						});
						this.validarTotalMediosPagosV2();
						this.marcarCalculadora( datos, posicion, marcador );
					},

					llenarValorTotalMetodoPagoPedidoV2( datos, posicion, marcador ){
						if(this.validarValorMetodosNoEfectivo()<this.dicPedidoDetalle.pedidoTotalNeto && this.objDetallePago[ posicion ].metodo!='Efectivo'){
							this.objDetallePago[ posicion ].valor = this.dicPedidoDetalle.pedidoTotalNeto - this.validarValorMetodosNoEfectivo(this.objDetallePago[ posicion ].metodo); 
						}if(this.validarValorMetodosNoEfectivo()>this.dicPedidoDetalle.pedidoTotalNeto && this.objDetallePago[ posicion ].valor>0 && this.objDetallePago[ posicion ].metodo!='Efectivo'){
							this.objDetallePago[ posicion ].valor = this.dicPedidoDetalle.pedidoTotalNeto - this.validarValorMetodosNoEfectivo(this.objDetallePago[ posicion ].metodo); 
						}else if (this.objDetallePago[ posicion ].metodo=='Efectivo'){
							this.objDetallePago[ posicion ].valor = this.dicPedidoDetalle.pedidoTotalNeto; 
						}

						this.validarTotalMediosPagosV2();
					},


					ajustarTotalMediosPagos( posicionModificado ){
						console.log(" ---posicionModificado--- ", posicionModificado);
						var valorRestante = 0;
						var divicionFacturaMetodosPagos = 0;
						var totalDivision = 0;
						this.objDetallePago.forEach(( elemento, posicion )=>{
							if ( posicion > parseInt( posicionModificado ) ){
								console.log(" ---divicionFacturaMetodosPagos---entra--- ", divicionFacturaMetodosPagos);
								totalDivision = totalDivision + Number(divicionFacturaMetodosPagos.toFixed(2));
								if ( ( posicion + 1 ) == this.objDetallePago.length ){
									console.log("ultima posicion", Number((divicionFacturaMetodosPagos * (posicion - (posicionModificado+1))).toFixed(2)));
									divicionFacturaMetodosPagos = (divicionFacturaMetodosPagos>0) ? valorRestante - (Number(divicionFacturaMetodosPagos.toFixed(2)) * (posicion - (posicionModificado+1))) : 0;
									console.log(" ---divicionFacturaMetodosPagos--- ", divicionFacturaMetodosPagos);
								}else{
									console.log(" ---divicionFacturaMetodosPagos--- ", divicionFacturaMetodosPagos);
								}
								this.objDetallePago[ posicion ].valor = Number(divicionFacturaMetodosPagos.toFixed(2));
							}else{
								totalDivision = parseFloat(totalDivision) + parseFloat(this.objDetallePago[ posicion ].valor);
								valorRestante = ( valorRestante === 0 ) ? this.dicPedidoDetalle.pedidoTotalNeto - this.objDetallePago[ posicion ].valor : valorRestante - this.objDetallePago[ posicion ].valor;
								console.log(" ---valorRestante--- ", valorRestante);
								console.log(" ---totalDivision--- ", totalDivision);
								divicionFacturaMetodosPagos = (totalDivision >= this.dicPedidoDetalle.pedidoTotalNeto) ? 0 : valorRestante / ( this.objDetallePago.length - ( posicion + 1 ) );
								console.log(" ---divicionFacturaMetodosPagos---division--- ", (totalDivision <= this.dicPedidoDetalle.pedidoTotalNeto));
								console.log(" ---divicionFacturaMetodosPagos---division--- ", divicionFacturaMetodosPagos);
							}
						});
					}, 

					marcarCalculadoraMetodo( datos, posicion, marcador ){
						this.cambioRecienTocado = true; 
						this.validarTotalMediosPagosV2();
						this.marcarCalculadora( datos, posicion, marcador );
					}, 

					marcarCalculadoraPropina( datos, posicion, marcador ){
						this.cambioRecienTocado = true;
						setTimeout(()=>{
							this.dicCalculado = {
								total: JSON.parse( JSON.stringify( this.dicPedidoDetalle.pedidoPropinaValor ) ), 
								totalStr: this.cantidadC( JSON.parse( JSON.stringify( this.dicPedidoDetalle.pedidoPropinaValor ) ) ), 
								posicion: posicion, 
								marcador: marcador, 
							};
						});
					},

					gestionarFidelizacionVenta(){
						this.idFidelizacion = ""; this.dicCupon = {}; 
						if (this.dicPedidoDetalle.cuponId!=null){
							this.idFidelizacion = JSON.parse(JSON.stringify(this.dicPedidoDetalle.cuponId)); 
							this.dicCupon = {
								id: this.idFidelizacion, descuento:this.dicPedidoDetalle.pedidoDescuento, 
							}; 
						}
						this.showModal("modalGestionarFidelizacion"); 
					}, 

					marcarCuponFidelizacion(item){
						item = JSON.parse(JSON.stringify(item)); 
						if (item.id==this.idFidelizacion){
							this.idFidelizacion = ""; this.dicCupon = {}; 
						}else{
							this.idFidelizacion = item.id; 
							this.dicCupon = item; 
						}
					}, 

					asignarCuponFidelzacion(){
						if (this.idFidelizacion==""){
							this.dicPedidoDetalle.cuponId = null; 
							this.dicPedidoDetalle.pedidoDescuento = 0; 
						}else{
							this.dicPedidoDetalle.cuponId = JSON.parse(JSON.stringify(this.idFidelizacion)); 
							this.dicPedidoDetalle.pedidoDescuento = JSON.parse(JSON.stringify(this.dicCupon.descuento)); 
						}
						this.calcularDescuentoSubtotalPedidoV2();
						this.hideModal("modalGestionarFidelizacion"); 
					}, 

					marcarCalculadora( datos, posicion, marcador ){
						setTimeout(()=>{
							this.cambioRecienTocado = true; 
							this.dicCalculado = {
								total: JSON.parse( JSON.stringify( datos.valor ) ), 
								totalStr: this.cantidadC( JSON.parse( JSON.stringify( datos.valor ) ) ), 
								posicion: posicion, 
								marcador: marcador, 
							};
						});
					},

					agregarMetodoPagoPedidoV2(){
						// setTimeout(()=>{
							if (this.objDetallePago.length<app.objGlobalMetodosPagos.length){
								this.validarTotalMediosPagosV2();
								var metodo = this.validarMetodoFaltante(); 
								// console.log("metodo", metodo)
								metodo = alasql("select * from ? where id="+metodo, [app.objGlobalMetodosPagos])[0]; 
								var valorFaltante = this.dicPedidoDetalle.pedidoTotalNeto - this.totalPagoMedios;
								valorFaltante = ( valorFaltante <= -1 ) ? 0 : valorFaltante;
								this.objDetallePago.push({
									id:'', 
									metodoPago__id: metodo.id, 
									metodo: metodo.tipo_pago, 
									valor:valorFaltante,
									valorPagado:valorFaltante,
									valorCambio:0,
								});
								this.validarTotalMediosPagosV2();
								this.marcarCalculadora( this.objDetallePago[ this.objDetallePago.length - 1 ], this.objDetallePago.length - 1, 'metodo_pago' );
								this.cargarMetodosPagosSeleccionados();
								this.seleccionarMetodoPago = '';
							}
						// });
					},

					cambiarMetodoPagoMarcado(metodo){
						if (this.objDetallePago.length>0){
							var posicion = 0; 
							if (this.dicCalculado.marcador=='metodo_pago' && !app.vacios.includes(this.dicCalculado.posicion) && parseInt(this.dicCalculado.posicion)>0){
								posicion = parseInt(this.dicCalculado.posicion); 
							}
							var validar = alasql("select * from ? where metodo='"+metodo+"'", [this.objDetallePago]); 
							if (validar.length==0){
								var metodo = alasql("select * from ? where tipo_pago='"+metodo+"'", [app.objGlobalMetodosPagos])[0]; 
								this.objDetallePago[posicion].metodoPago__id = metodo.id;
								this.objDetallePago[posicion].metodo = metodo.tipo_pago;
							}

							if (!app.vacios.includes(this.objDetallePago[posicion].valor) && parseFloat(this.objDetallePago[posicion].valor)==0){
								this.llenarValorTotalMetodoPagoPedidoV2(this.objDetallePago[posicion], posicion, "metodo_pago"); 
							}
						}else{
							this.agregarMetodoPagoPedidoV2(); 
							this.cambiarMetodoPagoMarcado(metodo); 
						}
					}, 

					agregarMetodoPagoPedidoV3(){
						setTimeout(()=>{
							if (this.objDetallePago.length<3){
								this.validarTotalMediosPagosV2();
								var metodo = this.validarMetodoFaltante(); 
								var valorFaltante = this.dicPedidoDetalle.pedidoTotalNeto - this.totalPagoMedios;
								valorFaltante = ( valorFaltante <= -1 ) ? 0 : valorFaltante;
								this.objDetallePago.push({
									id:'', 
									metodo: metodo, 
									valor:valorFaltante,
									valorPagado:valorFaltante,
									valorCambio:0,
								});
								this.validarTotalMediosPagosV2();
								this.marcarCalculadora( this.objDetallePago[ this.objDetallePago.length - 1 ], this.objDetallePago.length - 1, 'metodo_pago' );
								this.cargarMetodosPagosSeleccionados();
								this.seleccionarMetodoPago = '';
							}
						});
					}, 

					validarMetodoFaltante(){
						var metodo = ''; 
						var metodos = alasql("select column id from ?", [app.objGlobalMetodosPagos]); 
						var agregados = alasql("select column metodoPago__id from ?", [this.objDetallePago]); 
						// console.log("agregados", agregados); 
						metodos.forEach((elemento)=>{
							if (metodo=='' && !agregados.includes(elemento)){
								metodo = elemento; 
							}
						}); 
						return metodo; 
					}, 

					validarMetodoFaltanteV1(){
						var metodo = ''; 
						var metodos = ['Efectivo', 'Transferencia', 'Tarjeta']; 
						var agregados = alasql("select column metodo from ?", [this.objDetallePago]); 
						metodos.forEach((elemento)=>{
							if (metodo=='' && !agregados.includes(elemento)){
								metodo = elemento; 
							}
						}); 
						return metodo; 
					}, 

					validarValorMetodosNoEfectivo(excluir){
						var consultaExcluir = ''; 
						if (!app.vacios.includes(excluir)){
							consultaExcluir = " and metodo!='" + excluir + "'"; 
						}
						var total = alasql(
							"select SUM( cast ( valor as float ) ) as sumaPagos from ? where valor>0 and metodo!='Efectivo'" + consultaExcluir, 
							[this.objDetallePago]
						)[0].sumaPagos;
						return total; 
					}, 
					
					validarValorMetodosEfectivo(){
						var total = alasql(
							"select SUM( cast ( valor as float ) ) as sumaPagos from ? where valor>0 and metodo='Efectivo'", 
							[this.objDetallePago]
						)[0].sumaPagos;
						return total; 
					}, 


					agregarMetodoPagoPedidoInicialV2(){
						setTimeout(()=>{
							this.validarTotalMediosPagosV2();
							var metodo = alasql("select * from ? where tipo_pago='Efectivo'", [app.objGlobalMetodosPagos]);
							if (metodo.length>0){
								metodo = metodo[0]; 
							}else{
								metodo = app.objGlobalMetodosPagos[0]; 
							}

							if ( this.totalPagoMedios <= this.dicPedidoDetalle.pedidoPrecioTotal ){
								this.objDetallePago.push({
									id:'', 
									metodoPago__id: metodo.id, 
									metodo: metodo.tipo_pago, 
									valor:0,
									valorPagado:0,
									valorCambio:0,
								});
								this.marcarCalculadora( this.objDetallePago[ this.objDetallePago.length - 1 ], this.objDetallePago.length - 1, 'metodo_pago' );
							}
							this.seleccionarMetodoPago = '';
						});
					}, 

					gestionarDescuentoCaculadorV2( ventana, valor, accion ){
						if (app.vacios.includes(this.dicPedidoDetalle.cuponId) && (!app.solicitarAutenticacionSiempre || (app.solicitarAutenticacionSiempre && app.rolResponsableAutenticacion=='Administrador'))){
							this.cambioRecienTocado = true;
							this.dicCalculado = {
								total: JSON.parse( JSON.stringify( this.dicPedidoDetalle.pedidoDescuento ) ), 
								totalStr: this.cantidadC( JSON.parse( JSON.stringify( this.dicPedidoDetalle.pedidoDescuento ) ) ), 
								posicion: 'descuento', 
								marcador: 'descuento', 
							};
						}
					}, 

					gestionarCalculadoraMetodosV2( ventana, valor, accion ){
						if ( this.dicCalculado.marcador == 'metodo_pago' ){
							if ( accion == 'agregar' ){
								if ( this.cambioRecienTocado ){ console.log("tocado recientenmente"); this.dicCalculado.total = '0'; this.cambioRecienTocado = false; }

								if ( ( this.dicCalculado.total == '0' && valor!='0' && valor!='00' ) || this.dicCalculado.total != '0' ){
									this.dicCalculado.total = ( this.dicCalculado.total != '0' ) ? this.dicCalculado.total + valor : valor;
									this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
									this.objDetallePago[ this.dicCalculado.posicion ].valor = JSON.parse( JSON.stringify( this.dicCalculado.total ) );

									if (this.objDetallePago[ this.dicCalculado.posicion ].metodo!='Efecivo'){
										this.validarTotalMediosPagosV2();
										if(this.validarValorMetodosNoEfectivo()>this.dicPedidoDetalle.pedidoTotalNeto){
											console.log("ajustar valor de metodo"); 
											this.objDetallePago[ this.dicCalculado.posicion ].valor = this.dicPedidoDetalle.pedidoTotalNeto - this.validarValorMetodosNoEfectivo(this.objDetallePago[ this.dicCalculado.posicion ].metodo); 
										} 
									}
								}
							}

							if ( accion == 'limpiar' ){
								this.dicCalculado.total = '0';
								this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
								this.objDetallePago[ this.dicCalculado.posicion ].valor = JSON.parse( JSON.stringify( this.dicCalculado.total ) );
							}

							if ( accion == 'borrar' ){
								this.dicCalculado.total = String( this.dicCalculado.total );
								if ( this.dicCalculado.total.length > 1 ){
									this.dicCalculado.total = this.dicCalculado.total.substr(0, this.dicCalculado.total.length-1);
								}else{
									this.dicCalculado.total = '0';
								}
								this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
								this.objDetallePago[ this.dicCalculado.posicion ].valor = JSON.parse( JSON.stringify( this.dicCalculado.total ) );
							}

							/* if ( (parseInt(this.dicCalculado.posicion) + 1) < this.objDetallePago.length ){
								this.ajustarTotalMediosPagos( this.dicCalculado.posicion );
							} */
							this.validarTotalMediosPagosV2();
						}else if ( this.dicCalculado.marcador == 'descuento' ){
							if ( accion == 'agregar' ){
								if ( this.cambioRecienTocado ){
									console.log("tocado recientenmente");
									this.dicCalculado.total = '0';
									this.cambioRecienTocado = false;
								}

								if ( ( this.dicCalculado.total == '0' && valor!='0' && valor!='00' ) || this.dicCalculado.total != '0' ){
									if ( this.dicCalculado.total != '0' ){
										if ( parseInt( this.dicCalculado.total + valor ) > 100 ){
											this.dicCalculado.total = this.dicCalculado.total;
										}else{
											this.dicCalculado.total = this.dicCalculado.total + valor;
										}
									}else{
										this.dicCalculado.total = valor;
									}
									this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
								}
								this.dicPedidoDetalle.propinaModificada = false;
							}

							if ( accion == 'limpiar' ){
								this.dicCalculado.total = '0';
								this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
								this.dicPedidoDetalle.propinaModificada = false;
							}


							if ( accion == 'borrar' ){
								this.dicCalculado.total = String( this.dicCalculado.total );
								if ( this.dicCalculado.total.length > 1 ){
									this.dicCalculado.total = this.dicCalculado.total.substr(0, this.dicCalculado.total.length-1);
								}else{
									this.dicCalculado.total = '0';
								}
								this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
								this.dicPedidoDetalle.propinaModificada = false;
							}

							this.dicPedidoDetalle.pedidoDescuento = parseInt( this.dicCalculado.total );
							this.calcularDescuentoSubtotalPedidoV2();
						}else  if ( this.dicCalculado.marcador == 'propina' && this.aplicarServicioPropina ){
							if ( accion == 'agregar' ){
								if ( this.cambioRecienTocado ){
									console.log("tocado recientenmente");
									this.dicCalculado.total = '0';
									this.cambioRecienTocado = false;
								}

								if ( ( this.dicCalculado.total == '0' && valor!='0' && valor!='00' ) || this.dicCalculado.total != '0' ){
									if ( this.dicCalculado.total != '0' ){
										
											this.dicCalculado.total = this.dicCalculado.total + valor;
									}else{
										this.dicCalculado.total = valor;
									}
									this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
								}
							}

							if ( accion == 'limpiar' ){
								this.dicCalculado.total = '0';
								this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
							}


							if ( accion == 'borrar' ){
								this.dicCalculado.total = String( this.dicCalculado.total );
								if ( this.dicCalculado.total.length > 1 ){
									this.dicCalculado.total = this.dicCalculado.total.substr(0, this.dicCalculado.total.length-1);
								}else{
									this.dicCalculado.total = '0';
								}
								this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
							}

							this.dicPedidoDetalle.pedidoPropinaValor = parseFloat( this.dicCalculado.total );
							this.calcularNuevoTotalPropina();
						}else  if ( this.dicCalculado.marcador == 'propina-porcentaje' && this.aplicarServicioPropina ){
							if ( accion == 'agregar' ){
								if ( this.cambioRecienTocado ){
									/* console.log("tocado recientenmente"); */
									this.dicCalculado.total = '0';
									this.cambioRecienTocado = false;
								}

								if ( ( this.dicCalculado.total == '0' && valor!='0' && valor!='00' ) || this.dicCalculado.total != '0' ){
									if ( this.dicCalculado.total != '0' ){
										this.dicCalculado.total = this.dicCalculado.total + valor;
									}else{
										this.dicCalculado.total = valor;
									}
									this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
								}
							}

							if ( accion == 'limpiar' ){
								this.dicCalculado.total = '0';
								this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
							}

							if ( accion == 'borrar' ){
								this.dicCalculado.total = String( this.dicCalculado.total );
								if ( this.dicCalculado.total.length > 1 ){
									this.dicCalculado.total = this.dicCalculado.total.substr(0, this.dicCalculado.total.length-1);
								}else{
									this.dicCalculado.total = '0';
								}
								this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
							}

							this.dicPedidoDetalle.porcentajePropina = parseFloat( this.dicCalculado.total );
							this.calcularNuevoTotalPropinaPorcentaje();
						}
					},

					calcularDescuentoSubtotalPedidoV2(){
						var vacios = [undefined, null, '', 'undefined', 'null', 'None'];
						/* this.calcularSubtotalDetallePedidoV2();
						this.calcularImpuestoDetallePedidoV2(); */
						if (!this.dicPedidoDetalle.ivaProducto){
							this.calcularSubtotalDetallePedidoV2();
							this.calcularImpuestosDetallePedido();
						}else{
							this.calcularSubtotalDetallePedidoV2IvaProducto(); 
							this.calcularImpuestosDetallePedidoIvaProducto(); 
							this.calcularIMpuestoDetallePedidoProducto(); 
						}

						if ( this.aplicarServicioPropina && !this.dicPedidoDetalle.propinaModificada ){
							this.dicPedidoDetalle.pedidoPropinaValor = ( (this.dicPedidoDetalle.pedidoSubTotal) * (this.dicConfiguracionVenta.porcentajeServicio/100) );
						}
						this.calcularTotalAPagarPedido();
						this.reiniciarMetodosPagosCero();
						this.convertirValoresPedidoMonedaCurrency();
						this.calcularCambioPagoV2();
					}, 

					calcularNuevoTotalPropina(){
						var valor = this.dicPedidoDetalle.pedidoPropinaValor; 
						this.dicPedidoDetalle.propinaModificada = false;
						if ( this.dicPedidoDetalle.pedidoPropinaValor > 0 ){
							this.dicPedidoDetalle.propinaModificada = true;
						}

						this.dicPedidoDetalle.porcentajePropina = ((valor*100)/(this.dicPedidoDetalle.pedidoSubTotal));
						this.dicPedidoDetalle.porcentajePropina = parseFloat(this.dicPedidoDetalle.porcentajePropina); 

						this.calcularTotalAPagarPedido();
						this.reiniciarMetodosPagosCero();
						this.validarTotalMediosPagosV2();
						this.convertirValoresPedidoMonedaCurrency();
						this.calcularCambioPagoV2();
					}, 

					calcularNuevoTotalPropinaPorcentaje(){
						var porcentaje = this.dicPedidoDetalle.porcentajePropina; 
						this.dicPedidoDetalle.propinaModificada = false;
						if ( porcentaje > 0 ){
							this.dicPedidoDetalle.propinaModificada = true;
						}

						this.dicPedidoDetalle.pedidoPropinaValor = ( (this.dicPedidoDetalle.pedidoSubTotal) * (porcentaje/100) );
						this.dicPedidoDetalle.pedidoPropinaValor = parseFloat(this.dicPedidoDetalle.pedidoPropinaValor); 

						this.calcularTotalAPagarPedido();
						this.reiniciarMetodosPagosCero();
						this.convertirValoresPedidoMonedaCurrency();
						this.calcularCambioPagoV2();
					},

					reiniciarMetodosPagosCero(){
						console.log("SE REINICIA A CERO METODOS DE PAGOS"); 
						this.objDetallePago.forEach((elemento)=>{
							elemento.valor = 0; 
							elemento.valorPagado = 0; 
							elemento.valorCambio = 0; 
						}); 
						this.validarTotalMediosPagosV2();
					}, 


					convertirValoresPedidoMonedaCurrency(){
						this.dicPedidoDetalle.pedidoSubTotalConDescuentoStr = this.moneda( this.dicPedidoDetalle.pedidoSubTotalConDescuento );
						this.dicPedidoDetalle.pedidoTotalDescuentoStr = this.moneda( this.dicPedidoDetalle.pedidoTotalDescuento );
						this.dicPedidoDetalle.pedidoPropinaValorStr = this.moneda( this.dicPedidoDetalle.pedidoPropinaValor );
						this.dicPedidoDetalle.pedidoSubTotalStr = this.moneda( this.dicPedidoDetalle.pedidoSubTotal );
						this.dicPedidoDetalle.pedidoPrecioTotalProductosStr = this.moneda( this.dicPedidoDetalle.pedidoPrecioTotalProductos );
						this.dicPedidoDetalle.pedidoCambioPagoStr = this.moneda( this.dicPedidoDetalle.pedidoCambioPago );
						this.dicPedidoDetalle.pedidoValorImpuestoStr = this.moneda( this.dicPedidoDetalle.pedidoValorImpuesto );
						this.dicPedidoDetalle.pedidoPrecioTotalStr = this.moneda( this.dicPedidoDetalle.pedidoPrecioTotal );
						this.dicPedidoDetalle.pedidoTotalNetoStr = this.moneda( this.dicPedidoDetalle.pedidoTotalNeto );
						this.dicPedidoDetalle.pedidoRestanteStr = this.moneda( this.dicPedidoDetalle.pedidoRestante );
						this.dicPedidoDetalle.pedidoCambioPagoGuardadoStr = this.moneda( this.dicPedidoDetalle.pedidoCambioPagoGuardado );
						this.totalPagoMediosStr = this.moneda( this.totalPagoMedios );
					}, 

					convertirValoresPedidoMonedaCurrencyVerSolamente(){
						this.totalPagoMedios = parseFloat(this.dicPedidoDetalle.pedidoValorPagado); 
						console.log(" totalPagoMedios ", this.totalPagoMedios);
						console.log(" pedidoCambioPago ", this.dicPedidoDetalle.pedidoCambioPago);

						this.dicPedidoDetalle.pedidoSubTotalConDescuentoStr = this.moneda( this.dicPedidoDetalle.pedidoSubTotalConDescuento );
						this.dicPedidoDetalle.pedidoTotalDescuentoStr = this.moneda( this.dicPedidoDetalle.pedidoTotalDescuento );
						this.dicPedidoDetalle.pedidoPropinaValorStr = this.moneda( this.dicPedidoDetalle.pedidoPropinaValor );
						this.dicPedidoDetalle.pedidoSubTotalStr = this.moneda( this.dicPedidoDetalle.pedidoSubTotal );
						this.dicPedidoDetalle.pedidoPrecioTotalProductosStr = this.moneda( this.dicPedidoDetalle.pedidoPrecioTotalProductos );
						this.dicPedidoDetalle.pedidoCambioPagoStr = this.moneda( this.dicPedidoDetalle.pedidoCambioPago );
						this.dicPedidoDetalle.pedidoValorImpuestoStr = this.moneda( this.dicPedidoDetalle.pedidoValorImpuesto );
						this.dicPedidoDetalle.pedidoPrecioTotalStr = this.moneda( this.dicPedidoDetalle.pedidoPrecioTotal );
						this.dicPedidoDetalle.pedidoTotalNetoStr = this.moneda( this.dicPedidoDetalle.pedidoTotalNeto );
						this.dicPedidoDetalle.pedidoRestanteStr = this.moneda( this.dicPedidoDetalle.pedidoRestante );
						this.dicPedidoDetalle.pedidoCambioPagoGuardadoStr = this.moneda( this.dicPedidoDetalle.pedidoCambioPagoGuardado );
						this.totalPagoMediosStr = this.moneda( this.dicPedidoDetalle.pedidoValorPagado );
						// pedidoCambioPagoStr  pedidoCambioPago
					}, 

					abrirModalDividirCuenta( ventana ){
						this.numeroPersonas = ( this.objDivicionCuentaCopia.length > 0 ) ? String(this.objDivicionCuentaCopia.length) : '';
						this.objDivicionCuenta = JSON.parse( JSON.stringify( this.objDivicionCuentaCopia) );
						this.totalEfectivoDivision = 0; this.totalTarjetaDivision = 0; this.totalTransferenciaDivision = 0;
						this.tituloModalDividirCuenta = "Dividir Cuenta"; 
						this.marcarCalculadoraDivicionCuenta({valor:0}, '', 'divicion');
						this.calcularTotalesMetodosDivisionCuenta();
						this.showModal( ventana );
					}, 

					abrirModalAgregarComensales( ventana ){
						this.totalComensales = parseInt(JSON.parse(JSON.stringify(this.dicPedidoDetalle.comensales))); 
						this.promedioConsumoComensales = this.dicPedidoDetalle.pedidoTotalNeto/this.totalComensales; 
						this.tituloModalDividirCuenta = "Agregar Comensales"; 
						var datos = {valor:this.dicPedidoDetalle.comensales}; 
						this.marcarCalculadoraDivicionCuenta(datos, '', 'comensales');
						this.showModal( ventana );
					}, 

					generarDivicionCuenta(){
						if ( this.numeroPersonas == '' ){
							this.objDivicionCuenta = [];
						}else if ( parseInt( this.numeroPersonas ) > 0 ){
							this.cambioRecienTocadoDivision = true;
							this.objDivicionCuenta = []; var totalDivision = 0; var metodoPrincipal = []; 
							var divicion = this.dicPedidoDetalle.pedidoTotalNeto / parseInt( this.numeroPersonas );
							if (this.objDetallePago.length>0){
								metodoPrincipal = this.objDetallePago[0]; 
								metodoPrincipal = alasql("select * from ? where id="+metodoPrincipal.metodoPago__id, [app.objGlobalMetodosPagos]); 
							}
							
							if (metodoPrincipal.length==0){ metodoPrincipal = app.objGlobalMetodosPagos[0]; }else{ metodoPrincipal = metodoPrincipal[0]; }

							for ( var i = 0; i < parseInt( this.numeroPersonas ); i++ ){
								if ( ( i + 1 ) == parseInt(this.numeroPersonas) ){ 
									divicion = this.dicPedidoDetalle.pedidoTotalNeto - parseFloat(app.$options.filters.currency(totalDivision, "").replaceAll(",", "")); 
								}else{
									totalDivision = totalDivision + parseFloat(app.$options.filters.currency(divicion, "").replaceAll(",", ""));
								}

								this.objDivicionCuenta.push({
									id:'', 
									metodoPago__id: metodoPrincipal.id, 
									metodo: metodoPrincipal.tipo_pago, 
									valor: parseFloat(app.$options.filters.currency(divicion, "").replaceAll(",", "")), 
									valorStr: this.moneda(parseFloat(app.$options.filters.currency(divicion, "").replaceAll(",", ""))), 
									cambio: 0, 
									cambioStr: this.moneda(0), 
								});
							}
							console.log("Total dividido ", totalDivision);
						}
					}, 

					generarDivicionCuentaV1(){
						if ( this.numeroPersonas == '' ){
							this.objDivicionCuenta = [];
						}else if ( parseInt( this.numeroPersonas ) > 0 ){
							this.cambioRecienTocadoDivision = true;
							this.objDivicionCuenta = []; var totalDivision = 0;
							var divicion = this.dicPedidoDetalle.pedidoTotalNeto / parseInt( this.numeroPersonas );
							for ( var i = 0; i < parseInt( this.numeroPersonas ); i++ ){
								totalDivision = totalDivision + Math.round(divicion);
								if ( ( i + 1 ) == parseInt(this.numeroPersonas) ){
									divicion = this.dicPedidoDetalle.pedidoTotalNeto - Math.round(divicion) * i;
								}
								this.objDivicionCuenta.push({
									id:'', 
									metodo: 'Tarjeta', 
									valor: divicion, 
									valorStr: this.moneda(divicion), 
									cambio: 0, 
									cambioStr: this.moneda(0), 
								});
							}
						}
					}, 

					ajustarTotalDivicionCuenta( posicionModificado ){
						var totalDivision = 0; var divicionFacturaMetodosPagos = 0; var valorRestante = 0;
						this.objDivicionCuenta.forEach(( elemento, posicion )=>{
							if ( posicion > parseInt(posicionModificado) ){
								totalDivision = totalDivision + Math.round(divicionFacturaMetodosPagos);
								if ( ( posicion + 1 ) == this.objDivicionCuenta.length ){
									divicionFacturaMetodosPagos = (divicionFacturaMetodosPagos>0) ? valorRestante - (Math.round(divicionFacturaMetodosPagos) * (posicion - (posicionModificado+1))) : 0;
								}else{
								}
								this.objDivicionCuenta[ posicion ].valor = Math.round(divicionFacturaMetodosPagos);
							}else{
								totalDivision = parseFloat(totalDivision) + parseFloat(this.objDivicionCuenta[ posicion ].valor);
								console.log(" ---totalDivision--- ", totalDivision);
								valorRestante = ( valorRestante === 0 ) ? this.dicPedidoDetalle.pedidoTotalNeto - this.objDivicionCuenta[ posicion ].valor : valorRestante - this.objDivicionCuenta[ posicion ].valor;
								console.log(" ---valorRestante--- ", valorRestante);
								divicionFacturaMetodosPagos = (totalDivision >= this.dicPedidoDetalle.pedidoTotalNeto) ? 0 : valorRestante / ( this.objDivicionCuenta.length - ( posicion + 1 ) );
								console.log(" ---divicionFacturaMetodosPagos--- ", divicionFacturaMetodosPagos);
							}
						});
					}, 


					marcarCalculadoraDivicionCuenta( datos, posicion, marcador ){
						setTimeout(()=>{
							if (!app.vacios.includes(datos.metodoPago__id)){
								var metodo = alasql("select * from ? where id="+datos.metodoPago__id, [app.objGlobalMetodosPagos])[0]; 
								this.objDivicionCuenta[ posicion ].metodo = metodo.tipo_pago; 
							}

							this.cambioRecienTocadoDivision = true;
							this.dicCalculadoDivicion = {
								total: JSON.parse( JSON.stringify( datos.valor ) ), 
								totalStr: this.cantidadC( JSON.parse( JSON.stringify( datos.valor ) ) ), 
								posicion: posicion, 
								marcador: marcador, 
							};
						});
					},

					gestionarCalculadoraDivicionCuenta( ventana, valor, accion ){
						if ( this.dicCalculadoDivicion.marcador == 'divicion' ){
							if ( accion == 'agregar' ){
								if ( this.cambioRecienTocadoDivision ){ this.dicCalculadoDivicion.total = '0'; this.cambioRecienTocadoDivision = false; }

								if ( ( this.dicCalculadoDivicion.total == '0' && valor!='0' && valor!='00' ) || this.dicCalculadoDivicion.total != '0' ){
									this.dicCalculadoDivicion.total = ( this.dicCalculadoDivicion.total != '0' ) ? this.dicCalculadoDivicion.total + valor : valor;
									this.dicCalculadoDivicion.totalStr = this.cantidadC( this.dicCalculadoDivicion.total );
									this.objDivicionCuenta[ this.dicCalculadoDivicion.posicion ].valor = JSON.parse( JSON.stringify( this.dicCalculadoDivicion.total ) );
									
									if (this.objDivicionCuenta[ this.dicCalculadoDivicion.posicion ].metodo!='Efecivo'){
										if(this.validarValorDividirNoEfectivo()>this.dicPedidoDetalle.pedidoTotalNeto){
											this.objDivicionCuenta[ this.dicCalculadoDivicion.posicion ].valor = this.dicPedidoDetalle.pedidoTotalNeto - this.validarValorDividirNoEfectivo(this.dicCalculadoDivicion.posicion); 
										} 
									}

									this.objDivicionCuenta[ this.dicCalculadoDivicion.posicion ].valorStr = this.moneda( JSON.parse( JSON.stringify( this.objDivicionCuenta[ this.dicCalculadoDivicion.posicion ].valor ) ) );
								}
							}

							if ( accion == 'limpiar' ){
								this.dicCalculadoDivicion.total = '0';
								this.dicCalculadoDivicion.totalStr = this.cantidadC( this.dicCalculadoDivicion.total );
								this.objDivicionCuenta[ this.dicCalculadoDivicion.posicion ].valor = JSON.parse( JSON.stringify( this.dicCalculadoDivicion.total ) );
								this.objDivicionCuenta[ this.dicCalculadoDivicion.posicion ].valorStr = this.moneda( JSON.parse( JSON.stringify( this.dicCalculadoDivicion.total ) ) );
							}

							if ( accion == 'borrar' ){
								this.dicCalculadoDivicion.total = String( this.dicCalculadoDivicion.total );
								if ( this.dicCalculadoDivicion.total.length > 1 ){
									this.dicCalculadoDivicion.total = this.dicCalculadoDivicion.total.substr(0, this.dicCalculadoDivicion.total.length-1);
								}else{
									this.dicCalculadoDivicion.total = '0';
								}
								this.dicCalculadoDivicion.totalStr = this.cantidadC( this.dicCalculadoDivicion.total );
								this.objDivicionCuenta[ this.dicCalculadoDivicion.posicion ].valor = JSON.parse( JSON.stringify( this.dicCalculadoDivicion.total ) );
								this.objDivicionCuenta[ this.dicCalculadoDivicion.posicion ].valorStr = this.moneda( JSON.parse( JSON.stringify( this.dicCalculadoDivicion.total ) ) );
							}

							/* if ( (parseInt(this.dicCalculadoDivicion.posicion) + 1) < this.objDivicionCuenta.length ){
								this.ajustarTotalDivicionCuenta( this.dicCalculadoDivicion.posicion );
							} */
							this.calcularTotalesMetodosDivisionCuenta();
						}else if ( this.dicCalculadoDivicion.marcador == 'comensales' ){
							if ( accion == 'agregar' ){
								if ( ( this.dicCalculadoDivicion.total == '0' && valor!='0' && valor!='00' ) || this.dicCalculadoDivicion.total != '0' ){
									this.dicCalculadoDivicion.total = ( this.dicCalculadoDivicion.total != '0' ) ? this.dicCalculadoDivicion.total + valor : valor;
									this.totalComensales = parseInt(JSON.parse( JSON.stringify( this.dicCalculadoDivicion.total ) ));
								}
							}

							if ( accion == 'limpiar' ){
								this.dicCalculadoDivicion.total = '0';
								this.totalComensales = parseInt(JSON.parse( JSON.stringify( this.dicCalculadoDivicion.total ) ));
							}

							if ( accion == 'borrar' ){
								this.dicCalculadoDivicion.total = String( this.dicCalculadoDivicion.total );
								if ( this.dicCalculadoDivicion.total.length > 1 ){
									this.dicCalculadoDivicion.total = this.dicCalculadoDivicion.total.substr(0, this.dicCalculadoDivicion.total.length-1);
								}else{
									this.dicCalculadoDivicion.total = '0';
								}
								this.totalComensales = parseInt(JSON.parse( JSON.stringify( this.dicCalculadoDivicion.total ) ));
							}

							this.calcularPromedioConsunmoComensales(); 
						}
					}, 

					calcularPromedioConsunmoComensales(){
						this.promedioConsumoComensales = (!app.vacios.includes(this.totalComensales) && parseInt(this.totalComensales)>0) ? this.dicPedidoDetalle.pedidoTotalNeto/this.totalComensales : 0; 
					}, 

					validarValorDividirNoEfectivo(posicion){
						var objDivicionCuenta = JSON.parse(JSON.stringify(this.objDivicionCuenta)); 
						if (!app.vacios.includes(posicion)){
							objDivicionCuenta.splice(posicion, 1); 
							console.log("posicion ", posicion, objDivicionCuenta.length); 
						}
						var total = alasql(
							"select SUM( cast ( valor as float ) ) as sumaPagos from ? where valor>0 and metodo!='Efectivo'", [objDivicionCuenta]
						)[0].sumaPagos;
						return total; 
					}, 
					
					calcularTotalesMetodosDivisionCuenta(){
						var metodoDivision = alasql( "select column metodoPago__id from ?", [ this.objDivicionCuenta ] ); 
						var sumatoria = []; var set = new Set(metodoDivision);
						metodoDivision = Array.from(set); 
						metodoDivision.forEach((elemento)=>{
							var metodo = alasql( "select * from ? where id="+elemento, [ app.objGlobalMetodosPagos] )[0]; 
							var total = alasql( "select sum( cast( valor as float ) ) as suma from ? where metodoPago__id="+elemento, [ this.objDivicionCuenta ] )[0].suma;
							sumatoria.push({
								metodoPago__id:elemento, 
								metodo: metodo.tipo_pago, 
								valor: total, 
							});
						});

						return sumatoria; 
					},

					calcularTotalesMetodosDivisionCuentaV1(){
						this.totalEfectivoDivision = alasql( "select sum( cast( valor as float ) ) as suma from ? where metodo='Efectivo'", [ this.objDivicionCuenta ] )[0].suma;
						this.totalTarjetaDivision = alasql( "select sum( cast( valor as float ) ) as suma from ? where metodo='Tarjeta'", [ this.objDivicionCuenta ] )[0].suma;
						this.totalTransferenciaDivision = alasql( "select sum( cast( valor as float ) ) as suma from ? where metodo='Transferencia'", [ this.objDivicionCuenta ] )[0].suma;
						// console.log("Efectivo ", this.totalEfectivoDivision);
						// console.log("Tarjeta ", this.totalTarjetaDivision);
						// console.log("Transferencia ", this.totalTransferenciaDivision);
					},

					confirmarAgregarDivicionCuenta( ventana ){
						var sumatoria = this.calcularTotalesMetodosDivisionCuenta();
						this.objDetallePago = [];
						sumatoria.forEach((elemento)=>{
							this.objDetallePago.push({ 
								id:'', metodo: elemento.metodo, metodoPago__id: elemento.metodoPago__id, 
								valor:elemento.valor, 
							});
						});
						this.objDivicionCuentaCopia = JSON.parse( JSON.stringify( this.objDivicionCuenta ) );
						this.validarTotalMediosPagosV2();
						this.hideModal( ventana );
					}, 

					confirmarAgregarDivicionCuentaV1( ventana ){
						this.calcularTotalesMetodosDivisionCuenta();
						this.objDetallePago = [];
						var efectivo = false; var tarjeta = false; var transferencia = false;
						this.objDetallePago.forEach(( elemento )=>{
							if ( elemento.metodo == 'Efectivo' ){
								efectivo = true;
								elemento.valor = this.totalEfectivoDivision;
							}if ( elemento.metodo == 'Tarjeta' ){
								tarjeta = true;
								elemento.valor = this.totalTarjetaDivision;
							}if ( elemento.metodo == 'Transferencia' ){
								transferencia = true;
								elemento.valor = this.totalTransferenciaDivision;
							}
						});

						if ( !efectivo && this.totalEfectivoDivision > 0 ){ this.objDetallePago.push({ id:'', metodo: 'Efectivo', valor:this.totalEfectivoDivision, }); }
						if ( !tarjeta && this.totalTarjetaDivision > 0 ){ this.objDetallePago.push({ id:'', metodo: 'Tarjeta', valor:this.totalTarjetaDivision, }); }
						if ( !transferencia && this.totalTransferenciaDivision > 0 ){ this.objDetallePago.push({ id:'', metodo: 'Transferencia', valor:this.totalTransferenciaDivision, }); }
						this.objDivicionCuentaCopia = JSON.parse( JSON.stringify( this.objDivicionCuenta ) );
						this.validarTotalMediosPagosV2();
						this.hideModal( ventana );
					}, 

					confirmarAgregarComensalesPedido(ventana){
						if (app.vacios.includes(this.totalComensales) || parseInt(this.totalComensales)<=0){
							this.totalComensales = 1; 
						}
						this.dicPedidoDetalle.comensales = parseInt(this.totalComensales); 
						this.dicPedidoDetalle.totalPromedioConsumo = this.promedioConsumoComensales; 
						this.hideModal( ventana );
					}, 

					gestionarDescuentoProductoDetalleRow(item){
						if (this.dicPedidoDetalle.pedidoEstado=='Finalizado' && this.modoDividirFacturaPedido){
							var productos = alasql("select column referencia from ?", [this.objDetalleProductosPedido]); 
							var posicion = productos.indexOf(item.referencia); 
							this.gestionarDescuentoProductoDetalle(item, posicion, ''); 
						}
					}, 

					gestionarDescuentoProductoDetalle( item, posicion, marcador ){
						/*console.log("ITEM ", item);*/
						this.dicCalculadoDescuentoDetalle = { total:'', totalStr:'', posicion:'', marcador: '', };
						this.dicDetallePedidoDescuento = JSON.parse( JSON.stringify( item ) );
						this.dicDetallePedidoDescuento['productoCantidadStr'] = this.cantidadC(item.productoCantidad);
						this.dicDetallePedidoDescuento['detalleDescuentoStr'] = this.cantidadC(item.detalleDescuento);
						this.dicDetallePedidoDescuento['detalleValorDescuentoStr'] = this.moneda(item.detalleValorDescuento);
						this.dicDetallePedidoDescuento['productoPrecioVentaStr'] = this.moneda(item.productoPrecioVenta);
						this.dicDetallePedidoDescuento['productoPrecionTotalStr'] = this.moneda(item.productoPrecionTotal);
						this.dicDetallePedidoDescuento['posicion'] = posicion;

						this.detalleDescuentoRealizar = item.detalleDescuento;
						this.detalleDescuentoRealizarStr = this.cantidadC(item.detalleDescuento);

						this.detalleValorDescuentoRealizar = item.detalleValorDescuento;
						this.detalleValorDescuentoRealizarStr = this.cantidadC(item.detalleValorDescuento);
						
						this.detalleValorPrecioVentaRealizar = item.productoPrecioVenta;
						this.detalleValorPrecioVentaRealizarStr = this.cantidadC(item.productoPrecioVenta);

						this.detalleCantidadRealizar = item.productoCantidad;

						this.marcarCalculadoraDescuentoProductoDetalle( this.detalleDescuentoRealizar, 'descuento', 'descuento' );
						this.showModal("modalDescuentoProductoDetalle");
					},

					marcarCalculadoraDescuentoProductoDetalle( valor, posicion, marcador ){
						if (
							!this.modoDividirFacturaPedido || 
							(this.modoDividirFacturaPedido && (marcador!='cantidad-detalle' || (marcador=='cantidad-detalle' && this.dicDetallePedidoDescuento.totalProductosContenidos==0)))
						){
							/*console.log("VALOR ", valor);*/
							this.cambioRecienTocadoDivision = true;
							setTimeout(()=>{
								this.dicCalculadoDescuentoDetalle = {
									total: '', 
									totalStr: '', 
									posicion: posicion, 
									marcador: marcador, 
								};
							});
						}
					},

					gestionarCalculadoraDescuentoDetalleProducto( ventana, valor, accion ){
						setTimeout(()=>{
							console.log("ORDEN_ ", valor, "__", accion);
							if ( this.dicCalculadoDescuentoDetalle.posicion == 'descuento' ){
								if ( accion == 'agregar' ){
									if ( this.cambioRecienTocadoDivision ){
										console.log("tocado recientenmente");
										this.detalleDescuentoRealizar = '0';
										this.cambioRecienTocadoDivision = false;
									}

									this.detalleDescuentoRealizar = parseFloat(this.detalleDescuentoRealizar);
									if ( this.detalleDescuentoRealizar === 0 ){
										this.detalleDescuentoRealizar = valor;
									}else if ( this.detalleDescuentoRealizar > 0 && this.detalleDescuentoRealizar <= 100 ){
										this.detalleDescuentoRealizar = this.detalleDescuentoRealizar + "" + valor;
									}
									if ( parseFloat( this.detalleDescuentoRealizar ) > 100 ){ 
										this.detalleDescuentoRealizar = 100; 
									}
									this.detalleDescuentoRealizar = parseFloat(this.detalleDescuentoRealizar);
									this.detalleDescuentoRealizarStr = this.cantidadC(this.detalleDescuentoRealizar);
								}

								if ( accion == 'limpiar' ){
									this.detalleDescuentoRealizar = 0;
									this.detalleDescuentoRealizarStr = this.cantidadC(this.detalleDescuentoRealizar);
								}

								if ( accion == 'borrar' ){
									this.detalleDescuentoRealizar = String(this.detalleDescuentoRealizar);
									if ( this.detalleDescuentoRealizar.length > 1 ){
										this.detalleDescuentoRealizar = this.detalleDescuentoRealizar.substr(0, this.detalleDescuentoRealizar.length-1);
									}else{
										this.detalleDescuentoRealizar = '0';
									}
									
									this.detalleDescuentoRealizar = parseFloat(this.detalleDescuentoRealizar);
									this.detalleDescuentoRealizarStr = this.cantidadC(this.detalleDescuentoRealizar);
								}

								var precio = this.detalleValorPrecioVentaRealizar;
								var cantidad = this.detalleCantidadRealizar; 
								this.detalleValorDescuentoRealizar = ((precio * cantidad) * (this.detalleDescuentoRealizar/100));
								this.detalleValorDescuentoRealizarStr = this.moneda(this.detalleValorDescuentoRealizar);
								console.log("descuento hecho ----- ", this.detalleValorDescuentoRealizar );

								this.dicDetallePedidoDescuento.productoPrecionTotal = (precio * cantidad) - this.detalleValorDescuentoRealizar;
								this.dicDetallePedidoDescuento.productoPrecionTotalStr = this.moneda(this.dicDetallePedidoDescuento.productoPrecionTotal);
							}else if ( this.dicCalculadoDescuentoDetalle.posicion == 'valor' ){
								var precio = this.detalleValorPrecioVentaRealizar;
								var cantidad = this.detalleCantidadRealizar;
								console.log("cantidad ----- ", cantidad);
								if ( accion == 'agregar' ){
									if ( this.cambioRecienTocadoDivision ){
										console.log("tocado recientenmente");
										this.detalleValorDescuentoRealizar = '0';
										this.cambioRecienTocadoDivision = false;
									}

									this.detalleValorDescuentoRealizar = parseFloat(this.detalleValorDescuentoRealizar);
									if ( this.detalleValorDescuentoRealizar === 0 ){
										this.detalleValorDescuentoRealizar = valor;
									}else if ( this.detalleValorDescuentoRealizar > 0 && this.detalleValorDescuentoRealizar <= (precio * cantidad) ){
										this.detalleValorDescuentoRealizar = this.detalleValorDescuentoRealizar + "" + valor;
									}
									if ( parseFloat( this.detalleValorDescuentoRealizar ) > (precio * cantidad) ){ 
										this.detalleValorDescuentoRealizar = (precio * cantidad); 
									}
									this.detalleValorDescuentoRealizar = parseFloat(this.detalleValorDescuentoRealizar);
									this.detalleValorDescuentoRealizarStr = this.moneda(this.detalleValorDescuentoRealizar);
								}

								if ( accion == 'limpiar' ){
									this.detalleValorDescuentoRealizar = 0									
									this.detalleValorDescuentoRealizarStr = this.moneda(this.detalleValorDescuentoRealizar);
								}

								if ( accion == 'borrar' ){
									this.detalleValorDescuentoRealizar = String(this.detalleValorDescuentoRealizar);
									if ( this.detalleValorDescuentoRealizar.length > 1 ){
										this.detalleValorDescuentoRealizar = this.detalleValorDescuentoRealizar.substr(0, this.detalleValorDescuentoRealizar.length-1);
									}else{
										this.detalleValorDescuentoRealizar = '0';
									}
									
									this.detalleValorDescuentoRealizar = parseFloat(this.detalleValorDescuentoRealizar);
									this.detalleValorDescuentoRealizarStr = this.cantidadC(this.detalleValorDescuentoRealizar);
								}

								/*this.detalleDescuentoRealizar = ((100*this.detalleValorDescuentoRealizar)/(precio * cantidad));*/
								this.detalleDescuentoRealizar = ( (precio * cantidad) === 0 ) ? 0 : ((100*this.detalleValorDescuentoRealizar)/(precio * cantidad));

								this.detalleDescuentoRealizarStr = this.cantidadC(this.detalleDescuentoRealizar);
								this.dicDetallePedidoDescuento.productoPrecionTotal = (precio * cantidad) - this.detalleValorDescuentoRealizar;
								this.dicDetallePedidoDescuento.productoPrecionTotalStr = this.moneda(this.dicDetallePedidoDescuento.productoPrecionTotal);
							}else if ( this.dicCalculadoDescuentoDetalle.posicion == 'precio' ){
								var precio = this.detalleValorPrecioVentaRealizar;
								var cantidad = this.detalleCantidadRealizar;
								if ( accion == 'agregar' ){
									if ( this.cambioRecienTocadoDivision ){
										console.log("tocado recientenmente");
										this.detalleValorPrecioVentaRealizar = '0';
										this.cambioRecienTocadoDivision = false;
									}

									this.detalleValorPrecioVentaRealizar = parseFloat(this.detalleValorPrecioVentaRealizar);
									if ( this.detalleValorPrecioVentaRealizar === 0 ){
										this.detalleValorPrecioVentaRealizar = valor;
									/* }else if ( this.detalleValorPrecioVentaRealizar > 0 && this.detalleValorPrecioVentaRealizar <= (precio * cantidad) ){ */
									}else{
										this.detalleValorPrecioVentaRealizar = this.detalleValorPrecioVentaRealizar + "" + valor;
									}
									/* if ( parseFloat( this.detalleValorPrecioVentaRealizar ) > (precio * cantidad) ){ 
										this.detalleValorPrecioVentaRealizar = (precio * cantidad); 
									} */
									this.detalleValorPrecioVentaRealizar = parseFloat(this.detalleValorPrecioVentaRealizar);
									this.detalleValorPrecioVentaRealizarStr = this.moneda(this.detalleValorPrecioVentaRealizar);
								}

								if ( accion == 'limpiar' ){
									console.log("limpiar");
									this.detalleValorPrecioVentaRealizar = 0									
									this.detalleValorPrecioVentaRealizarStr = this.moneda(this.detalleValorPrecioVentaRealizar);
								}

								if ( accion == 'borrar' ){
									console.log("borrar");
									this.detalleValorPrecioVentaRealizar = String(this.detalleValorPrecioVentaRealizar);
									if ( this.detalleValorPrecioVentaRealizar.length > 1 ){
										this.detalleValorPrecioVentaRealizar = this.detalleValorPrecioVentaRealizar.substr(0, this.detalleValorPrecioVentaRealizar.length-1);
									}else{
										this.detalleValorPrecioVentaRealizar = '0';
									}
									
									this.detalleValorPrecioVentaRealizar = parseFloat(this.detalleValorPrecioVentaRealizar);
									this.detalleValorPrecioVentaRealizarStr = this.cantidadC(this.detalleValorPrecioVentaRealizar);
								}
								
								var precio = this.detalleValorPrecioVentaRealizar;
								var cantidad = this.detalleCantidadRealizar;

								// this.detalleDescuentoRealizar = ( (precio * cantidad) === 0 ) ? 0 : ((100*this.detalleValorDescuentoRealizar)/(precio * cantidad));
								this.detalleValorDescuentoRealizar = ((precio * cantidad) * (this.detalleDescuentoRealizar/100));
								this.detalleValorDescuentoRealizarStr = this.moneda(this.detalleValorDescuentoRealizar);

								this.detalleDescuentoRealizarStr = this.cantidadC(this.detalleDescuentoRealizar);
								this.dicDetallePedidoDescuento.productoPrecionTotal = (precio * cantidad) - this.detalleValorDescuentoRealizar;
								this.dicDetallePedidoDescuento.productoPrecionTotalStr = this.moneda(this.dicDetallePedidoDescuento.productoPrecionTotal);
							}else if ( this.dicCalculadoDescuentoDetalle.posicion == 'cantidad-detalle' ){
								var precio = this.detalleValorPrecioVentaRealizar;
								var cantidad = this.dicDetallePedidoDescuento.productoCantidad;
								if ( accion == 'agregar' ){
									if ( this.cambioRecienTocadoDivision ){
										this.detalleCantidadRealizar = '0'; this.cambioRecienTocadoDivision = false;
									}

									this.detalleCantidadRealizar = parseFloat(this.detalleCantidadRealizar);
									if ( this.detalleCantidadRealizar === 0 ){
										this.detalleCantidadRealizar = valor;
									}else{
										this.detalleCantidadRealizar = this.detalleCantidadRealizar + "" + valor;
									}

									this.detalleCantidadRealizar = parseFloat(this.detalleCantidadRealizar);
								}

								if ( accion == 'limpiar' ){ this.detalleCantidadRealizar = 0; }

								if ( accion == 'borrar' ){
									this.detalleCantidadRealizar = String(this.detalleCantidadRealizar);
									if ( this.detalleCantidadRealizar.length > 1 ){
										this.detalleCantidadRealizar = this.detalleCantidadRealizar.substr(0, this.detalleCantidadRealizar.length-1);
									}else{
										this.detalleCantidadRealizar = '0';
									}
									
									this.detalleCantidadRealizar = parseFloat(this.detalleCantidadRealizar);
								}
								
								var cantidad = this.detalleCantidadRealizar;
								var precio = this.detalleValorPrecioVentaRealizar;

								this.detalleValorDescuentoRealizar = ((precio * cantidad) * (this.detalleDescuentoRealizar/100));
								this.detalleValorDescuentoRealizarStr = this.moneda(this.detalleValorDescuentoRealizar);
								this.dicDetallePedidoDescuento.productoPrecionTotal = (precio * cantidad) - this.detalleValorDescuentoRealizar;
								this.dicDetallePedidoDescuento.productoPrecionTotalStr = this.moneda(this.dicDetallePedidoDescuento.productoPrecionTotal);
							}
						}, 1);
					}, 

					guardarCambiosDescuentoProductoDetalle( ventana ){
						var vacios = [undefined, null, '', 'undefined', 'null', 'None'];
						var posicion = this.dicDetallePedidoDescuento.posicion;
						var precio = this.detalleValorPrecioVentaRealizar;
						var cantidad = this.detalleCantidadRealizar;

						this.objDetalleProductosPedido[ posicion ].detalleDescuento = this.detalleDescuentoRealizar;
						this.objDetalleProductosPedido[ posicion ].productoPrecioVenta = this.detalleValorPrecioVentaRealizar;
						this.objDetalleProductosPedido[ posicion ].detalleValorDescuento = this.detalleValorDescuentoRealizar;
						this.objDetalleProductosPedido[ posicion ].productoPrecionTotal = (precio * cantidad) - this.detalleValorDescuentoRealizar;
						this.objDetalleProductosPedido[ posicion ].productoCantidad = this.detalleCantidadRealizar; 
						this.dicPedidoDetalle.propinaModificada = false;

						if (this.dicPedidoDetalle.ivaProducto && this.detalleDescuentoRealizar<100){
							this.calcularImpuestoProductoDetallePedidoPago(this.objDetalleProductosPedido[ posicion ], posicion); 
						}
						
						/* this.calcularSubtotalDetallePedidoV2();
						this.calcularImpuestoDetallePedidoV2(); */
						if (!this.dicPedidoDetalle.ivaProducto){
							this.calcularSubtotalDetallePedidoV2();
							this.calcularImpuestosDetallePedido();
						}else{
							this.calcularSubtotalDetallePedidoV2IvaProducto(); 
							this.calcularImpuestosDetallePedidoIvaProducto(); 
							this.calcularIMpuestoDetallePedidoProducto(); 
						}

						this.reiniciarMetodosPagosCero();
						this.gestionarServicioPropinaV2();
						this.convertirValoresPedidoMonedaCurrency();
						this.hideModal( ventana );
					}, 

					calcularImpuestoProductoDetallePedidoPago(data, posicion){
						var totalImpuesto = 0; 
						var precioDescuento = data.productoPrecioVenta - data.detalleValorDescuento; 
						var precioSinImpuesto = data.productoPrecioVenta - data.detalleValorDescuento; 

						if (data.impuestoIncluido==0){
							totalImpuesto = precioDescuento-(precioDescuento/(1+(data.impuestoValor/100)));
							precioSinImpuesto = precioDescuento-totalImpuesto;
						}else if (data.impuestoIncluido==1){
							totalImpuesto = precioDescuento*(data.impuestoValor/100);
							precioSinImpuesto = precioDescuento;
						}

						this.objDetalleProductosPedido[posicion].productoPrecioVentaSinImpuesto = precioSinImpuesto; 
						this.objDetalleProductosPedido[posicion].productoTotalImpuesto = totalImpuesto; 
					}, 

					calcularImpuestoDetallePedidoV2(){
						if ( !app.vacios.includes( this.dicPedidoDetalle.impuestoId ) ){
							if ( this.dicPedidoDetalle.impuestoIncluido == 0 ){
								this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto - (this.dicPedidoDetalle.subtotalConDescuentoImpuesto / ( 1 + ( this.dicPedidoDetalle.impuestoPorcentaje / 100 ) ));
								this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 
								
								
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto - this.dicPedidoDetalle.pedidoValorImpuesto;
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubtotalConImpuesto, "").replaceAll(",", "")); 
								console.log("this.dicPedidoDetalle.pedidoSubtotalConImpuesto", this.dicPedidoDetalle.pedidoSubtotalConImpuesto); 
							}else if ( this.dicPedidoDetalle.impuestoIncluido == 1 ){
								this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto * ( this.dicPedidoDetalle.impuestoPorcentaje / 100 );
								this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 
								
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto;
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubtotalConImpuesto, "").replaceAll(",", "")); 
							}
						}else{
							if ( this.dicConfiguracionVenta.idImpuesto__incluido == 0 ){
								this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto - (this.dicPedidoDetalle.subtotalConDescuentoImpuesto / ( 1 + ( this.dicConfiguracionVenta.idImpuesto__impuesto / 100 ) ));
								this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 
																

								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto - this.dicPedidoDetalle.pedidoValorImpuesto;
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubtotalConImpuesto, "").replaceAll(",", "")); 
							}else if ( this.dicConfiguracionVenta.idImpuesto__incluido == 1 ){
								this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto * ( this.dicConfiguracionVenta.idImpuesto__impuesto / 100 );
								this.dicPedidoDetalle.pedidoValorImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoValorImpuesto, "").replaceAll(",", "")); 
								this.dicPedidoDetalle.impuestoIncluido = 1;
								
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = this.dicPedidoDetalle.subtotalConDescuentoImpuesto;
								this.dicPedidoDetalle.pedidoSubtotalConImpuesto = parseFloat(app.$options.filters.currency(this.dicPedidoDetalle.pedidoSubtotalConImpuesto, "").replaceAll(",", "")); 
							}
						}

						this.dicPedidoDetalle.pedidoSubTotal = this.dicPedidoDetalle.pedidoSubtotalConImpuesto + this.dicPedidoDetalle.subtotalConDescuentoSinImpuesto; 
					},  
				
				/* Dividir Factura */
					confirmarActivarDividirFacturaPedido(){
						var titulo = this.modoDividirFacturaPedido ? "¿Cancelar Dividir Factura?": "¿Activar Dividir Factura?"; 
						Swal.fire({
							title: titulo, type: 'warning', showCancelButton: true, allowOutsideClick: false,
							confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
						}).then((result) => {
							if (result.value) {
								this.gestionarEstadoModoDividirFacturaPedido();
							}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
						});
					},

					gestionarEstadoModoDividirFacturaPedido(){
						this.consultaDetalleInformacion = true;
						this.modoDividirFacturaPedido = this.modoDividirFacturaPedido ? false : true; 
						axios.post( "/Estructura/gestionarEstadoModoDividirFacturaPedido" , 
							"pedido=" + this.dicPedidoDetalle.pedidoId +
							"&&modoDividirFactura=" + this.modoDividirFacturaPedido + 
							"&&usuario=" + app.usuarioActual.usuario, 
						).then((result) => {
							setTimeout(()=>{
								if ( result.data.mensaje == 'Registro Exitoso' ){
									this.dicPedidoDetalle.modoDividirFactura = this.modoDividirFacturaPedido; 
									// this.activarDividirFactura();

									var estadoMesa = this.modoDividirFacturaPedido ? "En Pago" : "Uso"; 
									var datosActualizacion = {
										sucursal:this.idSucursalGestion, 
										fecha: app.fechaActual, 
										hora: app.horaActual,
										accion:'Actualizar', 
										salon: this.dicPedidoDetalle.salonId, 
										estructura: this.dicPedidoDetalle.estructuraId, 
										estado: estadoMesa, 
										area: 'Estructura', 
									}; 
									app.socket.emit('generacionPedido', datosActualizacion);

									this.verDetallePedidoV2(); 
									// this.consultaDetalleInformacion = false;
								}else{
									Swal.fire( { title:'¡Error de Registro!', type:'error', showConfirmButton: false, timer:2000 } );
									this.consultaDetalleInformacion = false;
								}
							});
						}).catch( error => {
							this.consultaDetalleInformacion = false;
							app.erroServidor( '' );
						});
					}, 

					activarDividirFactura(){
						/* this.modoDividirFacturaPedido = this.modoDividirFacturaPedido ? false : true;  */
						this.idDivirFacturaPedido = ""; this.idClientePedido = ""; this.nombreCliente = ""; this.clienteExiste = false; 
						this.ajustarPedidoPrincipal = false; this.recargarPedido = false; 

						if (!this.modoDividirFacturaPedido){
							this.verDetallePedidoV2();
						}else{
							setTimeout(()=>{
								this.totalProductosSeleccionados = 0; this.hayProductosSeleccionados = false; this.dicPedidoDetalle.comensales = 1; 
								this.objDetalleProductosPedido.forEach((elemento, posicion)=>{
									this.objDetalleProductosPedido[posicion]['seleccionar'] = false; 
									this.objDetalleProductosPedido[posicion]['productoCantidadModificada'] = JSON.parse(JSON.stringify(elemento.productoCantidad)); 
								});	
								
								this.calcularSubtotalDetallePedidoV2();
								this.calcularImpuestoDetallePedidoV2();
								this.objDetallePago = []; this.objDivicionCuenta = []; 
								this.agregarMetodoPagoPedidoV2();
								this.gestionarServicioPropinaV2();
								this.convertirValoresPedidoMonedaCurrency();
							});
						}
					}, 

					validarProductosDivicionFacturaDetalle(){
						var validar = alasql("select * from ? where seleccionar=true", [this.objDetalleProductosPedido]); 
						this.totalProductosSeleccionados = validar.length; 
						this.hayProductosSeleccionados = validar.length>0?true:false; 

						/* this.calcularSubtotalDetallePedidoV2();
						this.calcularImpuestoDetallePedidoV2(); */
						if (!this.dicPedidoDetalle.ivaProducto){
							this.calcularSubtotalDetallePedidoV2();
							this.calcularImpuestosDetallePedido();
						}else{
							this.calcularSubtotalDetallePedidoV2IvaProducto(); 
							this.calcularImpuestosDetallePedidoIvaProducto(); 
							this.calcularIMpuestoDetallePedidoProducto(); 
						}

						this.reiniciarMetodosPagosCero();
						this.gestionarServicioPropinaV2();
						this.convertirValoresPedidoMonedaCurrency();
					}, 

					filtrandoPedido( datos ){
						this.totalDatosPedido = datos.length;
						this.currentPagePedido = 1;
					},

				/*detalle de pedido*/
					verModalDetallePedidoListadoPedidos( ventana, pedido ){
						setTimeout(()=>{
							this.idPedidoGestion = pedido.pedidoId;

							this.verModalDetallePedido( ventana );
						});
					},

					verModalDetallePedido( ventana ){
						setTimeout(()=>{
							this.objDetalleProductosPedido = [];
							this.dicPedidoDetalle = {};
							this.nombreClienteDetalle = '';

							this.showModal( ventana );
							// this.verDetallePedido();
							this.verDetallePedidoV2();
						});
					},

					verDetallePedido(){
						this.consultaDetalleInformacion = true;
						this.aperturarEstructura = false; 
						var vacios = [undefined, null, '', 'undefined', 'null', 'None'];
						axios.post( 
							"/Estructura/verDetallePedido", 
							"pedido=" + this.idPedidoGestion,
						).then((result) => {
							this.objDetalleProductosPedido = result.data.detalle;
							this.dicPedidoDetalle = result.data.pedido;
							this.objDetallePago = result.data.pagos;
							this.seleccionarMetodoPago = '';
							this.nombreClienteDetalle = this.dicPedidoDetalle.clienteResponsable;
							this.totalPagoMedios = 0;
							

							if ( this.objConfiguracionesVentas.length > 0 ){
								if ( !vacios.includes( this.dicPedidoDetalle.impuestoId ) ){
									if ( this.dicPedidoDetalle.impuestoIncluido == 0 ){
										this.dicPedidoDetalle.pedidoSubTotal = this.dicPedidoDetalle.pedidoSubTotal + this.dicPedidoDetalle.pedidoValorImpuesto;
										this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.pedidoSubTotal - (this.dicPedidoDetalle.pedidoSubTotal / ( 1 + ( this.dicPedidoDetalle.impuestoPorcentaje / 100 ) ));
										this.dicPedidoDetalle.pedidoSubTotal = this.dicPedidoDetalle.pedidoSubTotal - this.dicPedidoDetalle.pedidoValorImpuesto;
									}else if ( this.dicPedidoDetalle.impuestoIncluido == 1 ){
										this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.pedidoSubTotal * ( this.dicPedidoDetalle.impuestoPorcentaje / 100 );
									}
								}else{
									if ( this.dicConfiguracionVenta.idImpuesto__incluido == 0 ){
										this.dicPedidoDetalle.pedidoSubTotal = this.dicPedidoDetalle.pedidoSubTotal + this.dicPedidoDetalle.pedidoValorImpuesto;
										this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.pedidoSubTotal - (this.dicPedidoDetalle.pedidoSubTotal / ( 1 + ( this.dicConfiguracionVenta.idImpuesto__impuesto / 100 ) ));
										this.dicPedidoDetalle.pedidoSubTotal = this.dicPedidoDetalle.pedidoSubTotal - this.dicPedidoDetalle.pedidoValorImpuesto;
									}else if ( this.dicConfiguracionVenta.idImpuesto__incluido == 1 ){
										this.dicPedidoDetalle.pedidoValorImpuesto = this.dicPedidoDetalle.pedidoSubTotal * ( this.dicConfiguracionVenta.idImpuesto__impuesto / 100 );
									}
								}

								if ( this.dicPedidoDetalle.pedidoOrdenPago ){
									this.aplicarServicioPropina = ( this.dicPedidoDetalle.pedidoPropinaValor > 0 ) ? true : false; 
								}else{
									this.dicPedidoDetalle.pedidoMetodoPago = 'Efectivo';
									this.aplicarServicioPropina = true; 
									this.dicPedidoDetalle.pedidoPropinaValor = ( this.dicPedidoDetalle.pedidoSubTotal * (this.dicConfiguracionVenta.porcentajeServicio/100) );
								}

								this.dicPedidoDetalle.pedidoPropinaValorStr = this.moneda( this.dicPedidoDetalle.pedidoSubTotal * (this.dicConfiguracionVenta.porcentajeServicio/100) );
								this.dicPedidoDetalle.pedidoSubTotalStr = this.moneda( this.dicPedidoDetalle.pedidoSubTotal );
								this.dicPedidoDetalle.pedidoCambioPagoStr = this.moneda( this.dicPedidoDetalle.pedidoCambioPago );
								this.dicPedidoDetalle.pedidoValorImpuestoStr = this.moneda( this.dicPedidoDetalle.pedidoValorImpuesto );

								if ( !vacios.includes( this.dicPedidoDetalle.impuestoId ) ){
									if ( this.dicPedidoDetalle.impuestoIncluido == 1 ){
										var total = this.dicPedidoDetalle.pedidoSubTotal + this.dicPedidoDetalle.pedidoValorImpuesto + this.dicPedidoDetalle.pedidoPropinaValor;
									}else{
										var total = this.dicPedidoDetalle.pedidoSubTotal + this.dicPedidoDetalle.pedidoValorImpuesto + this.dicPedidoDetalle.pedidoPropinaValor;
									}
								}else{
									if ( this.dicConfiguracionVenta.idImpuesto__incluido == 1 ){
										var total = this.dicPedidoDetalle.pedidoSubTotal + this.dicPedidoDetalle.pedidoValorImpuesto + this.dicPedidoDetalle.pedidoPropinaValor;
									}else{
										var total = this.dicPedidoDetalle.pedidoSubTotal + this.dicPedidoDetalle.pedidoValorImpuesto + this.dicPedidoDetalle.pedidoPropinaValor;
									}
								}
								this.dicPedidoDetalle.pedidoPrecioTotal = total;
								this.dicPedidoDetalle.pedidoPrecioTotalStr = this.moneda(total);
								this.validarTotalMediosPagos();
							}

							this.consultaDetalleInformacion = false;
						}).catch( error => {
							console.log("error", error);
							app.erroServidor( '' );
						});
					}, 

					agregarMetodoPagoPedido(){
						setTimeout(()=>{
							this.validarTotalMediosPagos();
							if ( this.totalPagoMedios <= this.dicPedidoDetalle.pedidoPrecioTotal ){
								this.objDetallePago.push({
									id:'', 
									metodo: JSON.parse( JSON.stringify( this.seleccionarMetodoPago ) ), 
									valor:0,
								});
							}
							this.seleccionarMetodoPago = '';
						});
					}, 

					validarTotalMediosPagos(){
						this.totalPagoMedios = alasql("select SUM( cast ( valor as integer ) ) as sumaPagos from ? where valor>0", [this.objDetallePago])[0].sumaPagos;
						this.totalPagoMediosStr = this.moneda( this.totalPagoMedios );
						this.dicPedidoDetalle.pedidoValorPagado = this.totalPagoMedios;
						this.calcularCambioPago();
					}, 

					quitarMetodPago( datos, posicion ){
						this.objDetallePago.splice( posicion, 1 );
						this.validarTotalMediosPagos();
					}, 

					abrirModalCalcularaMetodo( ventana, datos, posicion ){
						this.dicCalculado = {
							total: JSON.parse( JSON.stringify( datos.valor ) ), 
							totalStr: this.cantidadC( JSON.parse( JSON.stringify( datos.valor ) ) ), 
							posicion: posicion, 
						};
						this.showModal( ventana );
					}, 

					gestionarCalculadoraMetodos( ventana, valor, accion ){
						if ( accion == 'agregar' ){
							if ( ( this.dicCalculado.total == '0' && valor!='0' && valor!='00' ) || this.dicCalculado.total != '0' ){
								this.dicCalculado.total = ( this.dicCalculado.total != '0' ) ? this.dicCalculado.total + valor : valor;
								this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
							}
						}

						if ( accion == 'limpiar' ){
							this.dicCalculado.total = '0';
							this.dicCalculado.totalStr = this.cantidadC( this.dicCalculado.total );
						}

						if ( accion == 'finalizar' ){
							this.objDetallePago[ this.dicCalculado.posicion ].valor = JSON.parse( JSON.stringify( this.dicCalculado.total ) );
							this.dicCalculado = {};
							this.validarTotalMediosPagos();
							this.hideModal( ventana );
						}
					},

					gestionarServicioPropina(){
						if ( this.aplicarServicioPropina ){
							this.dicPedidoDetalle.pedidoPropinaValor = ( this.dicPedidoDetalle.pedidoSubTotal * (this.dicConfiguracionVenta.porcentajeServicio/100) );
							this.dicPedidoDetalle.pedidoPropinaValorStr = this.moneda( this.dicPedidoDetalle.pedidoPropinaValor);
						}else{
							this.dicPedidoDetalle.pedidoPropinaValor = ( this.dicPedidoDetalle.pedidoSubTotal * 0 );
							this.dicPedidoDetalle.pedidoPropinaValorStr = this.moneda( this.dicPedidoDetalle.pedidoPropinaValor);
						}

						if ( this.dicConfiguracionVenta.idImpuesto__incluido == 1 ){
							var total = this.dicPedidoDetalle.pedidoSubTotal + this.dicPedidoDetalle.pedidoValorImpuesto + this.dicPedidoDetalle.pedidoPropinaValor;
						}else{
							var total = this.dicPedidoDetalle.pedidoSubTotal + this.dicPedidoDetalle.pedidoValorImpuesto + this.dicPedidoDetalle.pedidoPropinaValor;
						}
						this.dicPedidoDetalle.pedidoPrecioTotal = total;
						this.dicPedidoDetalle.pedidoPrecioTotalStr = this.moneda(total);

						this.calcularCambioPago();
					}, 

					calcularCambioPago(){
						setTimeout(()=>{
							if ( this.dicPedidoDetalle.pedidoValorPagado > 0 && this.dicPedidoDetalle.pedidoValorPagado >= this.dicPedidoDetalle.pedidoPrecioTotal ){
								this.dicPedidoDetalle.pedidoCambioPago = this.dicPedidoDetalle.pedidoValorPagado - this.dicPedidoDetalle.pedidoPrecioTotal;
								this.dicPedidoDetalle.pedidoCambioPagoStr = this.moneda( this.dicPedidoDetalle.pedidoCambioPago );
							}else if ( this.dicPedidoDetalle.pedidoCambioPago < 0 ){
								this.dicPedidoDetalle.pedidoCambioPago = 0;
								this.dicPedidoDetalle.pedidoCambioPagoStr = this.moneda( this.dicPedidoDetalle.pedidoCambioPago );
							}
						});
					},

					confirmarGestionarOrdenPagoPedido( ventana ){
						Swal.fire({
							title: '¿Enviar Factura de Venta?', type: 'warning', showCancelButton: true, allowOutsideClick: false,
							confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
						}).then((result) => {
							if (result.value) {
								this.gestionarOrdenPagoPedido( ventana );
							}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
						});
					},

					confirmarActualizarMetodosPagosFactura( ventana ){
						Swal.fire({
							title: '¿Actualizar Datos?', text:'',  
							type: 'warning', showCancelButton: true, allowOutsideClick: false,
							confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
						}).then((result) => {
							if (result.value) {
								this.actualizarMetodosPagosFactura( ventana );
							}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
						});
					},

					validarValoresMetodoPagos(){
						var totalTT = alasql(
							"select SUM( cast ( valor as float ) ) as sumaPagos from ? where valor>0 AND metodo!='Efectivo'", 
							[this.objDetallePago]
						)[0].sumaPagos;
						var TTMetodos = alasql( "select * from ? where valor>0 AND metodo!='Efectivo'", [this.objDetallePago] );
						console.log("totalTT __ ", totalTT);
						console.log("totalTT __ ", TTMetodos.length);
						console.log("totalTT __ ", this.objDetallePago.length);
						if ( totalTT <= this.dicPedidoDetalle.pedidoTotalNeto && TTMetodos.length > 0 ){
							console.log("Valores restantes: ", this.dicPedidoDetalle.pedidoTotalNeto - totalTT );
							var restante = this.dicPedidoDetalle.pedidoTotalNeto - totalTT;
							this.objDetallePago.forEach(elemento => {
								if ( elemento.metodo == 'Efectivo' ){
									elemento.valor = restante;
								}
							});
						}/* else if ( TTMetodos.length == this.objDetallePago.length && totalTT > this.dicPedidoDetalle.pedidoTotalNeto ){
							console.log("calc_cambio_mas");
							var cambio = totalTT - this.dicPedidoDetalle.pedidoTotalNeto;
							this.objDetallePago.forEach(elemento => {
								elemento.valor = elemento.valor - ( cambio / this.objDetallePago.length );
							});
						} */else{
							var totalEE = alasql(
								"select SUM( cast ( valor as float ) ) as sumaPagos from ? where valor>0 AND metodo='Efectivo'", 
								[this.objDetallePago]
							)[0].sumaPagos;
							console.log("totalEE __ ", totalEE);
							console.log("totalEE__  __ ", totalTT < this.dicPedidoDetalle.pedidoTotalNeto);
							console.log("totalEE__  __ ", this.dicPedidoDetalle.pedidoTotalNeto);
							console.log("totalEE__  __ ", totalTT);
							console.log("totalEE__  __ ", TTMetodos.length == this.objDetallePago.length );
							console.log("totalEE__  __ ", this.objDetallePago.length );
							console.log("totalEE__  __ ", TTMetodos.length );
							if ( totalEE > this.dicPedidoDetalle.pedidoTotalNeto ){
								console.log("totalEE __ ", totalEE);
								var p = 0;
								this.objDetallePago.forEach(elemento => {
									if ( elemento.metodo == 'Efectivo' && p === 0 ){
										elemento.valor = this.dicPedidoDetalle.pedidoTotalNeto;
									}else{
										elemento.valor = 0;
									}
									p = p + 1;
								});
							}
						}
					},

					valorRecibidoMetodosPagos(){
						if(this.validarValorMetodosNoEfectivo()==this.dicPedidoDetalle.pedidoTotalNeto){
							this.objDetallePago.forEach((elemento=>{
								if (elemento.metodo=='Efectivo'){
									elemento.valorPagado = 0; 
									elemento.valorCambio = elemento.valor; 
								}else{
									elemento.valorPagado = elemento.valor; 
									elemento.valorCambio = 0; 
								}
							})); 
						}else {
							this.objDetallePago.forEach((elemento=>{
								if (elemento.metodo=='Efectivo'){
									elemento.valorPagado = this.dicPedidoDetalle.pedidoTotalNeto - this.validarValorMetodosNoEfectivo(); 
									elemento.valorCambio = elemento.valor - elemento.valorPagado; 
								}else{
									elemento.valorPagado = elemento.valor; 
									elemento.valorCambio = 0; 
								}
							})); 
						}
					}, 

					actualizarMetodosPagosFactura(ventana){
						this.consultaDetalleInformacion = true;
						var objPagosId = alasql("select column id from ? where valor>0", [this.objDetallePago]);
						var objPagosMetodo = alasql("select column metodoPago__id from ? where valor>0", [this.objDetallePago]);
						
						axios.post( "/Estructura/actualizarMetodosPagosFactura" , 
							"pedido=" + this.dicPedidoDetalle.pedidoId +
							"&&objPagosId=" + objPagosId +
							"&&objPagosMetodo=" + objPagosMetodo + 
							"&&usuario=" + app.usuarioActual.usuario, 
						).then((result) => {
							setTimeout(()=>{
								if ( result.data.mensaje == 'Registro Exitoso' ){
									this.verDetallePedidoV2();
								}else{
									Swal.fire( { title:'¡Error de Registro!', type:'error', showConfirmButton: false, timer:2000 } );
									this.consultaDetalleInformacion = false;
								}
							});
						}).catch( error => {
							this.consultaDetalleInformacion = false;
							app.erroServidor( '' );
						}); 
					}, 

					gestionarOrdenPagoPedido(ventana){
						if (
							 this.dicPedidoDetalle.pedidoEstado!='Pagado' || 
							 (this.dicPedidoDetalle.pedidoEstado=='Pagado' && app.pAdminEstructura && this.modificarFacturaPagada)
						){
							this.objDivicionCuenta = [];
							this.consultaDetalleInformacion = true;
							var vacios = [undefined, null, '', 'undefined', 'null', 'None'];
							var impuesto = ( !vacios.includes( this.dicPedidoDetalle.impuestoId ) ) ? this.dicPedidoDetalle.impuestoId : this.dicConfiguracionVenta.idImpuesto__id;
							
							this.valorRecibidoMetodosPagos(); 
							if (this.dicPedidoDetalle.pedidoDescuento<100){
								var objPagosId = alasql("select column id from ? where valor>0", [this.objDetallePago]);
								var objPagosMetodo = alasql("select column metodoPago__id from ? where valor>0", [this.objDetallePago]);
								var objPagosValor = alasql("select column valor from ? where valor>0", [this.objDetallePago]);
								var objPagosValorPagado = alasql("select column valorPagado from ? where valor>0", [this.objDetallePago]);
								var objPagosValorCambio = alasql("select column valorCambio from ? where valor>0", [this.objDetallePago]);
							}else{
								var objPagosId = this.objDetallePago[0].id;
								var objPagosMetodo = this.objDetallePago[0].metodoPago__id;
								var objPagosValor = this.objDetallePago[0].valor;
								var objPagosValorPagado = this.objDetallePago[0].valorPagado;
								var objPagosValorCambio = this.objDetallePago[0].valorCambio;
							}


							objDivisionId = alasql("select column id from ? where valor>0", [this.objDivicionCuenta]);
							objDivisionMetodo = alasql("select column metodoPago__id from ? where valor>0", [this.objDivicionCuenta]);
							objDivisionValor = alasql("select column valor from ? where valor>0", [this.objDivicionCuenta]);

							var referencias = alasql( "select column referencia from ?", [ this.objDetalleProductosPedido ] );
							var productos = alasql( "select column productoId from ?", [ this.objDetalleProductosPedido ] );
							var productosPrecioVenta = alasql( "select column productoPrecioVenta from ?", [ this.objDetalleProductosPedido ] );
							var productosPrecioTotal = alasql( "select column productoPrecionTotal from ?", [ this.objDetalleProductosPedido ] );
							var cantidades = alasql( "select column productoCantidad from ?", [ this.objDetalleProductosPedido ] );
							var notas = alasql( "select column detalleNota from ?", [ this.objDetalleProductosPedido ] );
							var categorias = alasql( "select column categoriaId from ?", [ this.objDetalleProductosPedido ] );
							var observaciones = alasql( "select column detalleObservacion from ?", [ this.objDetalleProductosPedido ] );
							var descuentoDetalle = alasql( "select column detalleDescuento from ?", [ this.objDetalleProductosPedido ] );
							var valorDescuentoDetalle = alasql( "select column detalleValorDescuento from ?", [ this.objDetalleProductosPedido ] );
							var productosContenidos = alasql( "select column totalProductosContenidos from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );
							var productosPrecioVentaSinImpuesto = alasql( "select column productoPrecioVentaSinImpuesto from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );
							var productosTotalImpuesto = alasql( "select column productoTotalImpuesto from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );
							var totalProductosPedido = this.objDetalleProductosPedido.length;

							var referenciasDividirFactura = ''; var productosDividirFactura = ''; var productosPrecioVentaDividirFactura = ''; 
							var productosPrecioTotalDividirFactura = ''; var cantidadesDividirFactura = ''; var notasDividirFactura = ''; 
							var categoriasDividirFactura = ''; var observacionesDividirFactura = ''; var descuentoDetalleDividirFactura = ''; 
							var valorDescuentoDetalleDividirFactura = ''; var totalProductosPedidoDividir = 0; var referenciasDividirFacturaCantidadModificada = ''; 
							var productosContenidosDividirFactura = ''; var productosPrecioVentaSinImpuestoDividirFactura = ''; var productosTotalImpuestoDividirFactura = ''; 
							if (this.modoDividirFacturaPedido){
								referenciasDividirFactura = alasql( "select column referencia from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								productosDividirFactura = alasql( "select column productoId from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								productosPrecioVentaDividirFactura = alasql( "select column productoPrecioVenta from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								productosPrecioTotalDividirFactura = alasql( "select column productoPrecionTotal from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								cantidadesDividirFactura = alasql( "select column productoCantidad from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								notasDividirFactura = alasql( "select column detalleNota from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								categoriasDividirFactura = alasql( "select column categoriaId from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								observacionesDividirFactura = alasql( "select column detalleObservacion from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								descuentoDetalleDividirFactura = alasql( "select column detalleDescuento from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								valorDescuentoDetalleDividirFactura = alasql( "select column detalleValorDescuento from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								productosContenidosDividirFactura = alasql( "select column totalProductosContenidos from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								productosPrecioVentaSinImpuestoDividirFactura = alasql( "select column productoPrecioVentaSinImpuesto from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								productosTotalImpuestoDividirFactura = alasql( "select column productoTotalImpuesto from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
								totalProductosPedidoDividir = referenciasDividirFactura.length; 
								referenciasDividirFacturaCantidadModificada = alasql( "select column referencia from ? where seleccionar=true and productoCantidad<productoCantidadModificada", [ this.objDetalleProductosPedido ] );
							}

							var resolucion = ''; var resolucionPrefijo = ''; var pedidoAnterior = ''; 
							if (!vacios.includes( this.dicConfiguracionVenta.resolucion )){ resolucion = this.dicConfiguracionVenta.resolucion;  }
							if (!vacios.includes( this.dicConfiguracionVenta.resolucionPrefijo )){ resolucionPrefijo = this.dicConfiguracionVenta.resolucionPrefijo;  }
							
							var porcentajePropina = this.dicPedidoDetalle.porcentajePropina; 
							axios.post( "/Estructura/gestionarOrdenPagoPedidoListado" , 
								"pedido=" + this.dicPedidoDetalle.pedidoId +
								"&&dividirCuenta=" + this.modoDividirFacturaPedido +
								"&&cliente=" + this.idClientePedido +
								"&&impuesto=" + impuesto +
								"&&estado=" + "Pagado" +
								"&&metodoPago=" + this.dicPedidoDetalle.pedidoMetodoPago +
								"&&estructura=" + this.dicPedidoDetalle.estructuraId +
								"&&aperturarEstructura=" + app.procesarTrueFalse(this.aperturarEstructura) +
								"&&pedidoOrdenPago=" + app.procesarTrueFalse(this.pedidoOrdenPago) +
								"&&pedidoMesaLiberada=" + app.procesarTrueFalse(this.dicPedidoDetalle.pedidoMesaLiberada) +
								"&&liberarMesaAutomaticamente=" + app.procesarTrueFalse(this.dicConfiguracionVenta.liberarMesaAutomaticamente) +

								"&&observacion=" + this.dicPedidoDetalle.pedidoObservacion +
								"&&resolucion=" + resolucion +
								"&&resolucionPrefijo=" + resolucionPrefijo +

								"&&objPagosId=" + objPagosId +
								"&&objPagosMetodo=" + objPagosMetodo +
								"&&objPagosValor=" + objPagosValor +
								"&&objPagosValorPagado=" + objPagosValorPagado +
								"&&objPagosValorCambio=" + objPagosValorCambio +

								"&&objDivisionId=" + objDivisionId +
								"&&objDivisionMetodo=" + objDivisionMetodo +
								"&&objDivisionValor=" + objDivisionValor +

								"&&referencias=" + referencias +
								"&&productos=" + productos +
								"&&productosPrecioVenta=" + productosPrecioVenta +
								"&&productosPrecioTotal=" + productosPrecioTotal +
								"&&cantidades=" + cantidades +
								"&&notas=" + notas +
								"&&categorias=" + categorias +
								"&&observaciones=" + observaciones +
								"&&descuentoDetalle=" + descuentoDetalle +
								"&&valorDescuentoDetalle=" + valorDescuentoDetalle +
								"&&productosContenidos=" + productosContenidos +
								"&&productosPrecioVentaSinImpuesto=" + productosPrecioVentaSinImpuesto +
								"&&productosTotalImpuesto=" + productosTotalImpuesto +

								"&&totalProductosPedido=" + totalProductosPedido +
								"&&totalProductosPedidoDividir=" + totalProductosPedidoDividir +

								"&&referenciasDividirFactura=" + referenciasDividirFactura +
								"&&productosDividirFactura=" + productosDividirFactura +
								"&&productosPrecioVentaDividirFactura=" + productosPrecioVentaDividirFactura +
								"&&productosPrecioTotalDividirFactura=" + productosPrecioTotalDividirFactura +
								"&&cantidadesDividirFactura=" + cantidadesDividirFactura +
								"&&notasDividirFactura=" + notasDividirFactura +
								"&&categoriasDividirFactura=" + categoriasDividirFactura +
								"&&observacionesDividirFactura=" + observacionesDividirFactura +
								"&&descuentoDetalleDividirFactura=" + descuentoDetalleDividirFactura +
								"&&valorDescuentoDetalleDividirFactura=" + valorDescuentoDetalleDividirFactura +
								"&&referenciasDividirFacturaCantidadModificada=" + referenciasDividirFacturaCantidadModificada +
								"&&productosContenidosDividirFactura=" + productosContenidosDividirFactura +
								"&&productosPrecioVentaSinImpuestoDividirFactura=" + productosPrecioVentaSinImpuestoDividirFactura +
								"&&productosTotalImpuestoDividirFactura=" + productosTotalImpuestoDividirFactura +

								"&&propina=" + app.procesarTrueFalse(this.aplicarServicioPropina) +
								"&&porcentajePropina=" + porcentajePropina +

								"&&descuento=" + this.dicPedidoDetalle.pedidoDescuento +
								"&&totalDescuento=" + this.dicPedidoDetalle.pedidoTotalDescuento +
								"&&totalNeto=" + this.dicPedidoDetalle.pedidoTotalNeto +
								"&&propinaModificada=" + app.procesarTrueFalse(this.dicPedidoDetalle.propinaModificada) +
								"&&porcentajePropina=" + this.dicPedidoDetalle.porcentajePropina +
								"&&cuponId=" + this.dicPedidoDetalle.cuponId +
								
								"&&comensales=" + this.dicPedidoDetalle.comensales +
								"&&totalPromedioConsumo=" + this.dicPedidoDetalle.totalPromedioConsumo +

								"&&valorImpuesto=" + this.dicPedidoDetalle.pedidoValorImpuesto +
								"&&precioTotal=" + this.dicPedidoDetalle.pedidoPrecioTotal +
								"&&subTotal=" + this.dicPedidoDetalle.pedidoSubTotal +
								"&&propinaValor=" + this.dicPedidoDetalle.pedidoPropinaValor +
								"&&valorPagado=" + this.dicPedidoDetalle.pedidoValorPagado +
								"&&cambioPago=" + this.dicPedidoDetalle.pedidoCambioPago +
								
								"&&subtotalImpuestos=" + this.dicPedidoDetalle.subtotalImpuestos +
								"&&subtotalSinImpuestos=" + this.dicPedidoDetalle.subtotalSinImpuestos +
								"&&totalDescuentoImpuesto=" + this.dicPedidoDetalle.totalDescuentoImpuesto +
								"&&totalDescuentoSinImpuesto=" + this.dicPedidoDetalle.totalDescuentoSinImpuesto +
								"&&subtotalConDescuentoImpuesto=" + this.dicPedidoDetalle.subtotalConDescuentoImpuesto +
								"&&subtotalConDescuentoSinImpuesto=" + this.dicPedidoDetalle.subtotalConDescuentoSinImpuesto +
								"&&pedidoSubtotalConImpuesto=" + this.dicPedidoDetalle.pedidoSubtotalConImpuesto +
								
								"&&usuario=" + app.usuarioActual.usuario, 
							).then((result) => {
								setTimeout(()=>{
									if ( result.data.mensaje == 'Registro Exitoso' ){
										if ( this.edicionCuenta ){ this.edicionCuenta = false; }
										if (this.modoDividirFacturaPedido){
											pedidoAnterior = JSON.parse(JSON.stringify(this.dicPedidoDetalle.pedidoId)); 
											this.dicPedidoDetalle.pedidoId = result.data.pedido; 
											this.recargarPedido = true; 
										}

										this.idPedidoGestion = this.dicPedidoDetalle.pedidoId;
										this.dicPedidoDetalle.consecutivo = result.data.consecutivo;
										Swal.fire( { title:'¡Guardado Exitoso!', type:'success', showConfirmButton: false, timer:2000 } );

										var sucursal  = alasql("select * from ? where id =" + parseInt( this.idSucursalGestion ), [ this.objSucursales ]);
										var sede  = alasql("select * from ? where id =" + parseInt( this.idSucursalGestion ), [ this.objSucursales ]);
										sede = sede[0].nombre;
										var fecha = app.fechaActual;
										app.horaActualNavegador();
										var hora = app.horaActual;

										console.log("METODOS DE PAGO 1 ", this.objDetallePago);
										var metodoPago = '';
										var metodosPagos = []; 
										if ( this.objDetallePago.length > 0 ){
											metodoPago = (this.objDetallePago.length==1) ? this.objDetallePago[0].metodo : 'Mixto';
											this.objDetallePago.forEach((elemento)=>{
												if (elemento.valorPagado>0){
													metodosPagos.push({metodo:elemento.metodo, valorPagado:elemento.valorPagado})
												}
											}); 
										}

										var direccion = sucursal[0].direccion; var ciudad  = ""; 
										if ( !app.vacios.includes( sucursal[0].ciudadNombre ) ){
											ciudad = sucursal[0].ciudadNombre + '-Colombia';
										}

										var mesero = ''; 
										if ( !app.vacios.includes( this.dicPedidoDetalle.meseroId ) ){
											mesero = this.dicPedidoDetalle.meseroNombre + ' ' + this.dicPedidoDetalle.meseroApellido; 
										}

										var cliente = ''; var clienteIdentifiacion = ''; var clienteDireccion = ''; var clienteCiudad = ""; 
										if (!app.vacios.includes(this.dicPedidoDetalle.clienteId)){
											cliente = this.dicPedidoDetalle.clienteNombre + " " + this.dicPedidoDetalle.clienteApellido; 
											clienteIdentifiacion = this.dicPedidoDetalle.clienteIdentificacion; 

											if (!app.vacios.includes(this.dicPedidoDetalle.clienteDireccion)){ 
												clienteDireccion = this.dicPedidoDetalle.clienteDireccion; 
											}else if (!app.vacios.includes( sucursal[0].direccion )){ 
												clienteDireccion = sucursal[0].direccion; 
											}
											
											if (!app.vacios.includes(this.dicPedidoDetalle.clienteCiudadNombre)){ 
												clienteCiudad = this.dicPedidoDetalle.clienteCiudadNombre; 
											}else if (!app.vacios.includes( sucursal[0].ciudadNombre )){ 
												clienteCiudad = sucursal[0].ciudadNombre; 
											}
										}else{
											cliente = "CONSUMIDOR FINAL"; 
											clienteIdentifiacion = "222222222222"; 
											if (!app.vacios.includes( sucursal[0].direccion )){ 
												clienteDireccion = sucursal[0].direccion; 
											}
											if (!app.vacios.includes( sucursal[0].ciudadNombre )){ 
												clienteCiudad = sucursal[0].ciudadNombre; 
											}
										}

										var detalleProductosImpresion = []; 
										if (result.data.detalleNuevoPedido.length>0){
											detalleProductosImpresion = JSON.parse(JSON.stringify(result.data.detalleNuevoPedido)); 
										}else{
											detalleProductosImpresion = JSON.parse(JSON.stringify(this.objDetalleProductosPedido)); 
										}
										
										var detalleImpuesto = this.procesarDetalleImpuesto(this.dicPedidoDetalle, this.objDetalleProductosPedido); 
										var datosImpresion = {
											pedido: this.dicPedidoDetalle.pedidoId, consecutivo: this.dicPedidoDetalle.consecutivo, mesa: this.dicPedidoDetalle.estructuraNombre, 
											dicConfiguracionVenta: this.dicConfiguracionVenta, resolucion: resolucion, resolucionPrefijo: resolucionPrefijo, sucursalId: this.idSucursalGestion, 
											sucursal: sede, fecha: fecha, hora: hora, mesero: mesero, direccion: direccion, ciudad: ciudad, celular: sucursal[0].celular, email: sucursal[0].email, 
											telefono: sucursal[0].telefono, nit: sucursal[0].nit, metodoPago: metodoPago, metodosPagos: metodosPagos, cliente: cliente, 
											clienteIdentifiacion: clienteIdentifiacion, clienteDireccion: clienteDireccion, clienteCiudad: clienteCiudad, 
											observacion: this.dicPedidoDetalle.pedidoObservacion, totalCompra: this.dicPedidoDetalle.pedidoPrecioTotalProductos, 
											subtotal: this.dicPedidoDetalle.pedidoSubTotal, impuesto: this.dicPedidoDetalle.pedidoValorImpuesto, 
											impuestoPorcentaje: !vacios.includes(this.dicPedidoDetalle.impuestoId)?this.dicPedidoDetalle.impuestoPorcentaje:this.dicConfiguracionVenta.idImpuesto__impuesto, 
											impoconsumo: this.dicPedidoDetalle.impuestoIncluido, 
											iva: ( !vacios.includes( this.dicPedidoDetalle.impuestoId ) ) ? this.dicPedidoDetalle.pedidoValorImpuesto : this.dicConfiguracionVenta.idImpuesto__impuesto, 
											servicio: this.dicPedidoDetalle.pedidoPropinaValor, servicioDescuento: this.dicPedidoDetalle.porcentajePropina, 
											total: this.dicPedidoDetalle.pedidoTotalNeto, totalPagago: this.dicPedidoDetalle.pedidoValorPagado, totalNeto: this.dicPedidoDetalle.pedidoPrecioTotal, 

											descuento: this.dicPedidoDetalle.pedidoTotalDescuento, descuentoPorcentaje: this.dicPedidoDetalle.pedidoDescuento, 
											cambio: this.dicPedidoDetalle.pedidoCambioPago, ivaProducto: this.dicPedidoDetalle.ivaProducto, dobleImpresion: false, detalleImpuesto: detalleImpuesto, 
										};  
										if (this.dicConfiguracionVenta.reimprimirFacturaVenta){
											datosImpresion.dobleImpresion=true; 
										}

										this.listadoPedidos();
										var detalleImpresion = this.procesarProductosFacturarDetalle(detalleProductosImpresion); 
										
										if (app.globalEmpresa.versionPlugin==2){
											app.impirmirOrdenPagoV3(datosImpresion, detalleImpresion);
										}else{
											app.impirmirOrdenPagoV2(ventana, datosImpresion, detalleImpresion);
										}

										if (!app.vacios.includes(pedidoAnterior)){
											/* this.dicPedidoDetalle.pedidoId = JSON.parse(JSON.stringify(pedidoAnterior));  */
											this.idPedidoGestion = JSON.parse(JSON.stringify(pedidoAnterior)); 
										}
										this.verDetallePedidoV2();
									}else{
										Swal.fire( { title:'¡Error de Registro!', type:'error', showConfirmButton: false, timer:2000 } );
										this.consultaDetalleInformacion = false;
									}
								});
							}).catch( error => {
								this.consultaDetalleInformacion = false;
								app.erroServidor( '' );
							})
						}else{
							console.log("re-imprimir");

							console.log("METODOS DE PAGO 2 ", this.objDetallePago);
							var metodoPago = '';
							var metodosPagos = []; 
							if ( this.objDetallePago.length > 0 ){
								metodoPago = (this.objDetallePago.length==1) ? this.objDetallePago[0].metodo : 'Mixto';
								this.objDetallePago.forEach((elemento)=>{
									if (elemento.valorPagado>0){
										metodosPagos.push({metodo:elemento.metodo, valorPagado:elemento.valorPagado})
									}
								}); 
							}
							var vacios = [undefined, null, '', 'undefined', 'null', 'None'];
							var sucursal  = alasql("select * from ? where id =" + parseInt( this.idSucursalGestion ), [ this.objSucursales ]);
							var sede  = alasql("select * from ? where id =" + parseInt( this.idSucursalGestion ), [ this.objSucursales ]);
							sede = sede[0].nombre;
							var fecha = this.dicPedidoDetalle.modificacionFecha;
							app.horaActualNavegador();
							var hora = this.dicPedidoDetalle.modificacionHora;

							var direccion = sucursal[0].direccion; var ciudad  = ""; 
							if ( !app.vacios.includes( sucursal[0].ciudadNombre ) ){
								ciudad = sucursal[0].ciudadNombre + '-Colombia';
							}

							var mesero = ''; 
							if ( !app.vacios.includes( this.dicPedidoDetalle.meseroId ) ){
								mesero = this.dicPedidoDetalle.meseroNombre + ' ' + this.dicPedidoDetalle.meseroApellido; 
							}

							var resolucion = ''; var resolucionPrefijo = ''; 
							if (!vacios.includes( this.dicPedidoDetalle.resolucion )){ resolucion = this.dicPedidoDetalle.resolucion;  }
							if (!vacios.includes( this.dicPedidoDetalle.resolucionPrefijo )){ resolucionPrefijo = this.dicPedidoDetalle.resolucionPrefijo;  }

							var cliente = ''; var clienteIdentifiacion = ''; var clienteDireccion = ''; var clienteCiudad = ""; 
							if (!app.vacios.includes(this.dicPedidoDetalle.clienteId)){
								cliente = this.dicPedidoDetalle.clienteNombre + " " + this.dicPedidoDetalle.clienteNombre; 
								clienteIdentifiacion = this.dicPedidoDetalle.clienteIdentificacion; 

								if (!app.vacios.includes(this.dicPedidoDetalle.clienteDireccion)){ 
									clienteDireccion = this.dicPedidoDetalle.clienteDireccion; 
								}else if (!app.vacios.includes( sucursal[0].direccion )){ 
									clienteDireccion = sucursal[0].direccion; 
								}
								
								if (!app.vacios.includes(this.dicPedidoDetalle.clienteCiudadNombre)){ 
									clienteCiudad = this.dicPedidoDetalle.clienteCiudadNombre; 
								}else if (!app.vacios.includes( sucursal[0].ciudadNombre )){ 
									clienteCiudad = sucursal[0].ciudadNombre; 
								}
							}else{
								cliente = "CONSUMIDOR FINAL"; 
								clienteIdentifiacion = "222222222222"; 
								if (!app.vacios.includes( sucursal[0].direccion )){ 
									clienteDireccion = sucursal[0].direccion; 
								}
								if (!app.vacios.includes( sucursal[0].ciudadNombre )){ 
									clienteCiudad = sucursal[0].ciudadNombre; 
								}
							}

							/* var datosImpresion = {
								pedido: this.dicPedidoDetalle.pedidoId, consecutivo: this.dicPedidoDetalle.consecutivo, mesa: this.dicPedidoDetalle.estructuraNombre, 
								resolucion: resolucion, resolucionPrefijo: resolucionPrefijo, sucursal: sede, fecha: fecha, hora: hora, celular: sucursal[0].celular, 
								email: sucursal[0].email, direccion: direccion, ciudad: ciudad, telefono: sucursal[0].telefono, nit: sucursal[0].nit, metodoPago: metodoPago, 
								metodosPagos: metodosPagos, cliente: cliente, clienteIdentifiacion: clienteIdentifiacion, clienteDireccion: clienteDireccion, 
								clienteCiudad: clienteCiudad, mesero: mesero, observacion: this.dicPedidoDetalle.pedidoObservacion, totalCompra: this.dicPedidoDetalle.pedidoPrecioTotalProductos, 
								subtotal: this.dicPedidoDetalle.pedidoSubTotal, impuesto: this.dicPedidoDetalle.pedidoValorImpuesto, impuestoPorcentaje: this.dicPedidoDetalle.impuestoPorcentaje, 
								descuento: this.dicPedidoDetalle.pedidoTotalDescuento, descuentoPorcentaje: this.dicPedidoDetalle.pedidoDescuento, 
								impoconsumo: this.dicPedidoDetalle.impuestoIncluido, 
								iva: ( !vacios.includes( this.dicPedidoDetalle.impuestoId ) ) ? this.dicPedidoDetalle.pedidoValorImpuesto : this.dicConfiguracionVenta.idImpuesto__impuesto, 
								servicio: this.dicPedidoDetalle.pedidoPropinaValor, servicioDescuento: this.dicPedidoDetalle.porcentajePropina, totalNeto: this.dicPedidoDetalle.pedidoPrecioTotal, 
								total: this.dicPedidoDetalle.pedidoTotalNeto, totalPagago: this.dicPedidoDetalle.pedidoValorPagado, cambio: this.dicPedidoDetalle.pedidoCambioPago, 
								dobleImpresion: false, 
							};  */

							var detalleImpuesto = this.procesarDetalleImpuesto(this.dicPedidoDetalle, this.objDetalleProductosPedido); 
							var datosImpresion = {
								pedido: this.dicPedidoDetalle.pedidoId, consecutivo: this.dicPedidoDetalle.consecutivo, mesa: this.dicPedidoDetalle.estructuraNombre, 
								dicConfiguracionVenta: this.dicConfiguracionVenta, resolucion: resolucion, resolucionPrefijo: resolucionPrefijo, sucursalId: this.idSucursalGestion, 
								sucursal: sede, fecha: fecha, hora: hora, mesero: mesero, direccion: direccion, ciudad: ciudad, celular: sucursal[0].celular, email: sucursal[0].email, 
								telefono: sucursal[0].telefono, nit: sucursal[0].nit, metodoPago: metodoPago, metodosPagos: metodosPagos, cliente: cliente, clienteIdentifiacion: clienteIdentifiacion, 
								clienteDireccion: clienteDireccion, clienteCiudad: clienteCiudad, observacion: this.dicPedidoDetalle.pedidoObservacion, totalCompra: this.dicPedidoDetalle.pedidoPrecioTotalProductos, 
								subtotal: this.dicPedidoDetalle.pedidoSubTotal, impuesto: this.dicPedidoDetalle.pedidoValorImpuesto, impuestoPorcentaje: !vacios.includes(this.dicPedidoDetalle.impuestoId)?this.dicPedidoDetalle.impuestoPorcentaje:this.dicConfiguracionVenta.idImpuesto__impuesto, 
								impoconsumo: this.dicPedidoDetalle.impuestoIncluido, 
								iva: ( !vacios.includes( this.dicPedidoDetalle.impuestoId ) ) ? this.dicPedidoDetalle.pedidoValorImpuesto : this.dicConfiguracionVenta.idImpuesto__impuesto, 
								servicio: this.dicPedidoDetalle.pedidoPropinaValor, servicioDescuento: this.dicPedidoDetalle.porcentajePropina, total: this.dicPedidoDetalle.pedidoTotalNeto, 
								totalPagago: this.dicPedidoDetalle.pedidoValorPagado, totalNeto: this.dicPedidoDetalle.pedidoPrecioTotal, descuento: this.dicPedidoDetalle.pedidoTotalDescuento, 
								descuentoPorcentaje: this.dicPedidoDetalle.pedidoDescuento, cambio: this.dicPedidoDetalle.pedidoCambioPago, ivaProducto: this.dicPedidoDetalle.ivaProducto, 
								dobleImpresion: false, detalleImpuesto: detalleImpuesto, 
							};  
							var detalleImpresion = this.procesarProductosFacturarDetalle(this.objDetalleProductosPedido); 
							if ( app.equipoImpresion ){
								if (app.globalEmpresa.versionPlugin==2){
									app.impirmirOrdenPagoV3(datosImpresion, detalleImpresion);
								}else{
									app.impirmirOrdenPagoV2(ventana, datosImpresion, detalleImpresion);
								}
							}else{
								var datosSocket = {
									accion:'Imprimir', 
									sucursal: this.idSucursalGestion, 
									fecha: fecha, 
									hora: hora, 
									salon: '', 
									mesa: this.dicPedidoDetalle.estructuraNombre, 
									pedido: this.dicPedidoDetalle.pedidoId, 
									orden: 'IMPRESION_ODEN', 
									dicPedido: datosImpresion, 
									detalle: detalleImpresion, 
									quitados: [], 
								};
								app.socket.emit('generacionPedido', datosSocket);
							}
						}
					}, 

					procesarProductosFacturarDetalle(datos){
						var detalleOriginal = JSON.parse(JSON.stringify(datos)); 

						var referencia3 = alasql("select column referencia from ? where hayCombo=true", [detalleOriginal]); 
						if (referencia3.length>0){
							referencia3.forEach((elemento, posicion)=>{
								var principales3 = alasql("select column referencia from ?", [detalleOriginal]); 
								var posicionP3 = principales3.indexOf(referencia3[posicion]); 
								var principal3 = detalleOriginal[posicionP3]; 

								principal3.combo.forEach((elemento1, posicion1)=>{
									var agregar = {
										categoriaDestino: principal3.categoriaDestino, 
										categoriaId: principal3.categoriaId, 
										categoriaNombre: principal3.categoriaNombre, 
										detalleConsecutivoOrden: principal3.detalleConsecutivoOrden, 
										detalleDescuento: 0, detalleNota: "", detalleObservacion: "", detalleValorDescuento: 0, 
										observacionCostos: "", observacionIds: "", observacion: "", 
										productoNoAplicaImpuesto: false, productoTieneContenido: false, seleccionar: false, totalProductosContenidos: 0, 
										productoCantidad: principal3.productoCantidad, 
										productoCantidadModificada: principal3.productoCantidadModificada, 
										
										productoId: elemento1.productoId, 
										productoNombre: "++++"+elemento1.productoNombre, 
										productoPrecioVenta: parseFloat(elemento1.productoPrecioVenta), 
										productoPrecionTotal: parseFloat(elemento1.productoPrecionTotal), 
										referencia:referencia3[posicion]+"-"+elemento1.productoId, 
									}; 
									
									detalleOriginal[posicionP3].productoPrecioVenta = principal3.productoPrecioVenta - parseFloat(elemento1.productoPrecioVenta); 
									detalleOriginal[posicionP3].productoPrecionTotal = detalleOriginal[posicionP3].productoPrecioVenta*principal3.productoCantidad; 
									detalleOriginal.splice(posicionP3+1, 0, agregar); 
								}); 
							}); 
						}

						/* var observacionIds2 = alasql("select column observacionIds from ? where observacionIds!=''", [detalleOriginal]); 
						if (observacionIds2.length>0){
							var referencia2 = alasql("select column referencia from ? where observacionIds!=''", [detalleOriginal]); 
							var observacion2 = alasql("select column observacion from ? where observacionIds!=''", [detalleOriginal]); 
							var observacionCostos2 = alasql("select column observacionCostos from ? where observacionIds!=''", [detalleOriginal]); 
							
							observacionIds2.forEach((elemento, posicion)=>{
								var principales2 = alasql("select column referencia from ?", [detalleOriginal]); 
								var posicionP2 = principales2.indexOf(referencia2[posicion]); 
								var principal2 = detalleOriginal[posicionP2]; 

								var observacionIdsS2 = observacionIds2[posicion].split("]]coma[["); 
								var observacionS2 = observacion2[posicion].split("]]coma[["); 
								var observacionCostosS2 = observacionCostos2[posicion].split("]]coma[["); 
								observacionIdsS2.forEach((elemento1, posicion1)=>{
									var agregar = {
										categoriaDestino: principal2.categoriaDestino, 
										categoriaId: principal2.categoriaId, 
										categoriaNombre: principal2.categoriaNombre, 
										detalleConsecutivoOrden: principal2.detalleConsecutivoOrden, 
										detalleDescuento: 0, detalleNota: "", detalleObservacion: "", detalleValorDescuento: 0, 
										observacionCostos: "", observacionIds: "", observacion: "", 
										productoNoAplicaImpuesto: false, productoTieneContenido: false, seleccionar: false, totalProductosContenidos: 0, 
										productoCantidad: principal2.productoCantidad, 
										productoCantidadModificada: principal2.productoCantidadModificada, 
										
										productoId: observacionIdsS2[posicion1], 
										productoNombre: "++"+observacionS2[posicion1], 
										productoPrecioVenta: parseFloat(observacionCostosS2[posicion1]), 
										productoPrecionTotal: parseFloat(observacionCostosS2[posicion1]), 
										referencia:referencia2+"-"+observacionIdsS2[posicion1], 
									}; 
									
									detalleOriginal[posicionP2].productoPrecioVenta = principal2.productoPrecioVenta - parseFloat(observacionCostosS2[posicion1]); 
									detalleOriginal[posicionP2].productoPrecionTotal = detalleOriginal[posicionP2].productoPrecioVenta*principal2.productoCantidad; 
									detalleOriginal.splice(posicionP2+1, 0, agregar); 
								}); 
							}); 
						} */

						var observacionesIdsProducto = alasql("select column observacionesIdsProducto from ? where observacionesIdsProducto!=''", [detalleOriginal]); 
						if (observacionesIdsProducto.length>0){
							var referencia = alasql("select column referencia from ? where observacionesIdsProducto!=''", [detalleOriginal]); 
							var observacionesProducto = alasql("select column observacionesProducto from ? where observacionesIdsProducto!=''", [detalleOriginal]); 
							var observacionesCostosProducto = alasql("select column observacionesCostosProducto from ? where observacionesIdsProducto!=''", [detalleOriginal]); 
							var observacionesCantidadProducto = alasql("select column observacionesCantidadProducto from ? where observacionesIdsProducto!=''", [detalleOriginal]); 
							
							observacionesIdsProducto.forEach((elemento, posicion)=>{
								var principales = alasql("select column referencia from ?", [detalleOriginal]); 
								var posicionP = principales.indexOf(referencia[posicion]); 
								var principal = detalleOriginal[posicionP]; 

								var observacionesIdsProductoS = observacionesIdsProducto[posicion].split("]]coma[["); 
								var observacionesProductoS = observacionesProducto[posicion].split("]]coma[["); 
								var observacionesCostosProductoS = observacionesCostosProducto[posicion].split("]]coma[["); 
								var observacionesCantidadProductoS = observacionesCantidadProducto[posicion].split("]]coma[["); 
								observacionesIdsProductoS.forEach((elemento1, posicion1)=>{
									var agregar = {
										categoriaDestino: principal.categoriaDestino, 
										categoriaId: principal.categoriaId, 
										categoriaNombre: principal.categoriaNombre, 
										detalleConsecutivoOrden: principal.detalleConsecutivoOrden, 
										detalleDescuento: 0, detalleNota: "", detalleObservacion: "", detalleValorDescuento: 0, 
										observacionesCostosProducto: "", observacionesIdsProducto: "", observacionesProducto: "", 
										productoNoAplicaImpuesto: false, productoTieneContenido: false, seleccionar: false, totalProductosContenidos: 0, 
										productoCantidad: observacionesCantidadProductoS[posicion1], 
										productoCantidadModificada: observacionesCantidadProductoS[posicion1], 
										
										productoId: observacionesIdsProductoS[posicion1], 
										productoNombre: ">>"+observacionesProductoS[posicion1], 
										productoPrecioVenta: parseFloat(observacionesCostosProductoS[posicion1]), 
										productoPrecionTotal: parseFloat(observacionesCostosProductoS[posicion1]), 
										referencia:referencia+"-"+observacionesIdsProductoS[posicion1], 
									}; 
									
									detalleOriginal[posicionP].productoPrecioVenta = principal.productoPrecioVenta - (parseFloat(observacionesCostosProductoS[posicion1])*parseFloat(observacionesCantidadProductoS[posicion1])); 
									detalleOriginal[posicionP].productoPrecionTotal = detalleOriginal[posicionP].productoPrecioVenta*principal.productoCantidad; 
									detalleOriginal.splice(posicionP+1, 0, agregar); 
								}); 
							}); 
						}

						return detalleOriginal; 
					}, 

					mostrarDetalleImpuestos(){
						this.mostrarInputsDetalleImpuestos = this.mostrarInputsDetalleImpuestos ? false : true; 
						this.objDetalleImpuestosProducto = []; 
						this.calcularIMpuestoDetallePedidoProducto(); 
					}, 

					calcularIMpuestoDetallePedidoProducto(){
						var agregados = []; this.objDetalleImpuestosProducto = []; 

						var listaImpuestos = alasql("select column impuestoId from ?", [this.objDetalleProductosPedido]); 
						listaImpuestos = [...new Set(listaImpuestos)]; 
						if (listaImpuestos.length>0){
							listaImpuestos.forEach((elemento)=>{
								if (!app.vacios.includes(elemento)){
									impuesto = alasql("select * from ? where impuestoId="+elemento, [this.objDetalleProductosPedido])[0];
									if (impuesto.impuestoValor>0){
										impuestoNombre = impuesto.impuestoValor==8 ? "Impoconsumo 8%" : "Iva "+impuesto.impuestoValor+"%"; 
										totalImpuesto = alasql("select SUM(productoTotalImpuesto) as totalSuma from ? where impuestoId="+elemento, [this.objDetalleProductosPedido] )[0].totalSuma;
										totalImpuesto = totalImpuesto - (totalImpuesto*(this.dicPedidoDetalle.pedidoDescuento/100));

										if (agregados.includes(impuesto.impuestoValor)){
											var posicion = agregados.indexOf(impuesto.impuestoValor); 
											this.objDetalleImpuestosProducto[posicion].totalImpuesto = parseFloat(this.objDetalleImpuestosProducto[posicion].totalImpuesto)+totalImpuesto; 
										}else{
											agregados.push(impuesto.impuestoValor); 
											this.objDetalleImpuestosProducto.push({
												impuestoNombre: impuestoNombre, 
												totalImpuesto: totalImpuesto, 
											}); 
										}
									}
								}
							}); 
						}
					}, 

					procesarDetalleImpuesto(pedido, datos){
						var detalleImpuestos = []; var agregados = []; 

						var listaImpuestos = alasql("select column impuestoId from ?", [datos]); 
						listaImpuestos = [...new Set(listaImpuestos)]; 
						if (listaImpuestos.length>0){
							listaImpuestos.forEach((elemento)=>{
								if (!app.vacios.includes(elemento)){
									impuesto = alasql("select * from ? where impuestoId="+elemento, [datos])[0];
									if (impuesto.impuestoValor>0){
										impuestoNombre = impuesto.impuestoValor==8 ? "Impoconsumo 8%" : "Iva "+impuesto.impuestoValor+"%"; 
										totalImpuesto = alasql("select SUM(productoTotalImpuesto) as totalSuma from ? where impuestoId="+elemento, [datos] )[0].totalSuma;
										totalImpuesto = totalImpuesto - (totalImpuesto*(pedido.pedidoDescuento/100));

										if (agregados.includes(impuesto.impuestoValor)){
											var posicion = agregados.indexOf(impuesto.impuestoValor); 
											detalleImpuestos[posicion].totalImpuesto = parseFloat(detalleImpuestos[posicion].totalImpuesto)+totalImpuesto; 
										}else{
											agregados.push(impuesto.impuestoValor); 
											detalleImpuestos.push({
												impuestoNombre: impuestoNombre, 
												totalImpuesto: totalImpuesto, 
											}); 
										}
									}
								}
							}); 
						}
						return detalleImpuestos; 
					}, 

					verFacturaHija(item){
						this.consultaDetalleInformacion = true;
						this.hideModal("modalListadoPedidos"); 
						this.idPedidoGestion = JSON.parse(JSON.stringify(item.pedidoId)); 
						this.verDetallePedidoV2(); 
					}, 

					verPedidoPrincipal(item){
						this.consultaDetalleInformacion = true;
						this.hideModal("modalListadoPedidos"); 
						this.idPedidoGestion = JSON.parse(JSON.stringify(item)); 
						this.verDetallePedidoV2(); 
					}, 

					verProductosContenido(item){
						this.consultaDetalleInformacion = true;
						axios.post( "/Estructura/verProductosContenidos", "detalle=" + item.referencia, ).then((result) => {
							this.objDetalleProductosContendo = result.data.detalle;
							
							this.showModal("modaListadoProductosContenido"); 
							this.consultaDetalleInformacion = false;
						}).catch( error => {
							console.log("error", error);
							this.consultaDetalleInformacion = false;
							app.erroServidor( '' );
						});
					}, 

					activarEdicionFacturaPagada(){
						this.modificarFacturaPagada = this.modificarFacturaPagada ? false : true; 
						if(!this.modificarFacturaPagada){
							this.verDetallePedidoV2();
						}
					}, 

					abrirModalGestionarTokenAutorizacion(paso){
						this.tipoToken = "modificar-metodos-pagos"; 
						if (paso==1 && !this.dicConfiguracionVenta.autenticacionCodigo){ paso = 2; }

						if (paso==1){
							this.codigoMesero = ''; this.idMeseroAutorizacion = ''; 
							app.abrirModalGestionCodigosCalculadora("autorizar-actualizar-metodos-pagos"); 
						}else{
							this.activarEdicionFacturaPagada(); 
						}
					}, 

					validarCodigoActualizarMetodosPagos(paso){
						app.loading = true;
						axios.post( "/Estructura/validarCodigoResposnable", "codigo=" + this.codigoMesero,).then((result) => {
							setTimeout(()=>{
								if (!app.vacios.includes(result.data["respuesta"].id) && result.data.respuesta.rol=='Administrador'){
									if(this.tipoToken=='anular-pedido'){
										this.solicitarTokenAutorizacionAnulacion('anular-pedido',2); 
									}else if(this.tipoToken=='reactivar-pedido'){
										this.solicitarTokenAutorizacionReactivacion('reactivar-pedido',2); 
									}else{
										this.abrirModalGestionarTokenAutorizacion(paso); 
									}
									app.loading = false; 
								}else if (result.data.respuesta.rol!='Administrador'){
									Swal.fire({title:'¡Acceso Denegado!', type:'error', showConfirmButton: false, timer:2000});
									app.loading = false; 
									if(this.tipoToken=='anular-pedido'){
										this.solicitarTokenAutorizacionAnulacion('anular-pedido',1); 
									}else if(this.tipoToken=='reactivar-pedido'){
										this.solicitarTokenAutorizacionReactivacion('reactivar-pedido',1); 
									}else{
										this.abrirModalGestionarTokenAutorizacion(1); 
									}
								} else{
									Swal.fire({title:'¡Código no Existe!', type:'error', showConfirmButton: false, timer:2000});
									app.loading = false; 
									if(this.tipoToken=='anular-pedido'){
										this.solicitarTokenAutorizacionAnulacion('anular-pedido',1); 
									}else if(this.tipoToken=='reactivar-pedido'){
										this.solicitarTokenAutorizacionReactivacion('reactivar-pedido',1); 
									}else{
										this.abrirModalGestionarTokenAutorizacion(1); 
									}
								}
							});
						}).catch( error => {
							app.erroServidor( '' ); 
						});
					}, 


					confirmarGenerarTokenAutorizacionEmail( ventana ){
						Swal.fire({
							title: '¿Generar Token?', type: 'warning', showCancelButton: true, allowOutsideClick: false,
							confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
						}).then((result) => {
							if (result.value) {
								this.generarTokenAutorizacionEmail( ventana );
							}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
						});
					}, 

					generarTokenAutorizacionEmail( ventana ){
						// this.hideModal( 'modalAutorizacionEdicion' );
						this.consultaDetalleInformacion = true;
						this.mensajeVerificacion = ''; this.codigoGeneradoVerificacion = ''; this.codigoVerificacion = ''; 
						axios.post( "/Estructura/generarTokenAutorizacionEmail", 
							"email=" + this.emailVerificacion + 
							"&&pedido=" + this.dicPedidoDetalle.pedidoId +
							"&&codigoMesero=" + this.codigoMesero +
							"&&tipoToken=" + this.tipoToken +
							"&&usuario=" + app.usuarioActual.usuario, 
						).then((result) => {
							this.mensajeVerificacion = result.data.mensaje; 
							this.codigoGeneradoVerificacion = result.data.codigo;
							if (app.vacios.includes(app.globalEmpresa.destinos)){
								app.globalEmpresa.destinos = JSON.parse(JSON.stringify(this.emailVerificacion)); 
							}
							console.log("codigo de verificacion generado ", this.codigoGeneradoVerificacion);
							if ( result.data.mensaje == "generado" ){
								Swal.fire( { title:'¡Token Generado!', type:'success', showConfirmButton: false, timer:2000 } );
							}else{
								Swal.fire( { title:'¡Error en Registro!', type:'error', showConfirmButton: false, timer:2000 } );
							}
							// this.showModal( 'modalAutorizacionEdicion' );
							this.consultaDetalleInformacion = false;
						}).catch(error =>{ 
							this.consultaDetalleInformacion = false;
							// this.showModal( 'modalAutorizacionEdicion' );
							console.log(error); 
							app.erroServidor('');
						});
					}, 
					
					reemprimirFacturaPedido(item){
						this.consultaDetalleInformacion = true;
						this.hideModal("modalListadoPedidos"); 
						axios.post( "/Estructura/verDetallePedido", "pedido=" + item.pedidoId, ).then((result) => {
							var pedido = result.data.pedido;
							var objDetalleProductosPedido = result.data.detalle;
							var objDetallePago = result.data.pagos;

							var metodoPago = ''; var metodosPagos = [];
							if ( objDetallePago.length > 0 ){
								metodoPago = (objDetallePago.length==1) ? objDetallePago[0].metodo : 'Mixto';
								objDetallePago.forEach((elemento)=>{
									if (elemento.valorPagado>0){
										metodosPagos.push({metodo:elemento.metodo, valorPagado:elemento.valorPagado})
									}
								}); 
							}

							var vacios = [undefined, null, '', 'undefined', 'null', 'None'];
							var sucursal  = alasql("select * from ? where id =" + parseInt( this.idSucursalGestion ), [ this.objSucursales ]);
							var sede  = alasql("select * from ? where id =" + parseInt( this.idSucursalGestion ), [ this.objSucursales ]);
							sede = sede[0].nombre;
							
							app.horaActualNavegador();
							var fecha = app.fechaActual; var hora = app.horaActual;
							var resolucion = ''; var resolucionPrefijo = ''; var cliente = ''; 

							var direccion = sucursal[0].direccion; var ciudad  = ""; 
							if ( !app.vacios.includes( sucursal[0].ciudadNombre ) ){
								ciudad = sucursal[0].ciudadNombre + '-Colombia';
							}
							if ( !app.vacios.includes( pedido.meseroId ) ){ mesero = pedido.meseroNombre + ' ' + pedido.meseroApellido; }
							if (!vacios.includes( pedido.resolucion )){ resolucion = pedido.resolucion;  }
							if (!vacios.includes( pedido.resolucionPrefijo )){ resolucionPrefijo = pedido.resolucionPrefijo;  }
							var cliente = ''; var clienteIdentifiacion = ''; var clienteDireccion = ''; var clienteCiudad = ""; 
							if (!app.vacios.includes(pedido.clienteId)){
								cliente = pedido.clienteNombre + " " + pedido.clienteApellido; 
								clienteIdentifiacion = pedido.clienteIdentificacion; 

								if (!app.vacios.includes(pedido.clienteDireccion)){ 
									clienteDireccion = pedido.clienteDireccion; 
								}else if (!app.vacios.includes( sucursal[0].direccion )){ 
									clienteDireccion = sucursal[0].direccion; 
								}
								
								if (!app.vacios.includes(pedido.clienteCiudadNombre)){ 
									clienteCiudad = pedido.clienteCiudadNombre; 
								}else if (!app.vacios.includes( sucursal[0].ciudadNombre )){ 
									clienteCiudad = sucursal[0].ciudadNombre; 
								}
							}else{
								cliente = "CONSUMIDOR FINAL"; 
								clienteIdentifiacion = "222222222222"; 
								if (!app.vacios.includes( sucursal[0].direccion )){ 
									clienteDireccion = sucursal[0].direccion; 
								}
								if (!app.vacios.includes( sucursal[0].ciudadNombre )){ 
									clienteCiudad = sucursal[0].ciudadNombre; 
								}
							}

							var datosImpresion = {
								pedido: pedido.pedidoId, consecutivo: pedido.consecutivo, mesa: pedido.estructuraNombre, 
								resolucion: resolucion, resolucionPrefijo: resolucionPrefijo, sucursal: sede, 
								fecha: fecha, hora: hora, celular: sucursal[0].celular, 
								email: sucursal[0].email, direccion: direccion, ciudad:ciudad, telefono: sucursal[0].telefono, 
								nit: sucursal[0].nit, metodoPago: metodoPago, metodosPagos: metodosPagos, 
								observacion: pedido.pedidoObservacion, totalCompra: pedido.pedidoPrecioTotalProductos, 
								cliente: cliente, clienteIdentifiacion: clienteIdentifiacion, clienteDireccion: clienteDireccion, clienteCiudad: clienteCiudad, 
								subtotal: pedido.pedidoSubTotal, impuesto: pedido.pedidoValorImpuesto, 
								impuestoPorcentaje: pedido.impuestoPorcentaje, descuento: pedido.pedidoTotalDescuento, 
								descuentoPorcentaje: pedido.pedidoDescuento, impoconsumo: pedido.impuestoIncluido, 
								iva: ( !vacios.includes( pedido.impuestoId ) ) ? pedido.pedidoValorImpuesto : this.dicConfiguracionVenta.idImpuesto__impuesto, 
								servicio: pedido.pedidoPropinaValor, servicioDescuento: pedido.porcentajePropina, 
								totalNeto: pedido.pedidoPrecioTotal, total: pedido.pedidoTotalNeto, 
								totalPagago: pedido.pedidoValorPagado, cambio: pedido.pedidoCambioPago, 
							}; 
							if ( app.equipoImpresion ){
								
								if (app.globalEmpresa.versionPlugin==2){
									this.impirmirOrdenPagoV3(datosImpresion, objDetalleProductosPedido);
								}else{
									this.impirmirOrdenPagoV2("", datosImpresion, objDetalleProductosPedido);
								}
							}else{
								var datosSocket = {
									accion:'Imprimir', sucursal: this.idSucursalGestion, fecha: fecha, hora: hora, 
									salon: '', mesa: pedido.estructuraNombre, pedido: pedido.pedidoId, orden: 'IMPRESION_ODEN', 
									dicPedido: datosImpresion, detalle: objDetalleProductosPedido, quitados: [], 
								};
								app.socket.emit('generacionPedido', datosSocket);
							}
							this.showModal("modalListadoPedidos"); 
							this.consultaDetalleInformacion = false;
						}).catch( error => {
							console.log("error", error);
							this.showModal("modalListadoPedidos"); 
							this.consultaDetalleInformacion = false;
							app.erroServidor( '' );
						});
					}, 

					confirmarGuardadoTemporalOrdenPedido( ventana ){
						if (this.modoDividirFacturaPedido){
							Swal.fire({
								title: '¿Dividir Factura?', type: 'warning', showCancelButton: true, allowOutsideClick: false,
								confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
							}).then((result) => {
								if (result.value) {
									this.guardadoTemporalOrdenPedido( ventana );
								}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
							});
						}else{
							this.guardadoTemporalOrdenPedido( ventana );
						}
					},

					guardadoTemporalOrdenPedido(ventana){
						this.consultaDetalleInformacion = true;
						this.aperturarEstructura = false; 
						var vacios = [undefined, null, '', 'undefined', 'null', 'None'];
						var impuesto = ( !vacios.includes( this.dicPedidoDetalle.impuestoId ) ) ? this.dicPedidoDetalle.impuestoId : this.dicConfiguracionVenta.idImpuesto__id;
						
						var objPagosId = alasql("select column id from ? where valor>=0", [this.objDetallePago]);
						var objPagosMetodo = alasql("select column metodoPago__id from ? where valor>=0", [this.objDetallePago]);
						var objPagosValor = alasql("select column valor from ? where valor>=0", [this.objDetallePago]);

						var objDivisionId = alasql("select column id from ? where valor>0", [this.objDivicionCuenta]);
						var objDivisionMetodo = alasql("select column metodoPago__id from ? where valor>0", [this.objDivicionCuenta]);
						var objDivisionValor = alasql("select column valor from ? where valor>0", [this.objDivicionCuenta]);

						var referencias = alasql( "select column referencia from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );
						var productos = alasql( "select column productoId from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );
						var productosPrecioVenta = alasql( "select column productoPrecioVenta from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );
						var productosPrecioTotal = alasql( "select column productoPrecionTotal from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );
						var cantidades = alasql( "select column productoCantidad from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );
						var notas = alasql( "select column detalleNota from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );
						var categorias = alasql( "select column categoriaId from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );
						var observaciones = alasql( "select column detalleObservacion from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );
						var descuentoDetalle = alasql( "select column detalleDescuento from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );
						var valorDescuentoDetalle = alasql( "select column detalleValorDescuento from ? where seleccionar=false", [ this.objDetalleProductosPedido ] );

						var referenciasDividirFactura = ''; var productosDividirFactura = ''; var productosPrecioVentaDividirFactura = ''; 
						var productosPrecioTotalDividirFactura = ''; var cantidadesDividirFactura = ''; var notasDividirFactura = ''; 
						var categoriasDividirFactura = ''; var observacionesDividirFactura = ''; var descuentoDetalleDividirFactura = ''; 
						var valorDescuentoDetalleDividirFactura = ''; var referenciasDividirFacturaCantidadModificada = ''; 
						if (this.modoDividirFacturaPedido){
							referenciasDividirFactura = alasql( "select column referencia from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
							productosDividirFactura = alasql( "select column productoId from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
							productosPrecioVentaDividirFactura = alasql( "select column productoPrecioVenta from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
							productosPrecioTotalDividirFactura = alasql( "select column productoPrecionTotal from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
							cantidadesDividirFactura = alasql( "select column productoCantidad from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
							notasDividirFactura = alasql( "select column detalleNota from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
							categoriasDividirFactura = alasql( "select column categoriaId from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
							observacionesDividirFactura = alasql( "select column detalleObservacion from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
							descuentoDetalleDividirFactura = alasql( "select column detalleDescuento from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );
							valorDescuentoDetalleDividirFactura = alasql( "select column detalleValorDescuento from ? where seleccionar=true", [ this.objDetalleProductosPedido ] );

							referenciasDividirFacturaCantidadModificada = alasql( "select column referencia from ? where seleccionar=true and productoCantidad<productoCantidadModificada", [ this.objDetalleProductosPedido ] );
						}

						axios.post( "/Estructura/guardadoTemporalOrdenPedido" , 
							"pedido=" + this.dicPedidoDetalle.pedidoId +
							"&&dividirCuenta=" + this.modoDividirFacturaPedido +
							"&&cliente=" + this.idClientePedido +
							"&&impuesto=" + impuesto +
							"&&estado=" + "Pagado" +
							"&&metodoPago=" + this.dicPedidoDetalle.pedidoMetodoPago +
							"&&estructura=" + this.dicPedidoDetalle.estructuraId +
							"&&aperturarEstructura=" + app.procesarTrueFalse(this.aperturarEstructura) +
							"&&pedidoOrdenPago=" + app.procesarTrueFalse(this.pedidoOrdenPago) +
							"&&pedidoMesaLiberada=" + app.procesarTrueFalse(this.dicPedidoDetalle.pedidoMesaLiberada) +

							"&&observacion=" + this.dicPedidoDetalle.pedidoObservacion +

							"&&objPagosId=" + objPagosId +
							"&&objPagosMetodo=" + objPagosMetodo +
							"&&objPagosValor=" + objPagosValor +
							
							"&&objDivisionId=" + objDivisionId +
							"&&objDivisionMetodo=" + objDivisionMetodo +
							"&&objDivisionValor=" + objDivisionValor +
							
							"&&referencias=" + referencias +
							"&&productos=" + productos +
							"&&productosPrecioVenta=" + productosPrecioVenta +
							"&&productosPrecioTotal=" + productosPrecioTotal +
							"&&cantidades=" + cantidades +
							"&&notas=" + notas +
							"&&categorias=" + categorias +
							"&&observaciones=" + observaciones +
							"&&descuentoDetalle=" + descuentoDetalle +
							"&&valorDescuentoDetalle=" + valorDescuentoDetalle +

							"&&referenciasDividirFactura=" + referenciasDividirFactura +
							"&&productosDividirFactura=" + productosDividirFactura +
							"&&productosPrecioVentaDividirFactura=" + productosPrecioVentaDividirFactura +
							"&&productosPrecioTotalDividirFactura=" + productosPrecioTotalDividirFactura +
							"&&cantidadesDividirFactura=" + cantidadesDividirFactura +
							"&&notasDividirFactura=" + notasDividirFactura +
							"&&categoriasDividirFactura=" + categoriasDividirFactura +
							"&&observacionesDividirFactura=" + observacionesDividirFactura +
							"&&descuentoDetalleDividirFactura=" + descuentoDetalleDividirFactura +
							"&&valorDescuentoDetalleDividirFactura=" + valorDescuentoDetalleDividirFactura +
							"&&referenciasDividirFacturaCantidadModificada=" + referenciasDividirFacturaCantidadModificada +
							
							"&&propina=" + app.procesarTrueFalse(this.aplicarServicioPropina) +
							"&&descuento=" + this.dicPedidoDetalle.pedidoDescuento +
							"&&totalDescuento=" + this.dicPedidoDetalle.pedidoTotalDescuento +
							"&&totalNeto=" + this.dicPedidoDetalle.pedidoTotalNeto +
							"&&propinaModificada=" + app.procesarTrueFalse(this.dicPedidoDetalle.propinaModificada) +
							"&&porcentajePropina=" + this.dicPedidoDetalle.porcentajePropina +
							"&&cuponId=" + this.dicPedidoDetalle.cuponId +

							"&&comensales=" + this.dicPedidoDetalle.comensales +
							"&&totalPromedioConsumo=" + this.dicPedidoDetalle.totalPromedioConsumo +
							
							"&&valorImpuesto=" + this.dicPedidoDetalle.pedidoValorImpuesto +
							"&&precioTotal=" + this.dicPedidoDetalle.pedidoPrecioTotal +
							"&&subTotal=" + this.dicPedidoDetalle.pedidoSubTotal +
							"&&propinaValor=" + this.dicPedidoDetalle.pedidoPropinaValor +
							"&&valorPagado=" + this.dicPedidoDetalle.pedidoValorPagado +
							"&&cambioPago=" + this.dicPedidoDetalle.pedidoCambioPago +
							
							"&&usuario=" + app.usuarioActual.usuario, 
						).then((result) => {
							setTimeout(()=>{
								if ( result.data.mensaje == 'Registro Exitoso' ){
									if (this.modoDividirFacturaPedido){
										this.dicPedidoDetalle.pedidoId = result.data.pedido; 
										this.recargarPedido = true; 
									}
									this.idPedidoGestion = this.dicPedidoDetalle.pedidoId;

									var sede  = alasql("select * from ? where id =" + parseInt( this.idSucursalGestion ), [ this.objSucursales ]);
									sede = sede[0].nombre;
									var fecha = app.fechaActual;
									app.horaActualNavegador();
									var hora = app.horaActual;

									var datosImpresion = {
										pedido: this.dicPedidoDetalle.pedidoId, 
										consecutivo: this.dicPedidoDetalle.consecutivo, 
										mesa: this.dicPedidoDetalle.estructuraNombre, 
										sucursal: sede, 
										fecha: fecha, 
										hora: hora, 
										observacion: this.dicPedidoDetalle.pedidoObservacion, 
										subtotal: this.dicPedidoDetalle.pedidoSubTotal, 
										impuesto: this.dicPedidoDetalle.pedidoValorImpuesto, 
										descuento: this.dicPedidoDetalle.pedidoTotalDescuento, 
										impoconsumo: this.dicPedidoDetalle.impuestoIncluido, 
										iva: ( !vacios.includes( this.dicPedidoDetalle.impuestoId ) ) ? this.dicPedidoDetalle.pedidoValorImpuesto : this.dicConfiguracionVenta.idImpuesto__impuesto, 
										servicio: this.dicPedidoDetalle.pedidoPropinaValor, 
										totalNeto: this.dicPedidoDetalle.pedidoPrecioTotal, 
										total: this.dicPedidoDetalle.pedidoTotalNeto, 
									}; 

									this.verDetallePedidoV2();
								}else{
									Swal.fire( { title:'¡Error de Registro!', type:'error', showConfirmButton: false, timer:2000 } );
									this.consultaDetalleInformacion = false;
								}
							});
						}).catch( error => {
							this.consultaDetalleInformacion = false;
							app.erroServidor( '' );
						});
					}, 

					agregarEspacioCantidad( valor ){
						if ( String( valor ).length == 1 ){ return valor + "  "; }
						if ( String( valor ).length == 2 ){ return valor + " "; }
						if ( String( valor ).length == 3 ){ return valor; }
						if ( String( valor ).length > 3 ){ return String(valor).substr(0,3); }
					}, 

					validarCaracteresProducto( valor ){
						if ( String(valor).length == 23 ){ return valor; }
						if ( String(valor).length < 23 ){ 
							var caracteres = 22 - String(valor).length;
							for ( var i = 0; i < caracteres; i++ ){ valor = valor + " "; }
							return valor;
						}
						if ( String(valor).length > 23 ){ return valor.substr( 0, 22 ); }
					}, 

					agregarEspacioDescuento( valor ){
						if ( String( valor ).length == 1 ){ return "  " + valor; }
						if ( String( valor ).length == 2 ){ return " " + valor; }
						if ( String( valor ).length == 3 ){ return valor; }
						if ( String( valor ).length == 4 ){ return valor; }
						if ( String( valor ).length >=5 ){ return String(valor).substr(0,5); }
					}, 

					validarCaracteresCantidad( valor ){
						if ( String(valor).length == 11 ){ return valor; }
						if ( String(valor).length < 11 ){ 
							var caracteres = 11 - String(valor).length;
							for ( var i = 0; i < caracteres; i++ ){ valor =  " " + valor; }
							return valor;
						}
						if ( String(valor).length > 11 ){ return String(valor).substr( 0, 11 ); }
					}, 

					procesarTotalPagarImpresion(valor){
						if ( String(valor).length == 15 ){ return valor; }
						if ( String(valor).length < 15 ){ 
							var caracteres = 15 - String(valor).length;
							for ( var i = 0; i < caracteres; i++ ){ valor =  " " + valor; }
							return valor;
						}
						if ( String(valor).length > 15 ){ return String(valor).substr( 0, 14 ); }
					},
					procesarPorcentajeImpresion(valor){
						if ( String(valor).length == 5 ){ return valor; }
						if ( String(valor).length < 5 ){ 
							var caracteres = 5 - String(valor).length;
							for ( var i = 0; i < caracteres; i++ ){ valor =  " " + valor; }
							return valor;
						}
						if ( String(valor).length >=6 ){ return String(valor).substr( 0, 5 ); }
					},

					moneda( valor ){ return app.$options.filters.currency(valor); },

					cantidadC( valor ){ return app.$options.filters.currency(valor, ''); },

					impirmirOrdenPago(  ventana ){
						this.impresora.operaciones = [];
						this.impresora.cut();

						var sede  = alasql("select * from ? where id =" + parseInt( this.idSucursalGestion ), [ this.objSucursales ]);
						sede = sede[0].nombre;
						var fecha = app.fechaActual;
						app.horaActualNavegador();
						var hora = app.horaActual;

						var totalPagar = 0; var totalPagar = 0;
						this.impresora.setAlign( C.AlineacionCentro );
						this.impresora.write( "................................................\n");
						this.impresora.write( "ORDEN DE PAGO N: " + this.dicPedidoDetalle.consecutivo + "\n");
						this.impresora.write( "................................................\n");
						this.impresora.write( app.procesarAcentos(sede) + "\n");
						
						this.impresora.write( "NIT: 71751281" + "\n"); 						
						this.impresora.write( "Santa Elena ant" + "\n"); 
						this.impresora.write( "(305) 244-1188" + "\n"); 
						
						this.impresora.write( "................................................\n");
						this.impresora.setAlign( C.AlineacionIzquierda );
						this.impresora.write( "Fecha: " + fecha + "   Hora: " + hora + "\n");
						if ( !app.vacios.includes( this.dicConfiguracionVenta.cajero ) ){
							this.impresora.write( "Cajero: " + app.procesarAcentos( this.dicConfiguracionVenta.cajero ) + "\n");
						}
						this.impresora.write( "Mesa: " + this.dicPedidoDetalle.estructuraNombre + "   Pedido: " + this.dicPedidoDetalle.pedidoId + "\n");
						if ( this.dicPedidoDetalle.meseroId!='' && this.dicPedidoDetalle.meseroId!=null && this.dicPedidoDetalle.meseroId!=undefined ){
							this.impresora.write( "Mesero: " + this.dicPedidoDetalle.meseroNombre + ' ' + this.dicPedidoDetalle.meseroApellido + "\n");
						}
						this.impresora.write( "................................................\n");
						this.impresora.write( " Cant           Producto                 Total  \n");
						this.impresora.write( "................................................\n");

						this.objDetalleProductosPedido.forEach( elemento => {
							totalPagar = totalPagar + (elemento.productoPrecioVenta * elemento.productoCantidad);
							this.impresora.write(" " + this.agregarEspacioCantidad(elemento.productoCantidad) + "  " + this.validarCaracteresProducto(app.procesarAcentos( elemento.productoNombre )) + " " + this.validarCaracteresCantidad(this.moneda(elemento.productoPrecioVenta * elemento.productoCantidad)) + "\n");
						});
						console.log("totalPrecioProductos ------> ------> ", totalPrecioProductos);
						console.log("totalPagar -------> -------> ", totalPagar);
						this.impresora.write( "................................................\n");
						this.impresora.write( "Total:                         " + this.procesarTotalPagarImpresion(this.moneda(totalPagar)) + "\n");
						this.impresora.write( "................................................\n");
						this.impresora.write( "Total Items: " + this.cantidadC(this.objDetalleProductosPedido.length) + "\n");
						if ( pedido.observacion !== '' ){
							this.impresora.write( "................................................\n");
							this.impresora.write( "Observacion: " + pedido.observacion + "\n");
						}
						

						if ( this.objConfiguracionesVentas.length > 0 ){
							if ( !app.vacios.includes( this.dicConfiguracionVenta.resolucion ) ){
								this.impresora.write( "................................................\n");
								this.impresora.write( app.procesarAcentos( this.dicConfiguracionVenta.resolucion ) + "\n");
							}
						}

						this.impresora.feed(3);
						this.impresora.cut();
						console.log("----....", this.impresora);
						this.impresora.imprimirEnImpresora( app.globalEmpresa.impresoraFacturacion );
						this.hideModal( ventana );
					}, 

					impirmirOrdenPagoV2(  ventana, pedido, detalle ){
						console.log("PEDIDO --- ", pedido);
						console.log("DETALLE --- ", detalle);
						this.impresora.operaciones = [];

						var sede  = alasql("select * from ? where id =" + parseInt( this.idSucursalGestion ), [ this.objSucursales ]);
						sede = sede[0].nombre;
						var fecha = app.fechaActual;
						app.horaActualNavegador();
						var hora = app.horaActual;

						var totalPagar = 0; var totalPrecioProductos = 0;
						this.impresora.setAlign( C.AlineacionCentro );
						this.impresora.write( "................................................\n");
						if ( !app.vacios.includes( pedido.resolucionPrefijo ) ){
							this.impresora.write( "Documento Equivalente Electronico P.O.S " + pedido.resolucionPrefijo + " " + pedido.consecutivo + "\n");
						}else{
							this.impresora.write( "Documento Equivalente Electronico P.O.S " + pedido.consecutivo + "\n");
						}
						
						this.impresora.write( "................................................\n");
						this.impresora.write( app.procesarAcentos(pedido.sucursal) + "\n");
						this.impresora.write( "NIT: " + pedido.nit + "\n"); 
						if (!app.vacios.includes(pedido.direccion)){ this.impresora.write( app.procesarAcentos(pedido.direccion) + "\n"); }
						if (!app.vacios.includes(pedido.email)){ this.impresora.write( pedido.email + "\n"); }
						if (!app.vacios.includes(pedido.ciudad)){ this.impresora.write( app.procesarAcentos(pedido.ciudad) + "\n"); }

						this.impresora.write( "................................................\n");
						this.impresora.setAlign( C.AlineacionIzquierda );
						this.impresora.write( "Fecha: " + fecha + "  Hora: " + hora + "\n");
						this.impresora.write( "Forma De Pago: Contado\n");
						if ( !app.vacios.includes( this.dicConfiguracionVenta.cajero ) ){ this.impresora.write( "Cajero: " + app.procesarAcentos( this.dicConfiguracionVenta.cajero ) + "\n"); }
						this.impresora.write( "Mesa: " + pedido.mesa + "\n");
						if ( pedido.mesero!='' && pedido.mesero!=null && pedido.mesero!=undefined ){ this.impresora.write( "Mesero: " + pedido.mesero + "\n"); }

						if ( pedido.cliente!='' && pedido.cliente!=null && pedido.cliente!=undefined ){
							this.impresora.write( "................................................\n");
							this.impresora.write( "CC/NIT: " + pedido.clienteIdentifiacion + "\n");
							this.impresora.write( "Cliente: " + app.procesarAcentos(pedido.cliente) + "\n");
							if (!app.vacios.includes(pedido.clienteDireccion)){ 
								this.impresora.write( "Direccion: " + app.procesarAcentos(pedido.clienteDireccion) + "\n");
							}
							if (!app.vacios.includes(pedido.clienteCiudad)){ 
								this.impresora.write( "Ciudad: " + app.procesarAcentos(pedido.clienteCiudad) + "\n");
							}
						}

						
						this.impresora.write( "................................................\n");
						this.impresora.write( " Cant           Producto       Desc      Total  \n");
						this.impresora.write( "................................................\n");

						detalle.forEach( elemento => {
							totalPagar = totalPagar + ((elemento.productoPrecioVenta * elemento.productoCantidad) - elemento.detalleValorDescuento);
							totalPrecioProductos = totalPrecioProductos + (elemento.productoPrecioVenta * elemento.productoCantidad);
							this.impresora.write(" " + this.agregarEspacioCantidad(elemento.productoCantidad) + "  " + 
								this.validarCaracteresProducto(app.procesarAcentos( elemento.productoNombre )) + "   " + 
								this.agregarEspacioDescuento( elemento.detalleDescuento ) + " " + 
								this.validarCaracteresCantidad(this.moneda(((elemento.productoPrecioVenta * elemento.productoCantidad) - elemento.detalleValorDescuento))) + "\n");
						});
						console.log("totalPrecioProductos ------> ------> ", totalPrecioProductos);
						console.log("totalPagar -------> -------> ", totalPagar);
						this.impresora.write( "................................................\n");
						this.impresora.write( "Subtotal:                      " + this.procesarTotalPagarImpresion(this.moneda(pedido.totalCompra)) + "\n");
						if (parseFloat(pedido.descuento)>0){
							this.impresora.write( "Descuento: (" + this.procesarPorcentajeImpresion(pedido.descuentoPorcentaje) + "%)              " + this.procesarTotalPagarImpresion(this.moneda(pedido.descuento)) + "\n");
							this.impresora.write( "Subtotal - Descuento:          " + this.procesarTotalPagarImpresion(this.moneda(parseFloat(pedido.totalCompra)-parseFloat(pedido.descuento))) + "\n");
						}
						if ( parseFloat( pedido.impuesto ) > 0 ){
							this.impresora.write( "Impoconsumo: (" + this.procesarPorcentajeImpresion(pedido.impuestoPorcentaje) + "%)            " + this.procesarTotalPagarImpresion(this.moneda(pedido.impuesto)) + "\n");
							if ( pedido.impoconsumo == 0){
								this.impresora.write( "Subtotal - Impoconsumo:        " + this.procesarTotalPagarImpresion(this.moneda((parseFloat(pedido.totalCompra)-parseFloat(pedido.descuento))-parseFloat(pedido.impuesto))) + "\n");
							}else{
								this.impresora.write( "Subtotal + Impoconsumo:        " + this.procesarTotalPagarImpresion(this.moneda((parseFloat(pedido.totalCompra)-parseFloat(pedido.descuento))+parseFloat(pedido.impuesto))) + "\n");
							}
						}
						this.impresora.write( "Total Neto:                    " + this.procesarTotalPagarImpresion(this.moneda(pedido.totalNeto)) + "\n");
						this.impresora.write( "Servicio: (" + this.procesarPorcentajeImpresion(pedido.servicioDescuento) + "%)               " + this.procesarTotalPagarImpresion(this.moneda(pedido.servicio)) + "\n");
						this.impresora.write( "................................................\n");
						this.impresora.write( "Total Compra:                  " + this.procesarTotalPagarImpresion(this.moneda(pedido.total)) + "\n");
						this.impresora.write( "Total Recibido:                " + this.procesarTotalPagarImpresion(this.moneda(pedido.totalPagago)) + "\n");
						this.impresora.write( "Cambio:                        " + this.procesarTotalPagarImpresion(this.moneda(pedido.cambio)) + "\n");
						this.impresora.write( "Total Items: " + this.cantidadC(detalle.length) + "\n");
						if ( pedido.metodoPago !== '' ){
							this.impresora.write( "................................................\n");
							pedido.metodosPagos.forEach((elemento)=>{
								this.impresora.write( elemento.metodo + ": " + this.moneda(elemento.valorPagado) + "\n");
							});
						}
						if ( pedido.observacion !== '' ){
							this.impresora.write( "................................................\n");
							this.impresora.write( "Observacion: " + pedido.observacion + "\n");
						}

						var resolucion = !app.vacios.includes( pedido.resolucion ) ? pedido.resolucion : this.dicConfiguracionVenta.resolucion; 
						if ( !app.vacios.includes( resolucion ) ){
							this.impresora.write( "................................................\n");
							this.impresora.write( app.procesarAcentos( resolucion ) + "\n");
						}

						this.impresora.write( "................................................\n");
						var responsableIva = this.dicConfiguracionVenta.responsableIva ? "Responsable De IVA" : "NO Responsable De IVA"; 
						this.impresora.write( app.procesarAcentos( responsableIva ) + "\n");
						var autorretenedor = this.dicConfiguracionVenta.autorretenedor ? "Somos Autorretenedores" : "NO Somos Autorretenedores"; 
						this.impresora.write( app.procesarAcentos( autorretenedor ) + "\n");
						var granContribuyecte = this.dicConfiguracionVenta.granContribuyecte ? "Somos Grandes contribuyentes" : "NO Somos Grandes contribuyentes"; 
						this.impresora.write( app.procesarAcentos( granContribuyecte ) + "\n");
						

						if (!app.vacios.includes(this.dicConfiguracionVenta.cufe) || !app.vacios.includes(this.dicConfiguracionVenta.firmaDigital) || !app.vacios.includes(this.dicConfiguracionVenta.urlQr)){
							this.impresora.write( "................................................\n");
						}
						if ( !app.vacios.includes( this.dicConfiguracionVenta.firmaDigital ) ){
							this.impresora.write( "Firma Digital: " + this.dicConfiguracionVenta.firmaDigital + "\n");
						}
						if ( !app.vacios.includes( this.dicConfiguracionVenta.cufe ) ){
							this.impresora.write( "\n");
							this.impresora.write( "CUFE: " + this.dicConfiguracionVenta.cufe + "\n");
						}
						if ( !app.vacios.includes( this.dicConfiguracionVenta.urlQr ) ){
							this.impresora.write( "\n");
							this.impresora.setAlign( C.AlineacionCentro );
							this.impresora.qr(this.dicConfiguracionVenta.urlQr);
						}

						this.impresora.write( "\n");
						this.impresora.setAlign( C.AlineacionCentro );
						this.impresora.write( "Documento elaborado por Size Soluciones a la Medida S.A.S Nit 901197754-9 PBX 5897948\n");

						this.impresora.cut();
						console.log("----....", this.impresora);
						this.impresora.imprimirEnImpresora( app.globalEmpresa.impresoraFacturacion );

						if (pedido.dobleImpresion){
							setTimeout(()=>{
								this.impresora.imprimirEnImpresora( app.globalEmpresa.impresoraFacturacion );
							}, 1000); 
						}
					}, 

					impirmirOrdenPagoV3(pedido, detalle){
						var sede  = alasql("select * from ? where id =" + parseInt( this.idSucursalGestion ), [ this.objSucursales ]);
						sede = sede[0].nombre;
						var fecha = app.fechaActual;
						app.horaActualNavegador();
						var hora = app.horaActual;
						var totalPagar = 0; var totalPrecioProductos = 0;
						
						var conector = new ConectorPluginV3(); 
						conector.Iniciar(); 
						conector.operaciones = []; 
						conector.Feed(2); 
						conector.serial = app.globalEmpresa.licenciaPluginImpresoraV3; 
		
						conector.EstablecerFuente(0); /* 0 o 1 */
						conector.EstablecerTamañoFuente(1, 1);
						conector.EstablecerEnfatizado(true);
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
						if(!app.vacios.includes(this.dicConfiguracionVenta.imagenImpresion)){
							var urlImagen = window.location.origin + "/media/configuraciones/puntoventa/" + this.dicConfiguracionVenta.imagenImpresion; 
							conector.DescargarImagenDeInternetEImprimir(urlImagen, 250, ConectorPluginV3.ALGORITMO_IMAGEN_RASTERIZACION); 
							conector.Feed(1); 
						}

						conector.TextoSegunPaginaDeCodigos(2, "cp850", "Documento Equivalente Electrónico P.O.S "+pedido.consecutivo+"\n");
						conector.TextoSegunPaginaDeCodigos(2, "cp850", pedido.sucursal+"\n");
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "NIT: " + pedido.nit+"\n"); 
						if (!app.vacios.includes(pedido.direccion)){ conector.TextoSegunPaginaDeCodigos(2, "cp850", pedido.direccion+"\n"); }
						if (!app.vacios.includes(pedido.email)){ conector.TextoSegunPaginaDeCodigos(2, "cp850", pedido.email+"\n"); }
						if (!app.vacios.includes(pedido.ciudad)){ conector.TextoSegunPaginaDeCodigos(2, "cp850", pedido.ciudad+"\n"); }
						conector.EscribirTexto( "................................................\n");
						
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_IZQUIERDA); 
						conector.EscribirTexto("Fecha: "+fecha+"  Hora: "+hora+"\n");
						conector.EscribirTexto("Forma De Pago: Contado\n");
						if (!app.vacios.includes(this.dicConfiguracionVenta.cajero)){ conector.TextoSegunPaginaDeCodigos(2, "cp850", "Cajero: "+this.dicConfiguracionVenta.cajero+"\n"); }
						conector.EscribirTexto( "Mesa: " + pedido.mesa + "\n");
						if (pedido.mesero!='' && pedido.mesero!=null && pedido.mesero!=undefined){ conector.TextoSegunPaginaDeCodigos(2, "cp850", "Mesero: "+pedido.mesero+"\n"); }

						if (pedido.cliente!='' && pedido.cliente!=null && pedido.cliente!=undefined){
							conector.EscribirTexto( "................................................\n");
							conector.TextoSegunPaginaDeCodigos(2, "cp850", "CC/NIT: "+pedido.clienteIdentifiacion+"\n");
							conector.TextoSegunPaginaDeCodigos(2, "cp850", "Cliente: "+pedido.cliente+"\n");
							if (!app.vacios.includes(pedido.clienteDireccion)){ 
								conector.TextoSegunPaginaDeCodigos(2, "cp850", "Direccion: "+pedido.clienteDireccion+"\n");
							}
							if (!app.vacios.includes(pedido.clienteCiudad)){ 
								conector.TextoSegunPaginaDeCodigos(2, "cp850", "Ciudad: "+pedido.clienteCiudad+"\n");
							}
						}

						conector.EscribirTexto( "................................................\n");
						conector.EscribirTexto( " Cant           Producto       Desc      Total  \n");
						conector.EscribirTexto( "................................................\n");

						detalle.forEach( elemento => {
							totalPagar = totalPagar + ((elemento.productoPrecioVenta * elemento.productoCantidad) - elemento.detalleValorDescuento);
							totalPrecioProductos = totalPrecioProductos + (elemento.productoPrecioVenta * elemento.productoCantidad);
							conector.TextoSegunPaginaDeCodigos(2, "cp850", " "+this.agregarEspacioCantidad(elemento.productoCantidad)+"  "+ 
								this.validarCaracteresProducto(elemento.productoNombre )+"   "+ this.agregarEspacioDescuento(elemento.detalleDescuento)+" "+ 
								this.validarCaracteresCantidad(this.moneda(((elemento.productoPrecioVenta * elemento.productoCantidad) - elemento.detalleValorDescuento))) + "\n");
						});

						conector.EscribirTexto( "................................................\n");
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "Subtotal:                      " + this.procesarTotalPagarImpresion(this.moneda(pedido.totalCompra)) + "\n");
						if (parseFloat(pedido.descuento)>0){
							conector.TextoSegunPaginaDeCodigos(2, "cp850", "Descuento: (" + this.procesarPorcentajeImpresion(pedido.descuentoPorcentaje) + "%)            " + this.procesarTotalPagarImpresion(this.moneda(pedido.descuento)) + "\n");
							conector.TextoSegunPaginaDeCodigos(2, "cp850", "Subtotal - Descuento:          " + this.procesarTotalPagarImpresion(this.moneda(parseFloat(pedido.totalCompra)-parseFloat(pedido.descuento))) + "\n");
						}
						if ( parseFloat( pedido.impuesto ) > 0 ){
							conector.TextoSegunPaginaDeCodigos(2, "cp850", "Impoconsumo: (" + this.procesarPorcentajeImpresion(pedido.impuestoPorcentaje) + "%)          " + this.procesarTotalPagarImpresion(this.moneda(pedido.impuesto)) + "\n");
							if ( pedido.impoconsumo == 0){
								conector.TextoSegunPaginaDeCodigos(2, "cp850", "Subtotal - Impoconsumo:        " + this.procesarTotalPagarImpresion(this.moneda((parseFloat(pedido.totalCompra)-parseFloat(pedido.descuento))-parseFloat(pedido.impuesto))) + "\n");
							}else{
								conector.TextoSegunPaginaDeCodigos(2, "cp850", "Subtotal + Impoconsumo:        " + this.procesarTotalPagarImpresion(this.moneda((parseFloat(pedido.totalCompra)-parseFloat(pedido.descuento))+parseFloat(pedido.impuesto))) + "\n");
							}
						}
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "Total Neto:                    " + this.procesarTotalPagarImpresion(this.moneda(pedido.totalNeto)) + "\n");
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "Servicio: (" + this.procesarPorcentajeImpresion(pedido.servicioDescuento) + "%)             " + this.procesarTotalPagarImpresion(this.moneda(pedido.servicio)) + "\n");
						conector.EscribirTexto( "................................................\n");
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "Total Compra:                  " + this.procesarTotalPagarImpresion(this.moneda(pedido.total)) + "\n");
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "Total Recibido:                " + this.procesarTotalPagarImpresion(this.moneda(pedido.totalPagago)) + "\n");
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "Cambio:                        " + this.procesarTotalPagarImpresion(this.moneda(pedido.cambio)) + "\n");
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "Total Items: " + this.cantidadC(detalle.length) + "\n");
						if ( pedido.metodoPago !== '' ){
							conector.EscribirTexto( "................................................\n");
							pedido.metodosPagos.forEach((elemento)=>{
								conector.TextoSegunPaginaDeCodigos(2, "cp850", elemento.metodo + ": " + this.moneda(elemento.valorPagado) + "\n");
							});
						}
						if ( pedido.observacion !== '' ){
							conector.EscribirTexto( "................................................\n");
							conector.TextoSegunPaginaDeCodigos(2, "cp850", "Observacion: " + pedido.observacion + "\n");
						}

						var resolucion = !app.vacios.includes( pedido.resolucion ) ? pedido.resolucion : this.dicConfiguracionVenta.resolucion; 
						if ( !app.vacios.includes( resolucion ) ){
							conector.EscribirTexto( "................................................\n");
							conector.TextoSegunPaginaDeCodigos(2, "cp850", resolucion+"\n");
						}

						conector.EscribirTexto( "................................................\n");
						var responsableIva = this.dicConfiguracionVenta.responsableIva ? "Responsable De IVA" : "NO Responsable De IVA"; 
						conector.TextoSegunPaginaDeCodigos(2, "cp850", responsableIva+"\n");
						var autorretenedor = this.dicConfiguracionVenta.autorretenedor ? "Somos Autorretenedores" : "NO Somos Autorretenedores"; 
						conector.TextoSegunPaginaDeCodigos(2, "cp850", autorretenedor+"\n");
						var granContribuyecte = this.dicConfiguracionVenta.granContribuyecte ? "Somos Grandes contribuyentes" : "NO Somos Grandes contribuyentes"; 
						conector.TextoSegunPaginaDeCodigos(2, "cp850", granContribuyecte+"\n");
						

						if (!app.vacios.includes(this.dicConfiguracionVenta.cufe) || !app.vacios.includes(this.dicConfiguracionVenta.firmaDigital) || !app.vacios.includes(this.dicConfiguracionVenta.urlQr)){
							conector.EscribirTexto( "................................................\n");
						}
						if ( !app.vacios.includes( this.dicConfiguracionVenta.firmaDigital ) ){
							conector.TextoSegunPaginaDeCodigos(2, "cp850", "Firma Digital: " + this.dicConfiguracionVenta.firmaDigital + "\n");
						}
						if ( !app.vacios.includes( this.dicConfiguracionVenta.cufe ) ){
							conector.EscribirTexto( "\n");
							conector.TextoSegunPaginaDeCodigos(2, "cp850", "CUFE: " + this.dicConfiguracionVenta.cufe + "\n");
						}
						if ( !app.vacios.includes( this.dicConfiguracionVenta.urlQr ) ){
							conector.EscribirTexto( "\n");
							conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
							conector.ImprimirCodigoQr(this.dicConfiguracionVenta.urlQr, 160, ConectorPluginV3.RECUPERACION_QR_MEJOR, 0);
						}

						conector.EscribirTexto( "\n");
						conector.EstablecerAlineacion(ConectorPluginV3.ALINEACION_CENTRO); 
						conector.TextoSegunPaginaDeCodigos(2, "cp850", "Documento elaborado por Size Soluciones a la Medida S.A.S Nit 901197754-9 PBX 5897948\n");

						conector.Feed(3);
						conector.Corte(2);
						conector.Pulso(48, 60, 120);

						conector.imprimirEn( app.globalEmpresa.impresoraFacturacion );
						if (pedido.dobleImpresion){
							setTimeout(()=>{
								conector.imprimirEn( app.globalEmpresa.impresoraFacturacion );
							}, 1000); 
						}						
					}, 

					impirmirOrdenPagoV2Copia1(  ventana, pedido, detalle ){
						console.log("PEDIDO --- ", pedido);
						console.log("DETALLE --- ", detalle);
						this.impresora.operaciones = [];
						// this.impresora.cut();

						var sede  = alasql("select * from ? where id =" + parseInt( this.idSucursalGestion ), [ this.objSucursales ]);
						sede = sede[0].nombre;
						var fecha = app.fechaActual;
						app.horaActualNavegador();
						var hora = app.horaActual;

						var totalPagar = 0; var totalPrecioProductos = 0;
						this.impresora.setAlign( C.AlineacionCentro );
						this.impresora.write( "................................................\n");
						this.impresora.write( "FACTURA DE VENTA N: " + pedido.consecutivo + "\n");
						this.impresora.write( "................................................\n");
						this.impresora.write( app.procesarAcentos(pedido.sucursal) + "\n");
						
						// this.impresora.write( "NIT: 901372177-9" + "\n"); //Socarrat
						// this.impresora.write( "NIT: 901375461-1" + "\n"); // district1
						// this.impresora.write( "NIT: 71751281" + "\n"); // promesa
						this.impresora.write( "NIT: " + pedido.nit + "\n"); 
						
						//this.impresora.write( "Dirección: Calle 40 # 74 - 88" + "\n"); // district1
						// this.impresora.write( "Dirección: Cl. 20 Sur #27-55, Envigado- Antioquia, San Lucas Plaza" + "\n"); //Socarrat
						// this.impresora.write( "Santa Elena ant" + "\n"); // promesa
						this.impresora.write( app.procesarAcentos(pedido.direccion) + "\n");
						
						// this.impresora.write( "5909465 - 324 2534795" + "\n"); // district1
						// this.impresora.write( "320 7764940" + "\n"); //Socarrat
						// this.impresora.write( "(305) 244-1188" + "\n"); // promesa
						this.impresora.write( pedido.celular + "\n");

						this.impresora.write( "................................................\n");
						this.impresora.setAlign( C.AlineacionIzquierda );
						this.impresora.write( "Fecha: " + pedido.fecha + "   Hora: " + pedido.hora + "\n");
						if ( !app.vacios.includes( this.dicConfiguracionVenta.cajero ) ){
							this.impresora.write( "Cajero: " + app.procesarAcentos( this.dicConfiguracionVenta.cajero ) + "\n");
						}
						this.impresora.write( "Mesa: " + pedido.mesa + "   Pedido: " + pedido.pedido + "\n");
						this.impresora.write( "................................................\n");
						this.impresora.write( " Cant           Producto       Desc      Total  \n");
						this.impresora.write( "................................................\n");

						detalle.forEach( elemento => {
							totalPagar = totalPagar + ((elemento.productoPrecioVenta * elemento.productoCantidad) - elemento.detalleValorDescuento);
							totalPrecioProductos = totalPrecioProductos + (elemento.productoPrecioVenta * elemento.productoCantidad);
							this.impresora.write(" " + this.agregarEspacioCantidad(elemento.productoCantidad) + "  " + 
								this.validarCaracteresProducto(app.procesarAcentos( elemento.productoNombre )) + "   " + 
								this.agregarEspacioDescuento( elemento.detalleDescuento ) + " " + 
								this.validarCaracteresCantidad(this.moneda(((elemento.productoPrecioVenta * elemento.productoCantidad) - elemento.detalleValorDescuento))) + "\n");
						});
						console.log("totalPrecioProductos ------> ------> ", totalPrecioProductos);
						console.log("totalPagar -------> -------> ", totalPagar);
						this.impresora.write( "................................................\n");
						this.impresora.write( "Precio Total:                      " + this.procesarTotalPagarImpresion(this.moneda(pedido.totalCompra)) + "\n");
						this.impresora.write( "Subtotal:                      " + this.procesarTotalPagarImpresion(this.moneda(pedido.subtotal)) + "\n");
						this.impresora.write( "................................................\n");
						this.impresora.write( "Impuesto:                      " + this.procesarTotalPagarImpresion(this.moneda(pedido.impuesto)) + "\n");
						this.impresora.write( "Descuento:                     " + this.procesarTotalPagarImpresion(this.moneda(pedido.descuento)) + "\n");
						this.impresora.write( "................................................\n");
						this.impresora.write( "Total Neto:                    " + this.procesarTotalPagarImpresion(this.moneda(pedido.totalNeto)) + "\n");
						this.impresora.write( "................................................\n");
						this.impresora.write( "Servicio:                      " + this.procesarTotalPagarImpresion(this.moneda(pedido.servicio)) + "\n");
						this.impresora.write( "................................................\n");
						this.impresora.write( "Total a Pagar:                 " + this.procesarTotalPagarImpresion(this.moneda(pedido.total)) + "\n");
						this.impresora.write( "................................................\n");
						this.impresora.write( "Total Items: " + this.cantidadC(detalle.length) + "\n");
						if ( pedido.metodoPago !== '' ){
							this.impresora.write( "................................................\n");
							this.impresora.write( "Metodo Pago: " + pedido.metodoPago + "\n");
						}
						if ( pedido.observacion !== '' ){
							this.impresora.write( "................................................\n");
							this.impresora.write( "Observacion: " + pedido.observacion + "\n");
						}

						if ( this.objConfiguracionesVentas.length > 0 ){
							if ( !app.vacios.includes( this.dicConfiguracionVenta.resolucion ) ){
								this.impresora.write( "................................................\n");
								this.impresora.write( app.procesarAcentos( this.dicConfiguracionVenta.resolucion ) + "\n");
							}
						}

						// this.impresora.write( "................................................\n");
						// this.impresora.write( "Resolucion DIAN N 18764011166942 De 2021-03-02 Autoriza De POS 1 Hasta POS 500.000." + "\n");
						// this.impresora.write( "................................................\n");

						// this.impresora.feed(0);
						this.impresora.cut();
						// this.impresora.imprimirEnImpresora("IMPRESORA20");
						// this.impresora.imprimirEnImpresora("IMPRESORABAR2");
						console.log("----....", this.impresora);
						this.impresora.imprimirEnImpresora( app.globalEmpresa.impresoraFacturacion );
						// this.hideModal( ventana );
					}, 

					gestionarCancelacionPedido( ventana ){
						setTimeout(()=>{
							this.observacionCancelacio = '';
							this.showModal( ventana );
						});
					}, 

					confirmarCancelacionPedido( ventana ){
						Swal.fire({
							title: '¿Cancelar Pedido?', type: 'warning', showCancelButton: true, allowOutsideClick: false,
							confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
						}).then((result) => {
							if (result.value) {
								this.cancelarPedido( ventana );
							}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
						});
					},

					cancelarPedido( ventana ){
						this.hideModal( ventana );
						this.consultaDetalle = true;

						var estado = 'Cancelado';
						axios.post( 
							"/Estructura/cancelarPedido" , 
							"pedido=" + this.dicPedidoDetalle.pedidoId +
							"&&observacion=" + this.observacionCancelacio + 
							"&&estado=" + estado + 
							"&&estructura=" + this.dicPedidoDetalle.estructuraId +
							
							"&&usuario=" + app.usuarioActual.usuario, 
						).then((result) => {
							setTimeout(()=>{
								if ( result.data.mensaje == 'Registro Exitoso' ){
									Swal.fire( { title:'¡Guardado Exitoso!', type:'success', showConfirmButton: false, timer:2000 } );
									this.listadoPedidos();
									this.verDetallePedido();
								}else{
									Swal.fire( { title:'¡Error de Registro!', type:'error', showConfirmButton: false, timer:2000 } );
									this.consultaDetalle = false;
									this.showModal( ventana );
								}
							});
						}).catch( error => {
							this.consultaDetalle = false;
							this.showModal( ventana );
							app.erroServidor( '' );
						});
					},

				/*ANULAR PEDIDO*/
					abrirModalAnularPedido( ventana, data ){
						this.dicPedidoDetalle = data;
						this.tituloModal = "Anulación de Pedido"; 
						this.observacionCancelacio = ''; this.mensaje = ""; this.idTipoAnulacion = ""; 
						this.subtotalStr = this.moneda( data.pedidoSubTotal ); 
						this.descuentoStr = this.moneda( data.pedidoTotalDescuento ); 
						this.impuestolStr = this.moneda( data.pedidoValorImpuesto ); 
						this.propinoStr = this.moneda( data.pedidoPropinaValor ); 
						this.totalNetoStr = this.moneda( data.pedidoTotalNeto ); 
						this.showModal( ventana );
					}, 

					solicitarTokenAutorizacionAnulacion(accion, paso){
						this.tipoToken = accion; 
						if (paso==1 && !this.dicConfiguracionVenta.autenticacionCodigo){
							paso = 2; 
						}

						if (paso==1){
							this.codigoMesero = ''; this.idMeseroAutorizacion = ''; 
							app.abrirModalGestionCodigosCalculadora("anular-pedido"); 
						}else{
							/* this.emailVerificacion = ''; this.mensajeVerificacion = ''; this.tokenVerificacion = ""; this.codigoVerificacion = ''; 
							if (!app.vacios.includes(app.globalEmpresa.destinos)){
								this.emailVerificacion = JSON.parse(JSON.stringify(app.globalEmpresa.destinos)); 
							}
							this.showModal( "modalAutorizacionEdicion" ); */
							this.confirmarAnularPedido(); 
						}
					}, 

					confirmarAnularPedido( ventana ){
						Swal.fire({
							title: '¿Cancelar Pedido?', type: 'warning', showCancelButton: true, allowOutsideClick: false,
							confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
						}).then((result) => {
							if (result.value) {
								this.anularPedido( ventana );
							}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
						});
					},

					anularPedido( ventana ){
						// this.hideModal( "modalAutorizacionEdicion" );
						this.hideModal( "modalAnularPedido" );
						app.loading = true; this.mensaje = ""; 

						var estado = 'Anulado';
						axios.post( 
							"/Estructura/anularPedido" , 
							"pedido=" + this.dicPedidoDetalle.pedidoId +
							"&&estructura=" + this.dicPedidoDetalle.estructuraId +
							"&&hoy=" + app.fechaActual +
							"&&observacion=" + this.observacionCancelacio + 
							"&&tipoAnulacion=" + this.idTipoAnulacion + 
							"&&estado=" + estado + 
							
							"&&usuario=" + app.usuarioActual.usuario, 
						).then((result) => {
							setTimeout(()=>{
								if ( result.data.mensaje == 'Registro Exitoso' ){
									Swal.fire( { title:'¡Guardado Exitoso!', type:'success', showConfirmButton: false, timer:2000 } );
									this.listadoPedidos();
								}else{
									Swal.fire( { title:'¡Error de Registro!', type:'error', showConfirmButton: false, timer:2000 } );
									app.loading = false;
									// this.showModal( 'modalAutorizacionEdicion' );
								}
							});
						}).catch( error => {
							app.loading = false;
							// this.showModal( 'modalAutorizacionEdicion' );
							app.erroServidor( '' );
						});
					},
					
					abrirModalReactivarPedido( ventana, data ){
						this.dicPedidoDetalle = JSON.parse(JSON.stringify(data)); 
						this.tituloModal = "Reactivación de Pedido"; 
						this.observacionCancelacio = ''; this.mensaje = ""; 
						this.subtotalStr = this.moneda( data.pedidoSubTotal ); 
						this.descuentoStr = this.moneda( data.pedidoTotalDescuento ); 
						this.impuestolStr = this.moneda( data.pedidoValorImpuesto ); 
						this.propinoStr = this.moneda( data.pedidoPropinaValor ); 
						this.totalNetoStr = this.moneda( data.pedidoTotalNeto ); 
						this.showModal( ventana );
					}, 

					solicitarTokenAutorizacionReactivacion(accion, paso){
						this.tipoToken = accion; 
						if (paso==1 && !this.dicConfiguracionVenta.autenticacionCodigo){
							paso = 2; 
						}

						if (paso==1){
							this.codigoMesero = ''; this.idMeseroAutorizacion = ''; 
							app.abrirModalGestionCodigosCalculadora("reactivar-pedido"); 
						}else{
							/* this.emailVerificacion = ''; this.mensajeVerificacion = ''; this.tokenVerificacion = ""; this.codigoVerificacion = ''; 
							if (!app.vacios.includes(app.globalEmpresa.destinos)){
								this.emailVerificacion = JSON.parse(JSON.stringify(app.globalEmpresa.destinos)); 
							}
							this.showModal( "modalAutorizacionEdicion" ); */
							this.confirmarReactivarPedido()
						}
					}, 

					confirmarReactivarPedido( ventana ){
						Swal.fire({
							title: '¿Reactivar Pedido?', type: 'warning', showCancelButton: true, allowOutsideClick: false,
							confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
						}).then((result) => {
							if (result.value) {
								this.reactivarPedido( ventana );
							}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
						});
					},

					reactivarPedido( ventana ){
						// this.hideModal( "modalAutorizacionEdicion" );
						this.hideModal( "modalAnularPedido" );
						app.loading = true; this.mensaje = ""; 

						var estado = 'Finalizado';
						axios.post( "/Estructura/reactivarPedido" , 
							"pedido=" + this.dicPedidoDetalle.pedidoId +
							"&&estructura=" + this.dicPedidoDetalle.estructuraId +
							"&&hoy=" + app.fechaActual +
							"&&observacion=" + this.observacionCancelacio + 
							"&&estado=" + estado + 
							
							"&&usuario=" + app.usuarioActual.usuario, 
						).then((result) => {
							setTimeout(()=>{
								if ( result.data.mensaje == 'Registro Exitoso' ){
									Swal.fire( { title:'¡Guardado Exitoso!', type:'success', showConfirmButton: false, timer:2000 } );

									var estado = result.data.pedidosPendientes ? 'Ocupado' : 'Uso'; 
									var datosActualizacion = {
										sucursal:this.idSucursalGestion, 
										fecha: app.fechaActual, 
										hora: app.horaActual,
										accion:'Actualizar', 
										salon: this.dicPedidoDetalle.salonId, 
										estructura: this.dicPedidoDetalle.estructuraId, 
										estado: estado, 
										area: 'Estructura', 
										pedidos: result.data.pedidos, 
										meseroId: this.dicPedidoDetalle.meseroId, 
									}; 
									app.socket.emit('generacionPedido', datosActualizacion);
									this.listadoPedidos();
								}else{
									this.mensaje = result.data.mensaje; 
									Swal.fire( { title:'¡Error de Registro!', type:'error', showConfirmButton: false, timer:2000 } );
									app.loading = false;
									this.showModal( "modalAnularPedido" );
								}
							});
						}).catch( error => {
							app.loading = false;
							this.showModal( "modalAnularPedido" );
							app.erroServidor( '' );
						});
					},

				/*Facturacion desde alma*/
					confirmarEviarFacturaCongeladaPedidoEstructura( ventana ){
						Swal.fire({
							title: '¿Generar Pedido?', type: 'warning', showCancelButton: true, allowOutsideClick: false,
							confirmButtonColor: '#28a745', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar'
						}).then((result) => {
							if (result.value) {
								this.enviarFacturaCongeladaPedidoEstructura( ventana );
							}else{ Swal.fire( { title:'¡Canceló!', type:'error', showConfirmButton: false, timer:2000 } ); }
						});
					}, 

					enviarFacturaCongeladaPedidoEstructura( ventana ){
						var productos = alasql( "select column productoId from ?", [ this.objDetalleProductosPedido ] );
						var cantidades = alasql( "select column productoCantidad from ?", [ this.objDetalleProductosPedido ] );
						this.generarFacturaCongeladaPedidoEstructura( productos, cantidades )
					},

					generarFacturaCongeladaPedidoEstructura( productos, cantidades ){
						var vendedor  = '';
						var cliente  = '';
						this.nombreCliente = '';
						axios.post( 
							"/Estructura/generarFacturaCongeladaPedidoEstructura" , 
							"vendedor=" + vendedor +
							"&&sucursal=" + this.idSucursalGestion + 
							"&&fecha=" + app.fechaActual + 
							"&&pedido=" + this.idPedidoGestion + 
							
							"&&productos=" + productos +
							"&&cantidades=" + cantidades +
							
							"&&cliente=" + cliente +
							"&&nombreCliente=" + this.nombreCliente +
							"&&usuario=" + app.usuarioActual.usuario, 
						).then((result) => {
							Swal.fire( { title:'¡Facturación Enviada!', type:'success', showConfirmButton: false, timer:2000 } );
						}).catch( error => { app.erroServidor( '' ); });
					},

				// Funciones Globale
					listadoSucursales(){
						app.loading = true;
						if ( app.objGlobalSucursales.length == 0 ){
							axios.post( "/Principal/listadoSucursales", ).then((result) => {
								this.objSucursales = result.data.sucursales;
								if ( this.objSucursales.length > 0 ){
									this.idSucursalGestion = this.objSucursales[0].id;
									this.configuracionesVentasSucursal();
									this.listadoPedidos();
								}else{
									app.loading = false;
								}
							}).catch( error => this.erroServidor( '' ) );
						}else{
							this.objSucursales = JSON.parse( JSON.stringify( app.objGlobalSucursales ) );
							this.idSucursalGestion = this.objSucursales[0].id;
							this.configuracionesVentasSucursal();
							this.listadoPedidos();
						}
					},

					listadoImpuestos(){
						axios.post( "/Estructura/listadoImpuestos", ).then((result) => {
							this.objImpuestos = result.data.impuestos;
						}).catch( error =>{ 
							console.log("error", error);
							app.erroServidor( '' );
						});
					},

					configuracionesVentasSucursal(ventana){
						axios.post( "/Estructura/configuracionesVentasSucursal" ,"sucursal=" + this.idSucursalGestion, ).then((result) => {
							setTimeout(()=>{
								this.objConfiguracionesVentas = result.data["configuracionesVentas"];
								if ( this.objConfiguracionesVentas.length > 0 ){
									this.dicConfiguracionVenta = this.objConfiguracionesVentas[0];
								}
							});
						}).catch( error => app.erroServidor( '' ) );
					},

					listadoCategorias(ventana){
						axios.post( 
							"/Principal/listadoCategorias" ,
						).then((result) => {
							setTimeout(()=>{
								this.objCategorias = result.data["categorias"];
								if ( this.objCategorias.length > 0 ){
									this.listadoProductos();
								}
							});
						}).catch( error => app.erroServidor( '' ) );
					},

					listadoProductos(ventana){
						axios.post( 
							"/Principal/listadoProductosInventario",
							"sucursal=" + this.idSucursalGestion,
						).then((result) => {
							setTimeout(()=>{
								this.objProductos = result.data["productos"];
								this.objProductosCopia = result.data["productos"];
								this.totalDatosProducto = this.objProductos.length;
							});
						}).catch( error => app.erroServidor( '' ) );
					},

					filtrandoProductoCategotia( data ){
						if ( this.categoriaFiltro == '' ){
								this.objProductos = JSON.parse( JSON.stringify( this.objProductosCopia ) );
							}else{
								this.objProductos = alasql( "select * from ? where categoriaId=" + this.categoriaFiltro, [ this.objProductosCopia ] );
							}
					},

					filtrandoProducto( datos ){
						this.totalDatosProducto = datos.length;
						this.currentPageProducto = 1;
					},


				/*CUstomizacion de Detalle de Pedido*/
					cargarVista ( nombre ) {
						axios.post( "/Principal/cargarVista", 'nombre=' + nombre ).then((result) => {
							console.log("Respuesta de customizacion: -- ", result.data[0]["campos"]);
							this.camposVista = result.data[0]["campos"];
							if ( this.camposVista!='' ){
								var temporal = this.camposVista.split(";");
								for ( var i = 0; i < this.customizacionDetalle.length; i++ ){
									if ( temporal.includes(this.customizacionDetalle[i]['key']) ){
										this.customizacionDetalle[i]['visible'] = true;
									}
								}
							}
						});
					}, 
			}, 

			mounted(){ 
				app.nombrePlantilla = 'Listado de Pedidos';
				app.customizacion = this.customizacion;
				this.cargarDatosSeccion();
			},
		});
	});
});