B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=12.2
@EndOfDesignText@

Sub Class_Globals
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore
	Dim g As GPS
	Dim clie_id As String
	Dim sDate,sTime As String
	Dim usuario As String
	Dim cuenta As String
	Dim btAdmin As BluetoothAdmin
	Dim cmp20 As Serial
	Dim printer As TextWriter
	Dim PairedDevices As Map
	Dim L As List
	Dim TAMANO As Int
	Dim ESPACIO As Int
	Dim BLANCO As String
	Dim impresoraConectada As Boolean = False
	Dim LONGITUD As String
	Dim LATITUD As String
	Dim NOMBRE As String
	Dim c As Cursor
	Dim s As Cursor
	Dim limite_credito As Double
	Dim banderaabono As String
	
	Dim bc As BarcodeGenerator
	
	Dim ListView1 As ListView
	Dim la_cuenta As Label
	Dim La_nombre As Label
	Dim la_Calle As Label
	Dim la_numero As Label
	Dim la_nint As Label
	Dim la_edo As Label
	Dim la_pob As Label
	Dim la_col As Label
	Dim la_cp As Label
	Dim la_zona As Label
	Dim gest As Button
	Dim la_saldotot As Label
	Dim la_saldooper As Label
	Dim reqManager As DBRequestManager
	Dim b_noEntrega As Button
	Dim Label10 As Label
	Dim Label11 As Label
	Dim d As Cursor
	Dim ime As IME
	Dim Tar As Button
	Private L_QR As Label
	Private BT_QR As Button
	Dim Printer1 As EscPosPrinter
	Dim la_comm As Label
	Dim la_actdte As Label
	Dim la_usuario As Label
	Dim la_resultado As Label
	Dim l_entre1 As Label
	Dim l_entre2 As Label
	Dim l_atiende As Label
	Dim l_atiende2 As Label
	Dim DATOS As Button
	Dim Guardar As Button
	Dim NUEVO As Button
	Private l_total As Label
	Private HIST As Button
	Dim PASA_IMP As String
	Private B_IMP As Button
	Dim total_cliente As String
	Dim CREDITO As String
	Private p_principal As Panel
	Private B_PASO2 As Button
	Private L_CANT As Label
	Dim errorImpresora As Int = 0
	Dim banderaimp As Int
	Private l_credi As Label
	Private l_pagare As Label
	Private l_montopag As Label
	Private l_efectivo As Label
	Private l_montoefec As Label
	Private p_credito As Panel
	Private b_acred As Button
	Private b_cancred As Button
	Private et_montoacredito As EditText
	Private Label16 As Label
	Private l_limite As Label
	Dim almacen As String
	Dim fechaprev As String
	Dim rutaprev As String
	Dim rutarep As String
	Dim montopagare As String
	Private p_abono As Panel
	Private clv_abonos As CustomListView
	Private et_abono As EditText
	Private b_cancelar As Button
	Private b_abono As Button
	Private l_montoabonostotal As Label
	Dim h, j,b, f As Cursor
	Private l_folio As Label
	Private l_saldo As Label
	Private b_cxc As Button
	Dim Tipoentrega As String
	Private b_cancel_pagare As Button
	Private p_transPagare2 As Panel
	Private i_qr As B4XImageView
	Private qr As QRGenerator
	Private b_cerrarqr As Button
	Private b_confirmar As Button
	Dim NOTA As String
	Private p_qr As Panel
	Private ChangingCheckboxesProgrammatically As Boolean = False
	Dim tipo_abonox As String
	Private cb_tipopago As B4XComboBox
	Dim itemselect As String
	Dim escreditoono As String
	Dim m_lat, m_lon As String
	Dim distance As Long
	Private b_imprimesegun As Button
	Private iv_foto As ImageView
	Dim Folio As String
	Private l_telefono As Label
	Private l_fecha As Label
	Private CheckBox1 As CheckBox
End Sub

'You can add more parameters here.
Public Sub Initialize As Object
	Return Me
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	Root = Root1
	'load the layout to Root
	g.Initialize("GPS")
'	Activity.LoadLayout("info_gral")
	Root.LoadLayout("cliente")
	c=Starter.skmt.ExecQuery("select CAT_CL_CODIGO, CAT_CL_RUTA, CAT_CL_NOMBRE, CAT_CL_ATIENDE1, CAT_CL_ATIENTE2, CAT_CL_TELEFONO, CAT_CL_EMAIL, CAT_CL_CALLE, CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT  from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
	s=Starter.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	s.Position=0
	c.Position=0
	la_cuenta.Text = c.GetString("CAT_CL_CODIGO")
	La_nombre.Text = c.GetString("CAT_CL_NOMBRE")
	la_Calle.Text = c.GetString("CAT_CL_CALLE") & c.GetString("CAT_CL_NOEXT")
	la_col.Text = c.GetString("CAT_CL_COLONIA")
	la_edo.Text = c.GetString("CAT_CL_EDO")
	la_cp.Text = c.GetString("CAT_CL_CP")
	l_entre1.Text = c.GetString("CAT_CL_CALLE1")
	l_entre2.Text = c.GetString("CAT_CL_CALLE2")
	p_transPagare2.left = 0 : p_transPagare2.Top = 0
	p_transPagare2.Width = Root.Width : p_transPagare2.Height = Root.Height
	Subs.centraPanel(p_qr, p_transPagare2.Width)
	qr.Initialize(i_qr.mBase.Width)
	If c.GetString("CAT_CL_ATIENDE1") <> Null And c.GetString("CAT_CL_ATIENDE1") <> "null" Then
		l_atiende.Text = c.GetString("CAT_CL_ATIENDE1")
	Else
		l_atiende.Text = " "
	End If
	If c.GetString("CAT_CL_ATIENTE2") <> Null And c.GetString("CAT_CL_ATIENTE2") <> "NULL" Then
		l_atiende2.Text = c.GetString("CAT_CL_ATIENTE2")
		Log("|"&c.GetString("CAT_CL_ATIENTE2")&"|")
	Else
		l_atiende2.Text = " "
	End If
	la_saldotot.Text = c.GetString("CAT_CL_TELEFONO")
	la_saldooper.Text = c.GetString("CAT_CL_EMAIL")
'	l_total.Text = s.GetString("TOTAL_CLIE")
	btAdmin.Initialize("BlueTeeth")
	cmp20.Initialize("Printer")
	reqManager.Initialize(Me, B4XPages.MainPage.SERVER)
End Sub

'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Sub B4XPage_Appear
	banderaimp = 0
	banderaabono = 0
	escreditoono = 0
	Tipoentrega = "CONTADO"
'	Subs.centraPanel(p_principal, Root.Width)
	Starter.skmt.Initialize(Starter.ruta,"kmt.db", True)
	reqManager.Initialize(Me, B4XPages.MainPage.SERVER)
	c=Starter.skmt.ExecQuery("select CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT, CAT_CL_BCREDITO  from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
	s=Starter.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	s.Position=0
	c.Position=0
	la_cuenta.Text = c.GetString("CAT_CL_CODIGO")
	La_nombre.Text = c.GetString("CAT_CL_NOMBRE")
	NOMBRE = c.GetString("CAT_CL_NOMBRE")
	LONGITUD = c.GetString("CAT_CL_LONG")
	LATITUD = c.GetString("CAT_CL_LAT")
	la_Calle.Text = c.GetString("CAT_CL_CALLE") & c.GetString("CAT_CL_NOEXT")
	la_col.Text = c.GetString("CAT_CL_COLONIA")
	la_edo.Text = c.GetString("CAT_CL_EDO")
	la_cp.Text = c.GetString("CAT_CL_CP")
	l_entre1.Text = c.GetString("CAT_CL_CALLE1")
	l_entre2.Text = c.GetString("CAT_CL_CALLE2")
	l_telefono.Text= c.GetString("CAT_CL_TELEFONO")
	If c.GetString("CAT_CL_ATIENDE1") <> Null And c.GetString("CAT_CL_ATIENDE1") <> "null" Then
		l_atiende.Text = c.GetString("CAT_CL_ATIENDE1")
	Else
		l_atiende.Text = " "
	End If
	If c.GetString("CAT_CL_ATIENTE2") <> Null And c.GetString("CAT_CL_ATIENTE2") <> "NULL" Then
		l_atiende2.Text = c.GetString("CAT_CL_ATIENTE2")
	Else
		l_atiende2.Text = " "
	End If
	la_saldotot.Text = c.GetString("CAT_CL_TELEFONO")
	la_saldooper.Text = c.GetString("CAT_CL_EMAIL")
'	l_total.Text = s.GetString("TOTAL_CLIE")
	CREDITO = C.GetString("CAT_CL_BCREDITO")
	p_abono.Width = Root.Width
	p_abono.Height = Root.Height
	p_principal.Width = Root.Width
	
	Private cym As Map = Subs.traeCantYMonto2(Subs.traeCliente)
	L_CANT.Text = cym.Get("cantidad")
	l_total.Text = Round2(cym.Get("monto"), 2)
			 
	Dim mostrarimp As Cursor = Starter.skmt.ExecQuery($"SELECT gestion from kmt_info where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)"$)
	mostrarimp.Position = 0
	If mostrarimp.GetString("gestion") = "0" Then
		b_imprimesegun.Visible = False
	Else if mostrarimp.GetString("gestion") = "2" Then
		b_imprimesegun.Visible = False
	End If
	mostrarimp.Close
	
	Dim cdias As Cursor = Starter.skmt.ExecQuery("select CAT_CL_DIASCREDITO from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
	cdias.Position = 0
	Dim pagarepen As Cursor = Starter.skmt.ExecQuery("select FECHA_PREVENTA, NOTA, CLIENTE FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If pagarepen.RowCount > 0 Then
		For pagadias = 0 To pagarepen.RowCount-1
			pagarepen.Position = pagadias
			DateTime.DateFormat="dd/MM/yyyy"
			Dim FechaInicio As String = pagarepen.GetString("FECHA_PREVENTA")  ' Formato: dd/MM/yyyy
			Log(pagarepen.GetString("FECHA_PREVENTA"))
			
			' Convertir las fechas a milisegundos (desde 01/01/1970)
			Dim TicksInicio As Long = DateTime.DateParse(FechaInicio)
			Dim TicksHoy As Long = DateTime.DateParse(DateTime.Date(DateTime.Now))

			' Calcular diferencia en días
			Dim DiferenciaDias As Int = (TicksHoy - TicksInicio) / DateTime.TicksPerDay

			' Mostrar resultado
			Log($"Días transcurridos: ${DiferenciaDias}"$)
			
			Starter.skmt.ExecNonQuery2("UPDATE ABONOSP set DIAS = ?, DIASATRASO = ?  where NOTA = ? AND CLIENTE IN (SELECT CUENTA FROM CUENTAA)",Array As String(DiferenciaDias,cdias.GetInt("CAT_CL_DIASCREDITO")-DiferenciaDias, pagarepen.GetString("NOTA")))
		Next
	End If
			 
'	If CREDITO = "1" Then
'		Msgbox("AVISO","SE TIENE QUE IMPRIMIR PAGARÉ") 'ignore
'	End If
'	Private cym As Map = Subs.traemosCantYMonto(clv_pedido)
'	L_CANT.Text = cym.Get("cantidad")
'	l_total.Text = cym.Get("monto")
	Starter.skmt.ExecNonQuery("UPDATE HIST_VENTAS set ESPROMO = 1  where HVD_CODPROMO = HVD_PROID AND HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	Private vc As Cursor = Starter.skmt.ExecQuery($"select HVD_PROID,HVD_COSTO_TOT, HVD_CANT, IFNULL(HVD_RECHAZOCANT, 0) AS HVD_RECHAZOCANT from HIST_VENTAS where BCAJAS = 0 and HVD_CODPROMO ='${Subs.traealmacen}' and HVD_CLIENTE in (select cuenta from cuentaa)"$)
	
	Private cuenta0 As String = 0
	Private arti As String = 0
	If vc.RowCount > 0 Then
		For i = 0 To vc.RowCount - 1
			vc.Position = i
			cuenta0 = cuenta0 + ((vc.GetString("HVD_CANT") - vc.GetString("HVD_RECHAZOCANT"))*(vc.GetString("HVD_COSTO_TOT")/vc.GetString("HVD_CANT")))
'			Log(vc.GetString("HVD_CANT")&","&vc.GetString("HVD_RECHAZOCANT"))
			arti = arti + (vc.GetString("HVD_CANT") - vc.GetString("HVD_RECHAZOCANT"))
'			Log(vc.GetString("HVD_CANT") &"  - "& vc.GetString("HVD_RECHAZOCANT")&" * "& vc8.GetString("CAT_GP_PRECIO"))
		Next
	End If
'	Log(cuenta0)
	
	Private vc2 As Cursor = Starter.skmt.ExecQuery("select HVD_PROID, HVD_CANT, IFNULL(HVD_RECHAZOCANT, 0) AS HVD_RECHAZOCANT, CANTC,HVD_COSTO_TOT from HIST_VENTAS where HVD_CLIENTE in (select cuenta from cuentaa) AND BCAJAS = 1")
	Private Cuenta1 As String = 0
	Private arti1 As String = 0
	If vc2.RowCount > 0 Then
		For i = 0 To vc2.RowCount - 1
			vc2.Position = i
			Dim preu As Float = NumberFormat2(vc2.GetString("HVD_COSTO_TOT")/vc2.GetString("CANTC"),0,2,2,False)
			Private vc3 As Cursor = Starter.skmt.ExecQuery($"select PRECIOCONVER, CONVERSION from CAT_GUNAPROD where CAT_GP_ID = '${vc2.GetString("HVD_PROID")}'"$)
			If vc3.RowCount > 0 Then
				vc3.Position = 0
				Cuenta1 = Cuenta1 + ((vc2.GetString("CANTC")-(vc2.GetString("HVD_RECHAZOCANT")/vc3.GetString("CONVERSION")))*preu)
				arti1 = arti1 + (vc2.GetString("HVD_CANT") - vc2.GetString("HVD_RECHAZOCANT"))
			End If
		Next
	End If
'	Log(Cuenta1)
	
	Private vc4 As Cursor = Starter.skmt.ExecQuery($"select HVD_PROID,HVD_PRONOMBRE,HVD_COSTO_TOT, HVD_CANT, IFNULL(HVD_RECHAZOCANT, 0) AS HVD_RECHAZOCANT, CANTC,HVD_COSTO_TOT, HVD_RECHAZO, HVD_CODPROMO from HIST_VENTAS where HVD_CLIENTE in (select cuenta from cuentaa) AND BCAJAS = 0 and HVD_CODPROMO <> '${Subs.traeAlmacen}'"$)
	Private Cuenta2 As String = 0
	Private arti2 As String = 0
	If vc4.RowCount > 0 Then
		For i = 0 To vc4.RowCount - 1
			vc4.Position = i
			If vc4.GetString("HVD_PROID") <> vc4.GetString("HVD_CODPROMO") Then
				If vc4.GetString("HVD_RECHAZO") = 0 Then
					Cuenta2 = Cuenta2 + vc4.GetString("HVD_COSTO_TOT")
					arti2 = arti2 + vc4.GetString("HVD_CANT")
				Else
					Private vc5 As Cursor = Starter.skmt.ExecQuery($"select CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${vc4.GetString("HVD_PROID")}'"$)
					If vc5.RowCount > 0 Then
						vc5.Position= 0
'						Log(vc5.GetString("CAT_GP_PRECIO"))
						Cuenta2 = Cuenta2 +((vc4.GetString("HVD_CANT")- vc4.GetString("HVD_RECHAZOCANT"))*(vc4.GetString("HVD_COSTO_TOT")/vc4.GetString("HVD_CANT")))
						arti2 = arti2 +(vc4.GetString("HVD_CANT")- vc4.GetString("HVD_RECHAZOCANT"))
					End If
				End If
			End If
		Next
	End If
'	Log(arti2)
	Subs.centraPanel(p_credito, Root.Width)
	Private c4 As Cursor = Starter.skmt.ExecQuery($"SELECT IFNULL(PE_CANT,0) AS PE_CANT, iFNULL(PE_COSTO_TOT,0) AS PE_COSTO_TOT FROM PEDIDO WHERE PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA)"$)
	Private Cuenta3 As String = 0
	Private arti3 As String = 0
	If c4.RowCount > 0 Then
		For i = 0 To c4.RowCount -1
			c4.Position = i
			arti3 = arti3 + c4.GetString("PE_CANT")
			Cuenta3 = Cuenta3 + c4.GetString("PE_COSTO_TOT")
		Next
	End If
'	Log(cuenta0)
'	Log(Cuenta1)
'	Log(Cuenta2)
'	Log(Cuenta3)
	l_total.Text = NumberFormat2((cuenta0 + Cuenta1 + Cuenta2 + Cuenta3),0,2,2,True)
	L_CANT.Text = NumberFormat2((arti + arti1 +arti2 + arti3),0,0,0,True)
'	l_total.Text = cuenta + Cuenta1 + Cuenta2
'	L_CANT.Text = arti + arti1 +arti2
	c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("MACIMP"))
	If c.RowCount > 0 Then
		c.Position = 0
		Starter.MAC_IMPRESORA = c.GetString("CAT_VA_VALOR")
	End If
	If Starter.MAC_IMPRESORA = "" Then Starter.MAC_IMPRESORA = "0"
'	Log("|" & Starter.MAC_IMPRESORA & "|")
	Printer1.Initialize(Me, "Printer1")
	If Printer1.IsConnected = False Then
'		Printer1.Connect
'		Log("1")
	Else
		Printer1.DisConnect
		Printer1.Connect
		Log("2")
	End If

'	Dim pag As Cursor = Starter.skmt.ExecQuery("select * FROM PAGARES WHERE TMP_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'	If pag.RowCount > 0 Then
'		pag.Position = 0
'		l_credi.Visible = True
'		l_pagare.Visible = True
'		l_montoefec.Visible = True
'		l_efectivo.Visible = True
'		l_montopag.Visible = True
'		l_montopag.Text = pag.GetString("TMP_MONTO_PAGARE")
'		Dim PAGAREMONTO As Float = cuenta0 + Cuenta1 + Cuenta2 + Cuenta3
'		Dim PAGAREMONTO2 As Float = pag.GetString("TMP_MONTO_PAGARE")
	''		Log
'		If PAGAREMONTO - PAGAREMONTO2 < 0 Then
'			l_montoefec.Text = 0
'		Else 
'			l_montoefec.Text = PAGAREMONTO - PAGAREMONTO2
'		End If
'	Else If pag.RowCount = 0 Then
'		l_credi.Visible = False
'		l_pagare.Visible = False
'		l_montoefec.Visible = False
'		l_efectivo.Visible = False
'		l_montopag.Visible = False
'	End If

	c=Starter.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
	c.Position = 0
	almacen = c.GetString("ID_ALMACEN")
	c.Close
	
'	If almacen = "3" Or almacen = 3 Or almacen = "5" Or almacen = 5 Then
	Tar.Visible = False
	Log("SI AQUI")
	b = Starter.skmt.ExecQuery("select COUNT(*) AS CLIENTE FROM ABONOSP WHERE CLIENTE IN (Select CUENTA from cuentaa) AND SALDO_PENDIENTE <> 0")
	b.Position = 0
	Dim cabonos As String = b.GetString("CLIENTE")
	If cabonos = 0 Then
		b_cxc.Visible = False
	Else
		b_cxc.Visible = True
	End If
'	End If

	Dim cp As Cursor = Starter.skmt.ExecQuery("SELECT * FROM PAGARES WHERE PA_CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND PA_CANCELADO IS NULL")
	If cp.RowCount > 0 Then
		
		Dim x2 As Cursor =Starter.skmt.ExecQuery("SELECT gestion FROM kmt_info where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
		x2.Position = 0
		If x2.GetString("gestion") = 2 Then
			b_cancel_pagare.Visible = True
		Else
			b_cancel_pagare.Visible = False
		End If
		
	Else
		b_cancel_pagare.Visible = False
	End If
	
	CallSubDelayed(Tracker, "Track")
	CallSubDelayed(Tracker, "StartFLPSmall")
	If Tracker.FLP.IsInitialized And Tracker.FLP.GetLastKnownLocation.IsInitialized Then 'Si tenemos "UltimaUbicaccionConocida" la usamos.
		B4XPages.MainPage.lat_gps = Tracker.FLP.GetLastKnownLocation.Latitude
		B4XPages.MainPage.lon_gps = Tracker.FLP.GetLastKnownLocation.Longitude
'		Log($"Tenemos UUC: ${Tracker.FLP.GetLastKnownLocation.Latitude},${Tracker.FLP.GetLastKnownLocation.Longitude}"$)
		GPS_LocationChanged(Tracker.FLP.GetLastKnownLocation)
	End If
	
	Dim x1 As Cursor =Starter.skmt.ExecQuery("SELECT IFNULL(CAT_CL_LIMITECREDITO,0) AS CAT_CL_LIMITECREDITO FROM kmt_info where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	x1.Position = 0
	limite_credito = 0
	l_montopag.Text = x1.GetString("CAT_CL_LIMITECREDITO")
	
'	Dim fotomostrar As Cursor = Starter.skmt.ExecQuery("SELECT foto FROM FOTOS where CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'	If fotomostrar.RowCount > 0 Then
'		Dim fotomostrar1 As Cursor = Starter.skmt.ExecQuery("SELECT foto FROM FOTOS where CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND foto IS NULL")
'		If fotomostrar1.RowCount > 0 Then
'			iv_foto.Bitmap = LoadBitmap(File.DirAssets,"images.png")
'			Log("aqui no hay foto")
'		Else
'			fotomostrar.Position = 0
'			Private fotomostrarfinal() As Byte = fotomostrar.GetBlob("foto")
'			Dim InputStream1 As InputStream
'			InputStream1.InitializeFromBytesArray(fotomostrarfinal, 0, fotomostrarfinal.Length)
'			Dim Bitmap1 As Bitmap
'			Bitmap1.Initialize2(InputStream1)
'			InputStream1.Close
'			iv_foto.Bitmap = Bitmap1
'		
'			Log("aqui si hay foto")
'		End If
'		
'	End If
	
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

'Sub GPS_LocationChanged (Location1 As Location)
''	lat_gps=Location1.ConvertToSeconds(Location1.Latitude)
''	lon_gps=Location1.ConvertToSeconds(Location1.Longitude)
'	Dim sDate,sTime As String
'	DateTime.DateFormat = "MM/dd/yyyy"
'	sDate=DateTime.Date(DateTime.Now)
'	sTime=DateTime.Time(DateTime.Now)
'	Starter.skmt.ExecNonQuery("DELETE FROM HIST_GPS")
'	Starter.skmt.ExecNonQuery2("INSERT INTO  HIST_GPS (HGDATE, HGLAT, HGLON) VALUES(?,?,?) ", Array As Object (sDate & sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
'End Sub

Sub GPS_LocationChanged (Location1 As Location)
'	LogColor($"Entrando a Cliente.GPS_LocationChanged"$, Colors.red)
	If Tracker.FLP.GetLastKnownLocation.IsInitialized And Tracker.FLP.GetLastKnownLocation.Latitude <> 0 Then
		B4XPages.MainPage.lat_gps = Tracker.FLP.GetLastKnownLocation.Latitude
		B4XPages.MainPage.lon_gps = Tracker.FLP.GetLastKnownLocation.Longitude
		Log("Coords set to: " & B4XPages.MainPage.lat_gps & " and " & B4XPages.MainPage.lon_gps)
	End If
	
	If LATITUD.Length < 5 Then
		
	Else
			
	
		Dim l1, l2 As Location
		l1.Initialize2(B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps)
		Log($"Coordenadas de la tienda - lat:${LATITUD}, lon:${LONGITUD}"$)
		l2.Initialize2(LATITUD, LONGITUD)
		
	

		'now we need the distance between our location and the target location
		distance =    l1.DistanceTo(l2)  'the result is in meter
	
		Log("DISTANCIA "&distance)
	End If
	
	Dim sDate,sTime As String
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	Starter.skmt.ExecNonQuery("DELETE FROM HIST_GPS")
	Starter.skmt.ExecNonQuery2("INSERT INTO  HIST_GPS (HGDATE, HGLAT, HGLON) VALUES(?,?,?) ", Array As Object (sDate & sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
	CallSubDelayed(Tracker, "CreateLocationRequest")
End Sub


Sub ListView1_ItemLongClick (Position As Int, Value As Object)
	
End Sub

Sub gest_Click
	Dim x2 As Cursor =Starter.skmt.ExecQuery("SELECT gestion FROM kmt_info where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	x2.Position = 0
	If x2.GetString("gestion") = 2 Then
		Msgbox2Async("Ya se gestiono el cliente, no se pueden hacer modificaciones","Atención","","","Ok",LoadBitmap(File.DirAssets,"alert2.png"),False)
		Wait For Msgbox_Result (Result As Int)
		If Result= DialogResponse.NEGATIVE Then
			B4XPages.ShowPage("Principal")
		End If
	Else
'		If Subs.traeAlmacen = 92 Then
'			
'			Dim k As Cursor = Starter.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
'			k.Position = 0
'			Log(k.GetString("CUENTA"))
'			Dim cliecred As Cursor = Starter.skmt.ExecQuery("SELECT CAT_CL_LIMITECREDITO from kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
'			cliecred.Position = 0 
'			
'			Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente = ?", Array As String(k.GetString("CUENTA")))
'			y.position = 0
'			Dim u As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(SALDO_PENDIENTE),0) AS SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE = ?", Array As String(k.GetString("CUENTA")))
'			u.Position = 0
'			If u.RowCount > 0 Then
'				If u.GetString("SALDO_PENDIENTE") <> 0 Then
'					If y.GetString("a_abono")  > 0 Then
'						If cliecred.GetString("CAT_CL_LIMITECREDITO") >= (u.GetString("SALDO_PENDIENTE") - y.GetString("a_abono") + l_total.Text.Replace(",","")) Then
'							checacredito
'						Else
'							Dim creditofaltante As Float = 	(cliecred.GetString("CAT_CL_LIMITECREDITO") - ( u.GetString("SALDO_PENDIENTE") + l_total.Text.Replace(",","")- y.GetString("a_abono"))) * -1
'							
'							MsgboxAsync($"Para poder hacer una entrega se necesita liberar '${creditofaltante}' de credito."$,"Atención")
'						End If
''					Else If cliecred.GetString("CAT_CL_LIMITECREDITO") >= u.GetString("SALDO_PENDIENTE") + l_total.Text.Replace(",","") Then 'AQUI VAMOS A VALIDAR SI EL CREDITO ALCANZA'
''						MsgboxAsync("Para poder hacer una entrega se necesita liquidar el(los) pagare(s)","Atención")
'					Else If cliecred.GetString("CAT_CL_LIMITECREDITO") >= (u.GetString("SALDO_PENDIENTE") + l_total.Text.Replace(",","")) Then
'						checacredito
'					Else
'						Dim creditofaltante As Float = 	(cliecred.GetString("CAT_CL_LIMITECREDITO") - ( u.GetString("SALDO_PENDIENTE") + l_total.Text.Replace(",",""))) * -1
'							
'						MsgboxAsync($"Para poder hacer una entrega se necesita liberar '${creditofaltante}' de credito."$,"Atención")
'					End If
'				Else If u.GetString("SALDO_PENDIENTE") = 0 Then
'					checacredito
'				End If
'			Else
'				checacredito
'			End If
'			
'		Else
'			Dim k As Cursor = Starter.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
'			k.Position = 0
'			Log(k.GetString("CUENTA"))
'			Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente = ?", Array As String(k.GetString("CUENTA")))
'			y.position = 0
'			Dim u As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(SALDO_PENDIENTE),0) AS SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE = ?", Array As String(k.GetString("CUENTA")))
'			u.Position = 0
'			If u.RowCount > 0 Then
'				If u.GetString("SALDO_PENDIENTE") <> 0 Then
'					If y.RowCount > 0 Then
'						Log(NumberFormat2(u.GetDouble("SALDO_PENDIENTE"),0,2,2,False) &"   =   " & NumberFormat2(y.GetDouble("a_abono"),0,2,2,False))
'						If NumberFormat2(u.GetDouble("SALDO_PENDIENTE"),0,2,2,False) = NumberFormat2(y.GetDouble("a_abono"),0,2,2,False) Then
'							checacredito
'						Else
'							Log("aqui")
'							MsgboxAsync("Para poder hacer una entrega se necesita liquidar el(los) pagare(s)","Atención")
'						End If
'					Else
'						Log("aqui")
'						MsgboxAsync("Para poder hacer una entrega se necesita liquidar el(los) pagare(s)","Atención")
'					End If
'				Else If u.GetString("SALDO_PENDIENTE") = 0 Then
'					checacredito
'				End If
'			Else
'				checacredito
'			End If
'		End If
		Guardado
	End If
End Sub

Sub checacredito
	If l_total.Text = ".00" And L_CANT.Text = 1 Then
		Guardado
	Else
		
		Dim pagacheca As Cursor = Starter.skmt.ExecQuery("SELECT * FROM PAGARES WHERE PA_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	
		If pagacheca.RowCount > 0 Then
			esPagoACreditoGuardamosPagare
		Else
			
		
	
			Dim x1 As Cursor =Starter.skmt.ExecQuery("SELECT IFNULL(CAT_CL_LIMITECREDITO,0) AS CAT_CL_LIMITECREDITO FROM kmt_info where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
			x1.Position = 0
			limite_credito = 0
			If CREDITO = 1 And x1.GetString("CAT_CL_LIMITECREDITO") <> 0 Then '''' se debe de cambiar a si acepta o no credito, aparte de tener la bandera a credito
				Msgbox2Async("EL CLIENTE TIENE CREDITO DISPONIBLE, UNA VEZ SELECCIONADA UNA OPCION NO SE PODRA MODIFICAR!!!!!","Forma de pago","","Credito","Efectivo",LoadBitmap(File.DirAssets,"alert2.png"),False)
				Wait For Msgbox_Result (Result As Int)
				If Result= DialogResponse.POSITIVE Then
					Log(1)
'			p_credito.Visible = True
'			'monto
'			c=Starter.skmt.ExecQuery("select sum(HVD_COSTO_TOT) AS MONTO from HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND HVD_RECHAZO = 0 AND HVD_PARCIAL = 0")
'			c.Position = 0
'			montopagare = c.GetString("MONTO")
'			c.Close
'			l_limite.Text = "Monto de la venta: $" & l_total.Text
				Else If Result = DialogResponse.NEGATIVE Then
					escreditoono = 0
					Log(2)
					Tipoentrega = "CONTADO"
					B_IMP_Click
					banderaimp = 1
				Else If Result = DialogResponse.CANCEL Then
					Log(12)
					escreditoono = 1
'				If l_total.Text.Replace(",","") <= NumberFormat2( x1.GetString("CAT_CL_LIMITECREDITO").Replace(",",""),0,2,2,False) Then
					limite_credito = x1.GetString("CAT_CL_LIMITECREDITO")
					esPagoACreditoGuardamosPagare'' para brincar el r
					Log(3)
					'' descomentar
'					Private cliente As String = Subs.traeCliente
'					c = Starter.skmt.ExecQuery($"select CAT_CL_RUTA from kmt_info where cat_cl_codigo = '${cliente}'"$)
'					If c.RowCount > 0 Then
'						c.Position = 0
'						Private RUTA_PREVENTA = c.GetString("CAT_CL_RUTA")
'					End If
'					c = Starter.skmt.ExecQuery($"select distinct hvd_num_ticket from hist_ventas where hvd_cliente = '${cliente}'"$)
'					If c.RowCount > 0 Then
'						c.Position = 0
'						NOTA = c.GetString("HVD_NUM_TICKET")
'					End If
'					DateTime.DateFormat = "MM/dd/yyyy"
'					sDate=DateTime.Date(DateTime.Now)
'					sTime=DateTime.Time(DateTime.Now)
'					ProgressDialogShow("Un momento por favor!!")
'					Dim cmd As DBCommand
'					cmd.Initialize
'					cmd.Name = "insertaPagareGunaRep"
'					cmd.Parameters = Array As Object(Subs.traeAlmacen, RUTA_PREVENTA, Subs.traeRutaReparto, cliente, l_total.Text.Replace(",",""), NOTA, sDate & " " & sTime)
'					reqManager.ExecuteCommand(cmd, $"insertaPagare_${NOTA}"$)
					'' fin descomentar
					
'			Else
'				MsgboxAsync("El cliente debe de dar un pago de "& (l_total.Text.Replace(",","") - x1.GetString("CAT_CL_LIMITECREDITO")) &"","Atención")
'				Log(3)
'				Tipoentrega = "CREDITO"
'				DateTime.DateFormat = "dd/MM/yyyy"
'				DateTime.TimeFormat = "HH:mm:ss"
'				sDate=DateTime.Date(DateTime.Now)
'				sTime=DateTime.Time(DateTime.Now)
'				'cliente
'				c=Starter.skmt.ExecQuery("select CUENTA from cuentaa")
'				c.Position = 0
'				cuenta = c.GetString("CUENTA")
'				c.Close
'				'usuario
'				c=Starter.skmt.ExecQuery("select usuario from usuarioa")
'				c.Position = 0
'				usuario = c.GetString("USUARIO")
'				c.Close
'				'Almacen
'				c=Starter.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
'				c.Position = 0
'				almacen = c.GetString("ID_ALMACEN")
'				c.Close
'				'FECHA PREVENTA
'				c=Starter.skmt.ExecQuery("select HVD_FECHA from HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'				c.Position = 0
'				fechaprev = c.GetString("HVD_FECHA")
'				c.Close
'				'RUTAPREVENTA
'				c=Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
'				c.Position = 0
'				rutaprev = c.GetString("CAT_CL_RUTA")
'				c.Close
'				'RUTA rep
'				c=Starter.skmt.ExecQuery("select RUTAA from RUTAA")
'				c.Position = 0
'				rutarep = c.GetString("RUTAA")
'				c.Close
'				'monto
'				c=Starter.skmt.ExecQuery("select sum(HVD_COSTO_TOT) AS MONTO from HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND HVD_RECHAZO = 0 AND HVD_PARCIAL = 0")
'				c.Position = 0
'				montopagare = c.GetString("MONTO")
'				c.Close
'				Starter.skmt.ExecNonQuery2("INSERT INTO PAGARES (PA_ALMACEN, PA_RUTA_REP, PA_RUTAPREV, PA_FECHA_PREV, PA_CAPTURA, PA_MONTO, PA_USUARIO, PA_CLIENTE) VALUES(?,?,?,?,?,?,?,?) ", Array As Object (almacen,rutarep,rutaprev,fechaprev,(sDate),l_total.Text,usuario,cuenta))
'				B_IMP_Click
'				banderaimp = 1
'				End If
				End If
			Else
				Log(4)
				escreditoono = 0
				B_IMP_Click
				banderaimp = 1
			End If
		End If
	End If
End Sub

Sub esPagoACreditoGuardamosPagare
	Tipoentrega = "CREDITO"
	Log(3)
	DateTime.DateFormat = "dd/MM/yyyy"
	DateTime.TimeFormat = "HH:mm:ss"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	'cliente
	c=Starter.skmt.ExecQuery("select CUENTA from cuentaa")
	c.Position = 0
	cuenta = c.GetString("CUENTA")
	c.Close
	'usuario
	c=Starter.skmt.ExecQuery("select usuario from usuarioa")
	c.Position = 0
	usuario = c.GetString("USUARIO")
	c.Close
	'Almacen
	c=Starter.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
	c.Position = 0
	almacen = c.GetString("ID_ALMACEN")
	c.Close
	'FECHA PREVENTA
	c=Starter.skmt.ExecQuery("select HVD_FECHA from HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	c.Position = 0
	fechaprev = c.GetString("HVD_FECHA")
	c.Close
	'RUTAPREVENTA
	c=Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	c.Position = 0
	rutaprev = c.GetString("CAT_CL_RUTA")
	c.Close
	'RUTA rep
	rutarep = Subs.traeRutaReparto
	c.Close
	'monto
	c=Starter.skmt.ExecQuery("select sum(HVD_COSTO_TOT) AS MONTO from HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND HVD_RECHAZO = 0 AND HVD_PARCIAL = 0")
	c.Position = 0
	montopagare = c.GetString("MONTO")
	c.Close
	
	c = Starter.skmt.ExecQuery($"select distinct hvd_num_ticket from hist_ventas where hvd_cliente = '${la_cuenta.Text}'"$)
	If c.RowCount > 0 Then
		c.Position = 0
		NOTA = c.GetString("HVD_NUM_TICKET")
	End If
	c.Close
	Dim pagacheca As Cursor = Starter.skmt.ExecQuery("SELECT * FROM PAGARES WHERE PA_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	
	If pagacheca.RowCount > 0 Then
		B_IMP_Click
		banderaimp = 1
	Else
		If l_total.Text.Replace(",","") <= limite_credito Then
			Starter.skmt.ExecNonQuery2("INSERT INTO PAGARES (PA_ALMACEN, PA_RUTA_REP, PA_RUTAPREV, PA_FECHA_PREV, PA_CAPTURA, PA_MONTO, PA_USUARIO, PA_CLIENTE,PA_TICKET) VALUES(?,?,?,?,?,?,?,?,?) ", Array As Object (almacen,rutarep,rutaprev,fechaprev,(sDate),l_total.Text.Replace(",",""),usuario,cuenta,NOTA))
			B_IMP_Click
			banderaimp = 1
		Else
			Log(limite_credito)
			Msgbox2Async("Se debe de realizar un pago por " & NumberFormat2((l_total.Text.Replace(",","")-limite_credito),0,2,2,False) & " por que exede el limite de credito","Atención","","Aceptar","Cancelar",LoadBitmap(File.DirAssets,"alert2.png"),False)
			Wait For Msgbox_Result (Result As Int)
			If Result= DialogResponse.CANCEL Then
				Starter.skmt.ExecNonQuery2("INSERT INTO PAGARES (PA_ALMACEN, PA_RUTA_REP, PA_RUTAPREV, PA_FECHA_PREV, PA_CAPTURA, PA_MONTO, PA_USUARIO, PA_CLIENTE,PA_TICKET) VALUES(?,?,?,?,?,?,?,?,?) ", Array As Object (almacen,rutarep,rutaprev,fechaprev,(sDate),l_total.Text.Replace(",",""),usuario,cuenta,NOTA))
				tipo_abonox = "abono"
				banderaabono = 1
				banderaimp = 1
				B_IMP_Click
			End If
		End If
		
	End If
End Sub

Sub Guardado
	Log(escreditoono)
	DateTime.DateFormat = "MM/dd/yyyy"
	DateTime.TimeFormat="HHmmss"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c=Starter.skmt.ExecQuery("select CUENTA from cuentaa")
	c.Position = 0
	cuenta = c.GetString("CUENTA")
	c=Starter.skmt.ExecQuery("select usuario from usuarioa")
	c.Position = 0
	usuario = c.GetString("USUARIO")
	c.Close
	d = Starter.skmt.ExecQuery("SELECT RUTAA FROM RUTAA")
	d.Position = 0
	Dim ruta As String = d.GetString("RUTAA")
	d.Close
	d = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	d.Position = 0
	Dim rutapre As String = d.GetString("CAT_CL_RUTA")
	d.Close
	
'	d = Starter.skmt.ExecQuery("SELECT HVD_FECHA FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'	d.Position = 0
	Dim fechaprev As String = Subs.traefECHAPREV
'	d.Close
	
	Dim rutaactualizar As String
	Dim rut As Cursor = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	If rut.RowCount > 0 Then
		rut.Position = 0
		rutaactualizar = rut.GetString("CAT_CL_RUTA")
	End If
	
	Starter.skmt.ExecNonQuery($"DELETE FROM NOVENTA WHERE NV_CLIENTE IN (select cuenta from cuentaa)"$)
	Starter.skmt.ExecNonQuery2("INSERT INTO NOVENTA (NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON,NV_RUTA) VALUES(?,?,?,?,?,?,?,?) ", Array As Object (cuenta,sDate &" "& sTime, usuario, "ENTREGA","ENTREGA COMPLETA", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,rutaactualizar))
	Starter.skmt.ExecNonQuery2("INSERT INTO REPARTO_GEO (CLIENTE, USUARIO, FECHA_PUNTEO, LATITUD, LONGITUD, ALMACEN, RUTA_REPARTO, RUTA_PREV, FECHA_PREVENTA, TIPO,ENVIO) VALUES(?,?,?,?,?,?,?,?,?,?,0)",Array As String (la_cuenta.Text, usuario, sDate &" "&sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,B4XPages.MainPage.almacen,ruta,rutapre,fechaprev, "ENTREGADO"))
	Starter.skmt.ExecNonQuery($"UPDATE kmt_info set gestion = 2, HORAENT = '${sDate & " " & sTime}' where CAT_CL_CODIGO In (select cuenta from cuentaa) and CAT_CL_RUTA = '${rutaactualizar}' "$)
	Starter.skmt.ExecNonQuery("update HIST_VENTAS SET HVD_ESTATUS = 1 WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	mandaPendientesreparto
	
	If escreditoono = "1" Then
		
		Dim g5 As Cursor = Starter.skmt.ExecQuery("SELECT SUM(HVD_COSTO_TOT) as HVD_COSTO_TOT FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
		g5.Position = 0
		Dim totaltotal As String = NumberFormat2(g5.GetString("HVD_COSTO_TOT"),0,2,2,False)
		g5.Close
		LogColor(totaltotal,Colors.Red)
		LogColor(l_total.Text.Replace(",",""),Colors.Red)
		If totaltotal = l_total.Text.Replace(",","") Then
			Dim entregatotaloparial As String = "ENTREGA TOTAL"
		Else
			Dim entregatotaloparial As String = "ENTREGA PARCIAL"
		End If
		
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "UPDATE_ACTUAL_GEO_GUNA_VN"
'		cmd.Parameters = Array As String(l_total.Text,"1", l_total.Text,B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,"","",usuario,ruta,"ENTREGA", entregatotaloparial,"CREDITO", distance, L_CANT.text,la_cuenta.Text,fechaprev,almacen,Subs.traerUTAPREV)
		cmd.Parameters = Array As String(l_total.Text.Replace(",",""),"1", l_total.Text.Replace(",",""),B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,"","",usuario,ruta,"ENTREGA", entregatotaloparial,"CREDITO", distance, L_CANT.text,la_cuenta.Text,fechaprev,almacen,Subs.traerUTAPREV)
		Starter.skmt.ExecNonQuery2("INSERT INTO HIST_REPARTO_GEO(HIST_RG_MONTO , HIST_RG_CREDITO , HIST_RG_MONTO_CREDITO , HIST_RG_LAT , HIST_RG_LONG , HIST_RG_RECHAZO , HIST_RG_MOTIVO , HIST_RG_USUARIO_ENTREGO , HIST_RG_RUTA_REP , HIST_RG_ESTATUS_ENTREGA , HIST_RG_COMENTARIO_ENTREGA , HIST_RG_FORMA_PAGO , HIST_RG_GEOCERCA_MTS , HIST_RG_NO_ART , HIST_RG_CLIENTE , HIST_RG_FECHA , HIST_RG_ALMACEN , HIST_RG_RUTA_PRE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object(l_total.Text.Replace(",",""),"1", l_total.Text.Replace(",",""),B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,"","",usuario,ruta,"ENTREGA", entregatotaloparial,"CREDITO", distance, L_CANT.text,la_cuenta.Text,fechaprev,almacen,Subs.traerUTAPREV))
		reqManager.ExecuteCommand(cmd, "up_geo")
		
'		Dim cmd As DBCommand
'		cmd.Initialize
'		cmd.Name = "UPDATE_ACTUAL_GEO_GUNA_VN"
'		cmd.Parameters = Array As String(l_total.Text,"fue credito", "MONTO SI FUE A CREDITO",B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,"RECHAZO O NO",usuario,ruta,"entrega o rechazo", "parcial o total","efectivo o credito", "mts", L_CANT.text,la_cuenta.Text,fechaprev,almacen,rutaprev)
'		reqManager.ExecuteCommand(cmd, "up_geo")
		
	Else
		
		Dim g5 As Cursor = Starter.skmt.ExecQuery("SELECT SUM(HVD_COSTO_TOT) as HVD_COSTO_TOT FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
		g5.Position = 0
		Dim totaltotal As String = NumberFormat2(g5.GetString("HVD_COSTO_TOT"),0,2,2,False)
		g5.Close
		LogColor(totaltotal,Colors.Red)
		LogColor(l_total.Text.Replace(",",""),Colors.Red)
		If totaltotal = l_total.Text.Replace(",","") Then
			Dim entregatotaloparial As String = "ENTREGA TOTAL"
		Else
			Dim entregatotaloparial As String = "ENTREGA PARCIAL"
		End If
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "UPDATE_ACTUAL_GEO_GUNA_VN"
		cmd.Parameters = Array As String(l_total.Text.Replace(",",""),"0", "",B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,"","",usuario,ruta,"ENTREGA", entregatotaloparial,"EFECTIVO", distance, L_CANT.text,la_cuenta.Text,fechaprev,almacen,Subs.traerUTAPREV)
		Starter.skmt.ExecNonQuery2("INSERT INTO HIST_REPARTO_GEO(HIST_RG_MONTO , HIST_RG_CREDITO , HIST_RG_MONTO_CREDITO , HIST_RG_LAT , HIST_RG_LONG , HIST_RG_RECHAZO , HIST_RG_MOTIVO , HIST_RG_USUARIO_ENTREGO , HIST_RG_RUTA_REP , HIST_RG_ESTATUS_ENTREGA , HIST_RG_COMENTARIO_ENTREGA , HIST_RG_FORMA_PAGO , HIST_RG_GEOCERCA_MTS , HIST_RG_NO_ART , HIST_RG_CLIENTE , HIST_RG_FECHA , HIST_RG_ALMACEN , HIST_RG_RUTA_PRE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object(l_total.Text.Replace(",",""),"0", "",B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,"","",usuario,ruta,"ENTREGA", entregatotaloparial,"EFECTIVO", distance, L_CANT.text,la_cuenta.Text,fechaprev,almacen,Subs.traerUTAPREV))
		reqManager.ExecuteCommand(cmd, "up_geo")
		
	End If
	
	Log("FECHA "& rutaprev)

'	Dim mandamapa As Cursor = Starter.skmt.ExecQuery("SELECT * FROM kmt_info WHERE gestion = 0 and CAT_CL_CODIGO <> 63403")
'	If mandamapa.RowCount > 0 Then
'		StartActivity(MAPA_RUTAS)
'	Else If mandamapa.RowCount = 0 Then
	B4XPages.ShowPage("Principal")
'	End If
End Sub

Sub b_noEntrega_Click
	Dim x2 As Cursor =Starter.skmt.ExecQuery("SELECT gestion FROM kmt_info where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	x2.Position = 0
	If x2.GetString("gestion") = 2 Then
		Msgbox2Async("Ya se gestiono el cliente, no se pueden hacer modificaciones","Atención","","","Ok",LoadBitmap(File.DirAssets,"alert2.png"),False)
		Wait For Msgbox_Result (Result As Int)
		If Result= DialogResponse.NEGATIVE Then
			B4XPages.ShowPage("Principal")
		End If
	Else

'		Dim k As Cursor = Starter.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
'		k.Position = 0
'		Log(k.GetString("CUENTA"))
'		Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente = ?", Array As String(k.GetString("CUENTA")))
'		y.position = 0
'		Dim u As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(SALDO_PENDIENTE),0) AS SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE = ?", Array As String(k.GetString("CUENTA")))
'		u.Position = 0
		'
'		If u.RowCount > 0 Then
'			If u.GetString("SALDO_PENDIENTE") <> 0 Then
'				If y.RowCount > 0 Then
'			
'					If u.GetString("SALDO_PENDIENTE") = y.GetString("a_abono") Then
		B4XPages.ShowPage("noVenta")
'					Else
'						MsgboxAsync("Para poder hacer una entrega se necesita liquidar el(los) pagare(s)","Atención")
'					End If
'				Else
'					MsgboxAsync("Para poder hacer una entrega se necesita liquidar el(los) pagare(s)","Atención")
'				End If
'			Else If u.GetString("SALDO_PENDIENTE") = 0 Then
'				B4XPages.ShowPage("noVenta")
'			
'			End If
'		Else
'			B4XPages.ShowPage("noVenta")
'		End If
	End If
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
	' BACK key pressed
	' I want to capture the key here so I return True
	If p_credito.Visible Then
		et_montoacredito.Text = ""
		p_credito.Visible = False
		Return False
	Else If p_abono.Visible Then
		p_abono.Visible = False
		et_abono.Text = ""
		Return False
	Else
		B4XPages.ShowPage("Clientes")
		Return False
	End If
'	B4XPages.ShowPage("Clientes")
End Sub

Sub Tar_Click
'	StartActivity(colonia2)
	B4XPages.ShowPage("Productos")
End Sub

Sub DATOS_Click
'	StartActivity(telefonos)
End Sub

Sub Guardar_Click
'	Dim mandamapa As Cursor = Starter.skmt.ExecQuery("SELECT * FROM kmt_info WHERE gestion = 0 AND cat_cl_codigo <> 63403")
'	If mandamapa.RowCount > 0 Then
'		StartActivity(MAPA_RUTAS)
'	Else If mandamapa.RowCount = 0 Then
	B4XPages.ShowPage("Principal")
'	End If
End Sub

Sub NUEVO_Click
	StartActivity(MAPA_CLIENTE)
End Sub

Sub HIST_Click
	
	
	Dim x2 As Cursor =Starter.skmt.ExecQuery("SELECT gestion FROM kmt_info where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	x2.Position = 0
	If x2.GetString("gestion") = 2 Then
		Msgbox2Async("Ya se gestiono el cliente, no se pueden hacer modificaciones","Atención","","","Ok",LoadBitmap(File.DirAssets,"alert2.png"),False)
		Wait For Msgbox_Result (Result As Int)
		If Result= DialogResponse.NEGATIVE Then
			B4XPages.ShowPage("Principal")
		End If
	Else
		
		Dim pagacheca2 As Cursor = Starter.skmt.ExecQuery("SELECT * FROM PAGARES WHERE PA_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	
		If pagacheca2.RowCount > 0 Then
		
			
			Msgbox2Async("El pagare ya fue generdo, no se puede realizar modificación.","Atención","","","Ok",LoadBitmap(File.DirAssets,"alert2.png"),False)
			Wait For Msgbox_Result (Result As Int)
			If Result= DialogResponse.POSITIVE Then
				Log("Aqui")
			End If
		Else
		
		
			If Subs.traeAlmacen = 92 Then
			
				Dim k As Cursor = Starter.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
				k.Position = 0
				Log(k.GetString("CUENTA"))
				Dim cliecred As Cursor = Starter.skmt.ExecQuery("SELECT CAT_CL_LIMITECREDITO from kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
				cliecred.Position = 0
			
				Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente = ?", Array As String(k.GetString("CUENTA")))
				y.position = 0
				Dim u As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(SALDO_PENDIENTE),0) AS SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE = ?", Array As String(k.GetString("CUENTA")))
				u.Position = 0
				If u.RowCount > 0 Then
					If u.GetString("SALDO_PENDIENTE") <> 0 Then
						Log("AQUI ESTOY")
						If y.GetString("a_abono")  > 0 Then
							Log("AQUI AHORA")
							If cliecred.GetString("CAT_CL_LIMITECREDITO") >= (u.GetString("SALDO_PENDIENTE") - y.GetString("a_abono") + l_total.Text.Replace(",","")) Then
								B4XPages.MainPage.detalleVenta.prodsMap.Initialize
								B4XPages.ShowPage("DetalleVenta")
							Else
								Dim creditofaltante As Float = 	(cliecred.GetString("CAT_CL_LIMITECREDITO") - ( u.GetString("SALDO_PENDIENTE") + l_total.Text.Replace(",","")- y.GetString("a_abono"))) * -1
							
								MsgboxAsync($"Para poder hacer una entrega se necesita liberar '${creditofaltante}' de credito."$,"Atención")
							End If
'						Else If cliecred.GetString("CAT_CL_LIMITECREDITO") >= u.GetString("SALDO_PENDIENTE") + l_total.Text.Replace(",","") Then 'AQUI VAMOS A VALIDAR SI EL CREDITO ALCANZA'
'							MsgboxAsync("Para poder hacer una entrega se necesita liquidar el(los) pagare(s)","Atención")
						Else If cliecred.GetString("CAT_CL_LIMITECREDITO") >= (u.GetString("SALDO_PENDIENTE") + l_total.Text.Replace(",","")) Then
							B4XPages.MainPage.detalleVenta.prodsMap.Initialize
							B4XPages.ShowPage("DetalleVenta")
						Else
							Dim creditofaltante As Float = 	(cliecred.GetString("CAT_CL_LIMITECREDITO") - ( u.GetString("SALDO_PENDIENTE") + l_total.Text.Replace(",",""))) * -1
							
							MsgboxAsync($"Para poder hacer una entrega se necesita liberar '${creditofaltante}' de credito."$,"Atención")
						End If
						
					Else If u.GetString("SALDO_PENDIENTE") = 0 Then
						B4XPages.MainPage.detalleVenta.prodsMap.Initialize
						B4XPages.ShowPage("DetalleVenta")
					End If
				Else
					B4XPages.MainPage.detalleVenta.prodsMap.Initialize
					B4XPages.ShowPage("DetalleVenta")
				End If
			
			Else
				Dim k As Cursor = Starter.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
				k.Position = 0
				Log(k.GetString("CUENTA"))
				Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente = ?", Array As String(k.GetString("CUENTA")))
				y.position = 0
				Dim u As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(SALDO_PENDIENTE),0) AS SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE = ?", Array As String(k.GetString("CUENTA")))
				u.Position = 0
				If u.RowCount > 0 Then
					If u.GetString("SALDO_PENDIENTE") <> 0 Then
						If y.RowCount > 0 Then
							If u.GetString("SALDO_PENDIENTE") = y.GetString("a_abono") Then
								B4XPages.MainPage.detalleVenta.prodsMap.Initialize
								B4XPages.ShowPage("DetalleVenta")
							Else
								MsgboxAsync("Para poder hacer una entrega se necesita liquidar el(los) pagare(s)","Atención")
							End If
						Else
							MsgboxAsync("Para poder hacer una entrega se necesita liquidar el(los) pagare(s)","Atención")
						End If
					Else If u.GetString("SALDO_PENDIENTE") = 0 Then
						B4XPages.MainPage.detalleVenta.prodsMap.Initialize
						B4XPages.ShowPage("DetalleVenta")
					End If
				Else
					B4XPages.MainPage.detalleVenta.prodsMap.Initialize
					B4XPages.ShowPage("DetalleVenta")
				End If
			End If
		End If
	End If
'	B4XPages.MainPage.historico.prodsMap.Initialize
	''	B4XPages.MainPage.historico.clv_pedido.Clear
'	B4XPages.ShowPage("Historico")
'	B4XPages.MainPage.historico.clv_pedido.Clear

End Sub

Sub B_IMP_Click
	c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	ProgressDialogShow("Imprimiendo, un momento ...")
'	Printer1.DisConnect
'	If Not(Printer1.IsConnected) Then
''		Log("Conectando a impresora ...")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada)
'			Sleep(1000)
''			Log("++++++  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect 'Tratamos de reconectar
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	Else
''		Log("conectando 2")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
'			Sleep(1000)
''			Log("******  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	End If

	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	
	TAMANO = 0
	ESPACIO = 28
	BLANCO = " "
	Dim bmp As Bitmap
	bmp.InitializeResize(File.DirAssets, "logo-guna-18.jpg", 192, 192, True) 'ignore
	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
	myimage = Printer1.DitherImage2D(myimage, 128)
	myimage= Printer1.PackImage(myimage)
	Printer1.WriteString(CRLF) ' nudge the printer to show the user something is happening
	Printer1.WriteString(Printer1.REVERSE)
	Printer1.PrintImage(myimage)
	Printer1.WriteString(Printer1.UNREVERSE)
'	Dim Ticket As String = 0
'	Dim c6 As Cursor = Starter.skmt.ExecQuery("select distinct HVD_NUM_TICKET FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'	If c6.RowCount > 0 Then
'		c6.Position = 0
'		Ticket = c6.GetString("HVD_NUM_TICKET")
'	End If
'	c6.Close
	Dim telefono As String = ""
	Dim c7 As Cursor = Starter.skmt.ExecQuery("select IFNULL(CAT_CL_TELEFONO,' ') AS CAT_CL_TELEFONO FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	If c7.RowCount > 0 Then
		c7.Position = 0
		telefono = c7.GetString("CAT_CL_TELEFONO")
	End If
	c7.Close
	
	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  CRLF)
	Printer1.WriteString(sDate &  CRLF)
	Printer1.WriteString(sTime &  CRLF)
	Printer1.WriteString("Reparto:" & usuario &  CRLF)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  CRLF)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  CRLF)
	Printer1.WriteString("Calle: " & la_Calle.Text &  CRLF)
	Printer1.WriteString("Colonia: " & la_col.Text &  CRLF)
	Printer1.WriteString("Telefono: " & telefono &  CRLF)
	
	Dim Ticket As String = 0
	Dim c6 As Cursor = Starter.skmt.ExecQuery("select distinct HVD_NUM_TICKET FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If c6.RowCount > 0 Then
		For k = 0 To c6.RowCount -1
			c6.Position = k
			Ticket = c6.GetString("HVD_NUM_TICKET")
			Printer1.WriteString("Num. Ticket " & (k +1)&": " & Ticket &  CRLF)
		Next
	End If
	c6.Close

	Printer1.WriteString(" " &  CRLF)
	c = Starter.skmt.ExecQuery("SELECT * FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	
	
	Dim cobranza As Cursor = Starter.skmt.ExecQuery("SELECT * FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA) and HVD_PRONOMBRE = 'Cobranza Pendiente'")
	Dim restacobranza As Int = 0
	If cobranza.RowCount > 0 Then
		restacobranza = 1
	End If
	If c.RowCount > 0 Then
		' aqui es donde esta el pedo de julieta de los descuentos quitar el precio2 pero meter un if para saber si es ruta especial o es normal o que show.  ''CAT_TIPO_BONIFICACIONES
'		s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, HVD_CANT, length(HVD_CANT) as L_CANT, HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID, HVD_CODPROMO,IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) and (HVD_CODPROMO <> 'MI RETO' or HVD_CODPROMO <> 'MI RETO' or HVD_CODPROMO <> 'MI RETO') AND (HVD_COSTO_TOT/HVD_CANT) > 0.01 order by  HVD_PROID"$)
		s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) and (HVD_CODPROMO <> 'MIRETO' or HVD_CODPROMO <> 'SOCIOBAT' or HVD_CODPROMO <> 'CONECTADOS') AND HVD_CODPROMO = '${Subs.traeAlmacen}'  AND (HVD_COSTO_TOT/HVD_CANT) > 0.01 GROUP by  HVD_PROID"$)
		If S.RowCount>0 Then
		
		Printer1.WriteString("-------ENTREGA A "& Tipoentrega &"------" &  CRLF)
'		Printer1.WriteString("--------------------------------" &  CRLF)
		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
			For i=0 To S.RowCount -1
				S.Position=i
				Log(s.GetString("HVD_RECHAZO"))
				If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
					If s.GetInt("HVD_RECHAZO") = 0 Then
						Printer1.Justify = 0
						Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
						Dim punit As String = NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
						TAMANO = punit.Length + TAMANO
'						Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
						Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
						TAMANO = ptot.Length + TAMANO
						ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
						For E=0 To ESPACIO -1
							BLANCO = " " & BLANCO
						Next
						Printer1.Justify = 0
						Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
						Printer1.Justify = 1
						Printer1.WriteString( punit & BLANCO)
						Printer1.Justify = 2
						Printer1.WriteString( ptot &  CRLF )
						TAMANO = 0
						ESPACIO = 28
						BLANCO = " "
					Else If s.GetInt("HVD_RECHAZO") > 0 Then
						Printer1.Justify = 0
						Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
						Private vc5 As Cursor = Starter.skmt.ExecQuery($"select iFNULL(CAT_GP_PRECIO,0) AS CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${s.GetString("HVD_PROID")}'"$)
						vc5.Position = 0
						Dim punit As String = NumberFormat2((vc5.GetString("CAT_GP_PRECIO")),0,2,2,False)
						TAMANO = punit.Length + TAMANO
						vc5.Close
						Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
						TAMANO = ptot.Length + TAMANO
						ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
						For E=0 To ESPACIO -1
							BLANCO = " " & BLANCO
						Next
						Printer1.Justify = 0
						Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
						Printer1.Justify = 1
						Printer1.WriteString( punit & BLANCO)
						Printer1.Justify = 2
						Printer1.WriteString(ptot&  CRLF )
						TAMANO = 0
						ESPACIO = 28
						BLANCO = " "
						Printer1.Justify = 0
					End If
				End If
			Next
		End If
	End If
	Printer1.Justify = 0
	s.Close
	Printer1.WriteString(" " &  CRLF)
	
	
'	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, HVD_CANT, length(HVD_CANT) as L_CANT, HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID, HVD_CODPROMO,IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_RECHAZO = 0 AND HVD_CODPROMO <> '${Subs.traeAlmacen}' order by  HVD_CODPROMO, ESPROMO DESC, HVD_PROID"$)
	s=Starter.skmt.ExecQuery($"SELECT HVD_CODPROMO, HVD_PRONOMBRE, SUM(HVD_CANT) AS HVD_CANT, LENGTH(SUM(HVD_CANT)) AS L_CANT, SUM(HVD_COSTO_TOT) AS HVD_COSTO_TOT, LENGTH(SUM(HVD_COSTO_TOT)) AS L_COSTOU, HVD_PROID, SUM(IFNULL(HVD_RECHAZOCANT, 0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM cuentaa) AND HVD_CODPROMO <> HVD_PROID AND HVD_CODPROMO NOT IN ('SOCIOBAT', 'MIRETO', 'CONECTADOS') AND HVD_PRONOMBRE <> 'Cobranza Pendiente' AND HVD_CODPROMO <> '${Subs.traeAlmacen}' GROUP BY HVD_PROID, HVD_CODPROMO"$)
	

	If S.RowCount>0 Then
		Printer1.WriteString("------- BONIFIACIONES --------" &  CRLF)
		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		For i=0 To S.RowCount -1
			S.Position=i
			
				
			
			If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
'				If s.GetString("HVD_CODPROMO") <> Subs.traeAlmacen Then
					Printer1.Justify = 0
'					If s.GetString("HVD_CODPROMO") = s.GetString("HVD_PROID") Then
''						Printer1.WriteString("* "&s.GetString("HVD_PRONOMBRE") &  CRLF)
'						
'					Else
						
							Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
						
					Dim punit As String =NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
					Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
					Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString(ptot &  CRLF )
					TAMANO = 0
					ESPACIO = 29
					BLANCO = " "
					Printer1.Justify = 0
'					End If
'				Else
'				End If
			End If
			
		Next
	End If
	
'	Printer1.WriteString(" " &  CRLF)
'	s=Starter.skmt.ExecQuery($"select PE_PRONOMBRE, PE_CANT, length(PE_CANT) as L_CANT, PE_COSTO_TOT, length(PE_COSTO_TOT) as L_COSTOU,PE_PROID FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) order BY PE_PROID"$)
	'
'	If S.RowCount>0 Then
'		Printer1.WriteString("-----------VENTA------------" &  CRLF)
'		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
'		Printer1.WriteString("------------------------------" &  CRLF)
'		
'		For i=0 To S.RowCount -1
'			S.Position=i
	'
'			Printer1.Justify = 0
'			Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  CRLF)
'			Dim punit As String =NumberFormat2( (s.GETSTRING("PE_COSTO_TOT")/s.GetString("PE_CANT")),0,2,2,False)
'			TAMANO = punit.Length + TAMANO
'			Private ptot As String = NumberFormat2((punit*s.GetString("PE_CANT")),0,2,2,False)
'			TAMANO = ptot.Length + TAMANO
'			ESPACIO = (ESPACIO - TAMANO)/2
'			Log(ESPACIO)
'			For E=0 To ESPACIO -1
'				BLANCO = " " & BLANCO
'			Next
'			Printer1.Justify = 0
'			Printer1.WriteString( s.GetString("PE_CANT") & BLANCO)
'			Printer1.Justify = 1
'			Printer1.WriteString( punit & BLANCO)
'			Printer1.Justify = 2
'			Printer1.WriteString(ptot &  CRLF )
'			TAMANO = 0
'			ESPACIO = 29
'			BLANCO = " "
'			Printer1.Justify = 0
'		Next
'	End If
Printer1.WriteString(" " &  CRLF)
	
	
	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_CODPROMO = 'MIRETO' GROUP by  HVD_PROID"$)
	If S.RowCount>0 Then
		Printer1.WriteString("----------- MI RETO ------------" &  CRLF)
'		Printer1.WriteString("--------------------------------" &  CRLF)
		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		For i=0 To S.RowCount -1
			S.Position=i
			Log(s.GetString("HVD_RECHAZO"))
			If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
				If s.GetInt("HVD_RECHAZO") = 0 Then
					Printer1.Justify = 0
					Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
					Dim punit As String = NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
'						Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
					Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString( ptot &  CRLF )
					TAMANO = 0
					ESPACIO = 28
					BLANCO = " "
				Else If s.GetInt("HVD_RECHAZO") > 0 Then
					Printer1.Justify = 0
					Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
					Private vc5 As Cursor = Starter.skmt.ExecQuery($"select iFNULL(CAT_GP_PRECIO,0) AS CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${s.GetString("HVD_PROID")}'"$)
					vc5.Position = 0
					Dim punit As String = NumberFormat2((vc5.GetString("CAT_GP_PRECIO")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
					vc5.Close
					Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString(ptot&  CRLF )
					TAMANO = 0
					ESPACIO = 28
					BLANCO = " "
					Printer1.Justify = 0
				End If
			End If
		Next
	End If
	Printer1.Justify = 0
	s.Close
	
	Printer1.WriteString(" " &  CRLF)
	
	
	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_CODPROMO = 'CONECTADOS' GROUP by  HVD_PROID"$)
'	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_CODPROMO = 'SOCIOBAT' GROUP by  HVD_PROID"$)
	If S.RowCount>0 Then
		Printer1.WriteString("---------- CONECTADOS ----------" &  CRLF)
'		Printer1.WriteString("--------------------------------" &  CRLF)
		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		For i=0 To S.RowCount -1
			S.Position=i
			Log(s.GetString("HVD_RECHAZO"))
			If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
				If s.GetInt("HVD_RECHAZO") = 0 Then
					Printer1.Justify = 0
					Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
					Dim punit As String = NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
'						Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
					Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString( ptot &  CRLF )
					TAMANO = 0
					ESPACIO = 28
					BLANCO = " "
				Else If s.GetInt("HVD_RECHAZO") > 0 Then
					Printer1.Justify = 0
					Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
					Private vc5 As Cursor = Starter.skmt.ExecQuery($"select iFNULL(CAT_GP_PRECIO,0) AS CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${s.GetString("HVD_PROID")}'"$)
					vc5.Position = 0
					Dim punit As String = NumberFormat2((vc5.GetString("CAT_GP_PRECIO")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
					vc5.Close
					Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString(ptot&  CRLF )
					TAMANO = 0
					ESPACIO = 28
					BLANCO = " "
					Printer1.Justify = 0
				End If
			End If
		Next
	End If
	Printer1.Justify = 0
	s.Close
	
'	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_CODPROMO = 'CONECTADOS' GROUP by  HVD_PROID"$)
	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_CODPROMO = 'SOCIOBAT' GROUP by  HVD_PROID"$)
	If S.RowCount>0 Then
		Printer1.WriteString("---------- SOCIO BAT ----------" &  CRLF)
'		Printer1.WriteString("--------------------------------" &  CRLF)
		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		For i=0 To S.RowCount -1
			S.Position=i
			Log(s.GetString("HVD_RECHAZO"))
			If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
				If s.GetInt("HVD_RECHAZO") = 0 Then
					Printer1.Justify = 0
					Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
					Dim punit As String = NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
'						Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
					Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString( ptot &  CRLF )
					TAMANO = 0
					ESPACIO = 28
					BLANCO = " "
				Else If s.GetInt("HVD_RECHAZO") > 0 Then
					Printer1.Justify = 0
					Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
					Private vc5 As Cursor = Starter.skmt.ExecQuery($"select iFNULL(CAT_GP_PRECIO,0) AS CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${s.GetString("HVD_PROID")}'"$)
					vc5.Position = 0
					Dim punit As String = NumberFormat2((vc5.GetString("CAT_GP_PRECIO")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
					vc5.Close
					Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString(ptot&  CRLF )
					TAMANO = 0
					ESPACIO = 28
					BLANCO = " "
					Printer1.Justify = 0
				End If
			End If
		Next
	End If
	Printer1.Justify = 0
	s.Close

	
	Printer1.WriteString(" " &  CRLF)
	
	
	
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString("Total Articulos:   " & (L_CANT.Text.Replace(",","") -restacobranza) &  CRLF)
	Printer1.WriteString("Total:   $" & l_total.Text)
	Printer1.WriteString(" " &  CRLF)
	
	If almacen = "81" Then
		Printer1.WriteString("Telefono de atención:" &  CRLF)
		Printer1.WriteString("" &  CRLF)
	End If
	
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString("----ESTE TICKET NO ES UN -----" &  CRLF)
	Printer1.WriteString("--COMPROBANTE FISCAL, SOLO ES-" &  CRLF)
	Printer1.WriteString("--------INFORMATIVO-----------" &  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	
	
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Sleep(1000)
	Printer1.DisConnect
	ProgressDialogHide
	If banderaimp = 1 Then
		Msgbox2Async("Deseas imprimir de nuevo el ticket?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
		Wait For Msgbox_Result (resultado As Int)
		If resultado = DialogResponse.POSITIVE Then
			B_IMP_Click
		Else
			If Tipoentrega = "CREDITO" Then
				imprime_pagare
			Else
				
			End If
		End If
'	printer.Flush
		'	printer.Close
	Else If banderaimp = 0 Then
		Msgbox2Async("Deseas imprimir de nuevo el ticket?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
		Wait For Msgbox_Result (resultado As Int)
		If resultado = DialogResponse.POSITIVE Then
			B_IMP_Click
		End If
	End If
'	Guardado
End Sub

Sub Printer1_Connected (Success As Boolean)
'	If Logger Then Log("Printer1_Connected")
	If Success Then
		ToastMessageShow("Impresora conectada", False)
		Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MACIMP"))
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MACIMP",Starter.mac_impresora))
'		If logger Then LogColor("Impresora conectada", Colors.Green)
'		B_IMP2.Enabled = True
		impresoraConectada = True
	Else
'		Msgbox(Printer1.ConnectedErrorMsg, "Error connecting.") 'ignore
'		ToastMessageShow("Error conectando la impresora", False)
		LogColor("Error conectando la impresora", Colors.Red)
		errorImpresora = errorImpresora + 1
		If errorImpresora > 1 Then
			Starter.MAC_IMPRESORA = "0"
			errorImpresora = 0
		End If
	End If
End Sub

Sub Printer1_Error
	Log("error printer")
End Sub

Sub Printer_Connected (Success As Boolean)
	If Success Then
'		B_IMP.Enabled = True
		PASA_IMP = "1"
	Else
'		B_IMP.Enabled = False
		If Msgbox2("", "Printer Error","Reprint","Cancel","",Null) = DialogResponse.POSITIVE Then 'ignore
			StartPrinter
		End If
	End If
End Sub

Sub StartPrinter
	Dim PairedDevices As Map
	Dim L1 As List
	Dim resimp As Int
	ToastMessageShow("Printing.....",True)
	PairedDevices.Initialize
	Try
		PairedDevices = cmp20.GetPairedDevices
	Catch
		Msgbox("Getting Paired Devices","Printer Error") 'ignore
		printer.Close
		cmp20.Disconnect
	End Try

	If PairedDevices.Size = 0 Then
		Msgbox("Error Connecting to Printer - Printer Not Found","") 'ignore
		Return
	End If

	If PairedDevices.Size = 1 Then
		Try
			cmp20.Connect(PairedDevices.Get(PairedDevices.GetKeyAt(0)))
		Catch
			Msgbox("Connecting","Printer Error") 'ignore
			printer.Close
			cmp20.Disconnect
		End Try
	Else
		L1.Initialize
		For i = 0 To PairedDevices.Size - 1
			L1.Add(PairedDevices.GetKeyAt(i))
		Next
		resimp = InputList(L1, "Choose device", -1) 'ignore
		If resimp <> DialogResponse.CANCEL Then
			cmp20.Connect(PairedDevices.Get(L1.Get(resimp)))
		End If
	End If
End Sub


Sub B_PASO2_Click
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c=Starter.skmt.ExecQuery("select CUENTA from cuentaa")
	c.Position = 0
	cuenta = c.GetString("CUENTA")
	c=Starter.skmt.ExecQuery("select usuario from usuarioa")
	c.Position = 0
	usuario = c.GetString("USUARIO")
	c.Close
	Starter.skmt.ExecNonQuery("DELETE FROM NOVENTA WHERE NV_CLIENTE IN (select cuenta from cuentaa)")
	Starter.skmt.ExecNonQuery2("INSERT INTO  NOVENTA (NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON) VALUES(?,?,?,?,?,?,?) ", Array As Object (cuenta,sDate & sTime, usuario, "PASO","PASO ESPERA", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
'	Dim mandamapa As Cursor = Starter.skmt.ExecQuery("SELECT * FROM kmt_info WHERE gestion = 0")
'	If mandamapa.RowCount > 0 Then
'		StartActivity(MAPA_RUTAS)
'	Else If mandamapa.RowCount = 0 Then
	B4XPages.ShowPage("Principal")
'	End If
End Sub


Sub mandaPendientesreparto
'	c=Starter.skmt.ExecQuery("SELECT  CLIENTE, USUARIO, FECHA_PUNTEO, LATITUD, LONGITUD, ALMACEN, RUTA_REPARTO, RUTA_PREV, FECHA_PREVENTA, MOTIVO, COMENTARIO,TIPO FROM REPARTO_GEO where ENVIO <> 1")
'	Log($"REPARTO_Cliente PENDIENTE: ${c.RowCount}"$)
'	If c.RowCount>0 Then
'		For i=0 To c.RowCount -1
'			c.Position=i
'			Dim cmd As DBCommand
'			cmd.Initialize
'			cmd.Name = "insert_REPARTO_MARDS"'Ojala no Truene
'			cmd.Parameters = Array As Object(c.GetString("CLIENTE"), c.GetString("USUARIO"), c.GetString("FECHA_PUNTEO"), c.GetString("LATITUD"), c.GetString("LONGITUD"), c.GetString("ALMACEN"), c.GetString("RUTA_REPARTO"), c.GetString("RUTA_PREV"), c.GetString("FECHA_PREVENTA"), c.GetString("MOTIVO"), c.GetString("COMENTARIO"),c.GetString("TIPO"))
'			reqManager.ExecuteCommand(cmd , $"ins_REPARTOPendientes_head_${c.GetString("CLIENTE")}"$)
'			
'		Next
'	End If
'	c.Close
End Sub

Sub JobDone(Job As HttpJob)
	Log(Job.Success)
	If Job.Success = False Then
'		ToastMessageShow("Error: " & Job.ErrorMessage, True)
	Else
		LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green)  'Mod por CHV - 211027
		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag.As(String).IndexOf("ins_REPARTOPendientes_head_") > -1 Then
				Private cliente As String= resultado.Tag
				cliente = cliente.SubString(cliente.IndexOf("_")+24)
				Log($"Cliente1:${cliente}"$)
				Starter.skmt.ExecNonQuery2("update REPARTO_GEO SET ENVIO = ? WHERE CLIENTE = ? AND ENVIO <> ?",Array As String ("1", cliente,"1"))
				For Each records() As Object In resultado.Rows
					For Each k As String In resultado.Columns.Keys
						Log(resultado.Tag & ": " & k & ": " & records(resultado.Columns.Get(k)))
					Next
				Next
			End If
			If resultado.Tag.As(String).IndexOf("insertaPagare_") > -1 Then
				ProgressDialogHide
				Private NOTA As String= resultado.Tag
				NOTA = NOTA.SubString(NOTA.IndexOf("_")+1)
				Log(NOTA)
				p_transPagare2.Visible = True
				CrearQR(NOTA)
				
				
				
				
			End If
			If resultado.Tag.As(String).IndexOf("pagareConfirmado_") > -1 Then
				ProgressDialogHide
				Subs.logJobDoneResultados(resultado)
				Private NOTA As String= resultado.Tag
				NOTA = NOTA.SubString(NOTA.IndexOf("_")+1)
'				Log(NOTA)
'				Log(resultado.Rows.Size)
				If resultado.Rows.Size > 0 Then
					p_transPagare2.Visible = False
'					guardaVenta
					esPagoACreditoGuardamosPagare
'					Msgbox("¡Pagare confirmado!", "AVISO") 'ignore
				Else
					ToastMessageShow("El pagare NO ha sido confirmado por el cliente!", True)
				End If
			End If
		End If
		Job.Release
	End If
End Sub

Private Sub b_acred_Click
	If et_montoacredito.Text > l_total.Text Then
		MsgboxAsync("El monto del pagare no puede ser mayor a la venta","Atención")
	Else
		DateTime.DateFormat = "dd/MM/yyyy"
		DateTime.TimeFormat = "HH:mm:ss"
		sDate=DateTime.Date(DateTime.Now)
		sTime=DateTime.Time(DateTime.Now)
		'cliente
		c=Starter.skmt.ExecQuery("select CUENTA from cuentaa")
		c.Position = 0
		cuenta = c.GetString("CUENTA")
		c.Close
		'usuario
		c=Starter.skmt.ExecQuery("select usuario from usuarioa")
		c.Position = 0
		usuario = c.GetString("USUARIO")
		c.Close
		'Almacen
		c=Starter.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
		c.Position = 0
		almacen = c.GetString("ID_ALMACEN")
		c.Close
		'FECHA PREVENTA
		c=Starter.skmt.ExecQuery("select HVD_FECHA from HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
		c.Position = 0
		fechaprev = c.GetString("HVD_FECHA")
		c.Close
		'RUTAPREVENTA
		c=Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
		c.Position = 0
		rutaprev = c.GetString("CAT_CL_RUTA")
		c.Close
		'RUTA rep
		c=Starter.skmt.ExecQuery("select RUTAA from RUTAA")
		c.Position = 0
		rutarep = c.GetString("RUTAA")
		c.Close
		Starter.skmt.ExecNonQuery2("INSERT INTO  PAGARES (PA_ALMACEN, PA_RUTA_REP, PA_RUTAPREV, PA_FECHA_PREV, PA_CAPTURA, PA_MONTO, PA_USUARIO, PA_CLIENTE) VALUES(?,?,?,?,?,?,?,?) ", Array As Object (almacen,rutarep,rutaprev,fechaprev,(sDate),et_montoacredito.Text,usuario,cuenta))
		et_montoacredito.Text = ""
		p_credito.Visible = False
		Guardado
	End If
End Sub

Private Sub b_cancred_Click
	et_montoacredito.Text = ""
	p_credito.Visible = False
End Sub

Private Sub p_credito_Click
	
End Sub

Private Sub cb_tipopago_SelectedIndexChanged (Index As Int)
	itemselect = cb_tipopago.SelectedItem
End Sub

Private Sub b_cxc_Click
	tipo_abonox = "cxc"
	Folio = ""
	h = Starter.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
	h.Position = 0
	Log(h.GetString("CUENTA"))
	
	Dim Items As List
	Items.Initialize
	
	Items.Add("SELECCIONA UNA OPCION")
	Items.Add("TRANSFERENCIA")
	Items.Add("EFECTIVO")
	Items.Add("CHEQUE")
		
	cb_tipopago.SetItems(Items)
	
	itemselect= "SELECCIONA UNA OPCION"
	
	j = Starter.skmt.ExecQuery2("SELECT a_abono FROM ABONOS WHERE a_cliente = ?", Array As String(h.GetString("CUENTA")))
	j.position = 0
	Log(j.RowCount)
	If j.RowCount = 0 Then
		p_abono.Visible = True
		et_abono.text = ""
		Dim total As Double = 0
		f = Starter.skmt.ExecQuery("SELECT CUENTA FROM CUENTAA")
		f.Position = 0
		d = Starter.skmt.ExecQuery2("SELECT NOTA, SALDO_PENDIENTE,FECHA_PREVENTA FROM ABONOSP WHERE CLIENTE = ? AND SALDO_PENDIENTE <> 0 ORDER BY FECHA_PREVENTA DESC", Array As String (f.GetString("CUENTA")))
		clv_abonos.Clear
		For i = 0 To d.RowCount - 1
			d.Position = i
			Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) AND a_ticket = ?", Array As String(d.GetString("NOTA")))
			Log(Folio)
			y.position = 0
			
			clv_abonos.Add(CreateListItem(d.GetString("NOTA"),"$ " &NumberFormat2(d.GetString("SALDO_PENDIENTE")-y.GetString("a_abono"),0,2,2,False),d.GetString("FECHA_PREVENTA")),i)
			Log(d.GetString("NOTA"))
			Log(d.GetString("SALDO_PENDIENTE"))
			total = total + d.GetString("SALDO_PENDIENTE")
			Log(total)
		Next
		d.Close
		d = Starter.skmt.ExecQuery2("SELECT  a_abono,a_fecha FROM ABONOS WHERE a_cliente = ? and a_tipoabono is null ORDER BY a_fecha DESC ", Array As String (f.GetString("CUENTA")))
		If d.RowCount > 0 Then
			For i = 0 To d.RowCount - 1
				d.Position = i
				clv_abonos.Add(CreateListItem("ABONO","$ " & d.GetString("a_abono"),d.GetString("a_fecha")),i)
				total = total - d.GetString("a_abono")
				Log(total)
			Next
		End If
		l_montoabonostotal.Text = NumberFormat2(total,0,2,2,False)
		d.Close
		f.Close
	Else If j.RowCount > 0 Then
		p_abono.Visible = True
		et_abono.text = ""
		Dim total As Double = 0
		f = Starter.skmt.ExecQuery("SELECT CUENTA FROM CUENTAA")
		f.Position = 0
		d = Starter.skmt.ExecQuery2("SELECT NOTA, SALDO_PENDIENTE,FECHA_PREVENTA FROM ABONOSP WHERE CLIENTE = ? AND SALDO_PENDIENTE <> 0 ORDER BY FECHA_PREVENTA DESC", Array As String (f.GetString("CUENTA")))
		clv_abonos.Clear
		For i = 0 To d.RowCount - 1
			d.Position = i
			Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) AND a_ticket = ?", Array As String(d.GetString("NOTA")))
			Log(Folio)
			y.position = 0
			
			clv_abonos.Add(CreateListItem(d.GetString("NOTA"),"$ " & NumberFormat2(d.GetString("SALDO_PENDIENTE")-y.GetString("a_abono"),0,2,2,False),d.GetString("FECHA_PREVENTA")),i)
			Log(d.GetString("NOTA"))
			Log(d.GetString("SALDO_PENDIENTE"))
			total = total + d.GetString("SALDO_PENDIENTE")
			Log(total)
		Next
		d.Close
		d = Starter.skmt.ExecQuery2("SELECT  a_abono,a_fecha FROM ABONOS WHERE a_cliente = ? and a_tipoabono is null ORDER BY a_fecha DESC", Array As String (f.GetString("CUENTA")))
		If d.RowCount > 0 Then
			For i = 0 To d.RowCount - 1
				d.Position = i
				clv_abonos.Add(CreateListItem("ABONO","$ " & d.GetString("a_abono"),d.GetString("a_fecha")),i)
				total = total - d.GetString("a_abono")
				Log(total)
			Next
		End If
		l_montoabonostotal.Text = NumberFormat2(total,0,2,2,False)
		d.Close
		f.Close
'		MsgboxAsync("Este cliente ya tiene un pago capturado","Atención")
	End If
	h.Close
	j.Close
End Sub

Private Sub p_abono_Click
	
End Sub

'Sub CreateListItem(mostrar As String, mostrar1 As String, mostrar2 As String) As Panel
'	Dim p As B4XView = xui.CreatePanel("")
'	p.SetLayoutAnimated(0, 0, 0, 1, 10)
'	p.LoadLayout("folioabono")
'	p.Height= 32dip
'	p.Width = 80dip
''	p.Width = clv_orden.GetBase.Width
'	l_folio.Text = mostrar
'	l_saldo.Text = mostrar1
'	l_fecha.Text = mostrar2
''	cxc.Text = mostrar3
	''	Log(p.Width)
'	Return p
'End Sub

'Sub CreateListItem(mostrar As String, mostrar1 As String, mostrar2 As String) As Panel
'	Dim p As B4XView = xui.CreatePanel("")
'	p.SetLayoutAnimated(0, 0, 0, 1, 10)
'	p.LoadLayout("folioabono")
'	p.Height= 32dip
'	p.Width = 80dip
'	
'	l_folio.Text = mostrar
'	l_saldo.Text = mostrar1
'	l_fecha.Text = mostrar2
'	
'	CheckBox1.Checked = False
'	p.Tag = mostrar
'	Return p
'End Sub



' Evento del checkbox
'Sub CheckBox1_CheckedChange(Checked As Boolean)
'	Dim chk As CheckBox = Sender
'	
'	If Checked Then
'		For i = 0 To clv_abonos.Size - 1
'			Dim p As Panel = clv_abonos.GetPanel(i)
'			Log("Folio: " & p.Tag)
'			
'			' OBTENER EL TEXTO DIRECTAMENTE DEL TAG
'			
'			' Buscar y desmarcar otros checkboxes...
'			For Each v As View In p.GetAllViewsRecursive
'				If v Is CheckBox Then
'					Dim otherChk As CheckBox = v
'					If otherChk <> chk Then
'						otherChk.Checked = False
'					End If
'					Exit
'				End If
'			Next
'		Next
'	End If
'End Sub


Sub CreateListItem(mostrar As String, mostrar1 As String, mostrar2 As String) As Panel
	Dim p As B4XView = xui.CreatePanel("")
	p.SetLayoutAnimated(0, 0, 0, 1, 10)
	p.LoadLayout("folioabono")
	p.Height= 32dip
	p.Width = 80dip
	Folio = ""
	l_folio.Text = mostrar
	l_saldo.Text = mostrar1
	l_fecha.Text = mostrar2
	If mostrar = "ABONO" Then
		CheckBox1.Visible = False
	Else
		CheckBox1.Visible = True
	End If
	' Guardar referencia al label en el Tag del checkbox
	CheckBox1.Tag = l_folio
	
	
	Return p
End Sub

Sub CheckBox1_CheckedChange(Checked As Boolean)
	

		If ChangingCheckboxesProgrammatically Then Return
	
	Dim chk As CheckBox = Sender
	If chk.Checked = False Then
	
		et_abono.Text = ""
	End If
	
		If Checked Then
			' Obtener directamente el label desde el Tag del checkbox
			Dim l_folio As Label = chk.Tag
	
			Log("Folio seleccionado: " & l_folio.Text)
			Folio = l_folio.Text
			' Indicar que estamos cambiando checkboxes programáticamente
			ChangingCheckboxesProgrammatically = True
		
			If tipo_abonox = "cxc" Then
				Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) AND a_ticket = ?", Array As String(Folio))
				Log(Folio)
				y.position = 0
				Dim u As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(SALDO_PENDIENTE),0) AS SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND NOTA = ?", Array As String(Folio))
				u.Position = 0
			
				et_abono.Text = u.GetDouble("SALDO_PENDIENTE") - y.GetDouble("a_abono")
			Else If tipo_abonox = "abono" Then
				Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) AND a_ticket = ?", Array As String(Folio))
				Log(Folio)
				y.position = 0
				c = Starter.skmt.ExecQuery($"select iFNULL(sum(PA_MONTO),0) AS SALDO_PENDIENTE from PAGARES where PA_CLIENTE = '${la_cuenta.Text}'"$)
				c.Position = 0
			
				et_abono.Text = c.GetDouble("SALDO_PENDIENTE") - y.GetDouble("a_abono")
			End If
		
			' Desmarcar todos los demás checkboxes
			For i = 0 To clv_abonos.Size - 1
				Dim p As Panel = clv_abonos.GetPanel(i)
				Dim panelCheckbox As CheckBox = GetCheckboxFromPanel(p)
			
				If panelCheckbox <> Null And panelCheckbox <> chk Then
					panelCheckbox.Checked = False
				End If
			Next
		
			' Restaurar flag
			ChangingCheckboxesProgrammatically = False
		End If

End Sub

Sub GetCheckboxFromPanel(p As Panel) As CheckBox
	For Each v As View In p.GetAllViewsRecursive
		If v Is CheckBox Then
			Return v
		End If
	Next
	Return Null
  End Sub



Private Sub b_cancelar_Click
	et_abono.Text = ""
	p_abono.Visible = False
	ime.HideKeyboard
End Sub

Private Sub b_abono_Click
'	p_abono.Visible = False
	If et_abono.Text <> "" Then
'		If almacen = 92 Then
'			
'			Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) AND a_ticket = ?", Array As String(Folio))
'			Log(Folio)
'			y.position = 0
'			Dim u As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(SALDO_PENDIENTE),0) AS SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND NOTA = ?", Array As String(Folio))
'			u.Position = 0
'			
'			If y.GetString("a_abono") > 0 Then
'				Log((u.GetString("SALDO_PENDIENTE") + y.GetString("a_abono")))
'				If et_abono.text > (u.GetString("SALDO_PENDIENTE") - y.GetString("a_abono")) Then
'					MsgboxAsync("El monto a abonar no puede ser mayor que el monto del pagare seleccionado","Atención" )
'				Else
'					If et_abono.Text <> "" And et_abono.Text > 0 Then
'						If itemselect <> "SELECCIONA UNA OPCION" Then
'							If Folio <> "" Then
'								Msgbox2Async($"¿Seguro que quieres realizar un abono de $${et_abono.text} para este cliente?"$, "Guardar Abono", "Guardar", "Cancelar", "", Null, True)
'								Wait For Msgbox_Result (resultado As Int)
'								If resultado = DialogResponse.POSITIVE Then
'									imprime_abonopagare
'								End If
'							Else
'								MsgboxAsync("Por favor selecciona un pagare para aplicar el pago","Atención")
'							End If
'						Else
'							MsgboxAsync("Por favor selecciona un metodo de pago","Atención")
'						End If
'					End If
'				End If
'			Else
'				
'				Log("entramos aqui")
'				If Folio <> "" Then
'				If et_abono.text >= u.GetString("SALDO_PENDIENTE") Then
'					MsgboxAsync("El monto a abonar no puede ser mayor que el monto del pagare seleccionado","Atención" )
'				Else
'					If et_abono.Text <> "" And et_abono.Text > 0 Then
'						If itemselect <> "SELECCIONA UNA OPCION" Then
'							
'								Msgbox2Async($"¿Seguro que quieres realizar un abono de $${et_abono.text} para este cliente?"$, "Guardar Abono", "Guardar", "Cancelar", "", Null, True)
'								Wait For Msgbox_Result (resultado As Int)
'								If resultado = DialogResponse.POSITIVE Then
'									imprime_abonopagare
'								End If
'							
'						Else
'							MsgboxAsync("Por favor selecciona un metodo de pago","Atención")
'						End If
'					End If
'				End If
'				Else
'					MsgboxAsync("Por favor selecciona un pagare para aplicar el pago","Atención")
'				End If
'			End If
'			
'		Else
		
'			If et_abono.text > l_montoabonostotal.text Then
'				MsgboxAsync("El monto a abonar no puede ser mayor que el monto total","Atención" )
'			Else
'				If et_abono.Text <> "" And et_abono.Text > 0 Then
'					If itemselect <> "SELECCIONA UNA OPCION" Then
'						If Folio <> "" Then
'				
''				Dim k As Cursor = Starter.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
''				k.Position = 0
''				Log(k.GetString("CUENTA"))
''				Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT a_abono FROM ABONOS WHERE a_cliente = ?", Array As String(k.GetString("CUENTA")))
''				y.position = 0
''				If y.RowCount = 0 Then
'							Msgbox2Async($"¿Seguro que quieres realizar un abono de $${et_abono.text} para este cliente?"$, "Guardar Abono", "Guardar", "Cancelar", "", Null, True)
'							Wait For Msgbox_Result (resultado As Int)
'							If resultado = DialogResponse.POSITIVE Then
'								imprime_abonopagare
'							End If
''				Else If et_abono.Text > y.GetString("a_abono") Then
''					Msgbox2Async($"¿Seguro que quieres realizar un abono de $${et_abono.text} para este cliente?"$, "Guardar Abono", "Guardar", "Cancelar", "", Null, True)
''					Wait For Msgbox_Result (resultado As Int)
''					If resultado = DialogResponse.POSITIVE Then
''						imprime_abonopagare
''					End If
''				Else If et_abono.Text = y.GetString("a_abono") Then
''					p_abono.Visible = False
''					et_abono.Text = ""
''				Else If et_abono.Text < y.GetString("a_abono") Then
''					p_abono.Visible = False
''					MsgboxAsync("El pago no puede ser menor al monto capturado.","Atención")
''					et_abono.Text = ""
''				End If
'						Else
'							MsgboxAsync("Por favor selecciona un pagare para aplicar el pago","Atención")
'						End If
'					Else
'						MsgboxAsync("Por favor selecciona un metodo de pago","Atención")
'					End If
'				End If
'			End If
			

			Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) AND a_ticket = ?", Array As String(Folio))
			Log(Folio)
			y.position = 0
			Dim u As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(SALDO_PENDIENTE),0) AS SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND NOTA = ?", Array As String(Folio))
			u.Position = 0
			
			If y.GetDouble("a_abono") > 0 Then
				
				
				If tipo_abonox = "cxc" Then
				
					Log((u.GetDouble("SALDO_PENDIENTE") + y.GetDouble("a_abono")))
					If et_abono.text > (u.GetDouble("SALDO_PENDIENTE") - y.GetDouble("a_abono")) Then
						Log("aqui")
						MsgboxAsync("El monto a abonar no puede ser mayor que el monto del pagare seleccionado","Atención" )
					Else
						If et_abono.Text <> "" And et_abono.Text > 0 Then
							If itemselect <> "SELECCIONA UNA OPCION" Then
								If Folio <> "" Then
									Msgbox2Async($"¿Seguro que quieres realizar un abono de $${et_abono.text} para este cliente?"$, "Guardar Abono", "Guardar", "Cancelar", "", Null, True)
									Wait For Msgbox_Result (resultado As Int)
									If resultado = DialogResponse.POSITIVE Then
										imprime_abonopagare
									End If
								Else
									MsgboxAsync("Por favor selecciona un pagare para aplicar el pago","Atención")
								End If
							Else
								MsgboxAsync("Por favor selecciona un metodo de pago","Atención")
							End If
						End If
					End If
				
				Else If tipo_abonox = "abono" Then
				
					If Folio <> "" Then
						c = Starter.skmt.ExecQuery($"select iFNULL(sum(PA_MONTO),0) AS SALDO_PENDIENTE from PAGARES where PA_CLIENTE = '${la_cuenta.Text}'"$)
						c.Position = 0
'						Log(c.GetString("SALDO_PENDIENTE") &"   "& u.GetString("SALDO_PENDIENTE"))
						If et_abono.text > (c.GetDouble("SALDO_PENDIENTE") - y.GetDouble("a_abono")) Then
							Log("aqui")
							MsgboxAsync("El monto a abonar no puede ser mayor que el monto del pagare seleccionado","Atención" )
						Else
							If et_abono.Text <> "" And et_abono.Text > 0 Then
								If itemselect <> "SELECCIONA UNA OPCION" Then
							
									Msgbox2Async($"¿Seguro que quieres realizar un abono de $${et_abono.text} para este cliente?"$, "Guardar Abono", "Guardar", "Cancelar", "", Null, True)
									Wait For Msgbox_Result (resultado As Int)
									If resultado = DialogResponse.POSITIVE Then
										imprime_abonopagare
									End If
							
								Else
									MsgboxAsync("Por favor selecciona un metodo de pago","Atención")
								End If
							End If
						End If
					Else
						MsgboxAsync("Por favor selecciona un pagare para aplicar el pago","Atención")
					End If
				
				End If
				
				
			Else
				
				Log("entramos aqui")
				If tipo_abonox = "cxc" Then
					If Folio <> "" Then
						If et_abono.text > u.GetDouble("SALDO_PENDIENTE") Then
							Log("aqui")
							MsgboxAsync("El monto a abonar no puede ser mayor que el monto del pagare seleccionado","Atención" )
						Else
							If et_abono.Text <> "" And et_abono.Text > 0 Then
								If itemselect <> "SELECCIONA UNA OPCION" Then
							
									Msgbox2Async($"¿Seguro que quieres realizar un abono de $${et_abono.text} para este cliente?"$, "Guardar Abono", "Guardar", "Cancelar", "", Null, True)
									Wait For Msgbox_Result (resultado As Int)
									If resultado = DialogResponse.POSITIVE Then
										imprime_abonopagare
									End If
							
								Else
									MsgboxAsync("Por favor selecciona un metodo de pago","Atención")
								End If
							End If
						End If
					Else
						MsgboxAsync("Por favor selecciona un pagare para aplicar el pago","Atención")
					End If
				Else If tipo_abonox = "abono" Then
					
					'''checar
					
					If Folio <> "" Then
						c = Starter.skmt.ExecQuery($"select iFNULL(sum(PA_MONTO),0) AS SALDO_PENDIENTE from PAGARES where PA_CLIENTE = '${la_cuenta.Text}'"$)
						c.Position = 0
'						Log(c.GetString("SALDO_PENDIENTE") &"   "& u.GetString("SALDO_PENDIENTE"))
						If et_abono.text > c.GetDouble("SALDO_PENDIENTE") Then
							Log("aqui")
							MsgboxAsync("El monto a abonar no puede ser mayor que el monto del pagare seleccionado","Atención" )
						Else
							If et_abono.Text <> "" And et_abono.Text > 0 Then
								If itemselect <> "SELECCIONA UNA OPCION" Then
							
									Msgbox2Async($"¿Seguro que quieres realizar un abono de $${et_abono.text} para este cliente?"$, "Guardar Abono", "Guardar", "Cancelar", "", Null, True)
									Wait For Msgbox_Result (resultado As Int)
									If resultado = DialogResponse.POSITIVE Then
										imprime_abonopagare
									End If
							
								Else
									MsgboxAsync("Por favor selecciona un metodo de pago","Atención")
								End If
							End If
						End If
					Else
						MsgboxAsync("Por favor selecciona un pagare para aplicar el pago","Atención")
					End If
				End If
				
			End If


'		End If
	End If
	ime.HideKeyboard
End Sub

Sub imprime_abonopagare2
	c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	DateTime.DateFormat = "MM/dd/yyyy"
	DateTime.TimeFormat = "HH:mm:ss"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	ProgressDialogShow("Imprimiendo, un momento ...")
'	Printer1.DisConnect
'	If Not(Printer1.IsConnected) Then
'		Log("Conectando a impresora ...")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada)
'			Sleep(1000)
'			Log("++++++  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect 'Tratamos de reconectar
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	Else
'		Log("conectando 2")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
'			Sleep(1000)
'			Log("******  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	End If

	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	TAMANO = 0
	ESPACIO = 22
	BLANCO = " "
	Dim bmp As Bitmap
	bmp.InitializeResize(File.DirAssets, "logo-guna-18.jpg", 192, 192, True) 'ignore
	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
	myimage = Printer1.DitherImage2D(myimage, 128)
	myimage= Printer1.PackImage(myimage)
	Printer1.WriteString(CRLF) ' nudge the printer to show the user something is happening
	Printer1.WriteString(Printer1.REVERSE)
	Printer1.PrintImage(myimage)
	Printer1.WriteString(Printer1.UNREVERSE)
	Dim telefono As String = ""
	Dim c7 As Cursor = Starter.skmt.ExecQuery("select IFNULL(CAT_CL_TELEFONO,' ') AS CAT_CL_TELEFONO FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	If c7.RowCount > 0 Then
		c7.Position = 0
		telefono = c7.GetString("CAT_CL_TELEFONO")
	End If
	c7.Close
	
	

	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  CRLF)
'	Printer1.WriteString(sucursal &  CRLF)
	Printer1.WriteString(sDate &  CRLF)
	Printer1.WriteString(sTime &  CRLF)
	Printer1.WriteString("Reparto:" & usuario &  CRLF)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  CRLF)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  CRLF)
	Printer1.WriteString("Calle: " & la_Calle.Text &  CRLF)
	Printer1.WriteString("Colonia: " & la_col.Text &  CRLF)
	Printer1.WriteString("Telefono: " & telefono &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Dim notaabono As String
	Dim saldopendiente As Double
	Dim saldopendiente2 As Double
	
	If tipo_abonox = "abono" Then
		
	
		c = Starter.skmt.ExecQuery($"select distinct hvd_num_ticket from hist_ventas where hvd_cliente = '${la_cuenta.Text}'  and HVD_PRONOMBRE <> 'Cobranza Pendiente' "$)
		If c.RowCount > 0 Then
			c.Position = 0
			notaabono = c.GetString("HVD_NUM_TICKET")
		End If
		c.Close
		
		c = Starter.skmt.ExecQuery($"select iFNULL(sum(PA_MONTO),0) AS SALDO_PENDIENTE from PAGARES where PA_CLIENTE = '${la_cuenta.Text}'"$)
		If c.RowCount > 0 Then
			c.Position = 0
			saldopendiente = c.GetDouble("SALDO_PENDIENTE")
			Log(c.GetString("SALDO_PENDIENTE"))
		End If
		c.Close
		
		
		Dim saldopendiente1 As Double = 0
		Dim c4 As Cursor= Starter.skmt.ExecQuery("SELECT Ifnull(SUM(a_abono),0) AS SALDO_PENDIENTE FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) and a_tipoabono is not null")
		If c4.RowCount > 0 Then
			c4.Position = 0
			Dim c5 As Cursor= Starter.skmt.ExecQuery("SELECT Ifnull(a_abono,0) AS SALDO_PENDIENTE FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) and a_tipoabono is not null")
			saldopendiente1 = c4.GetDouble("SALDO_PENDIENTE")
			
			
		End If
		c4.Close
		
	Else If tipo_abonox = "cxc" Then
		c = Starter.skmt.ExecQuery("SELECT NOTA, SUM(SALDO_PENDIENTE) AS SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
		If c.RowCount > 0 Then
			c.Position = 0
			notaabono = c.GetString("NOTA")
			saldopendiente = c.GetDouble("SALDO_PENDIENTE")
		End If
		c.Close
		
		Dim saldopendiente1 As Double = 0
		Dim c4 As Cursor= Starter.skmt.ExecQuery("SELECT Ifnull(SUM(a_abono),0) AS SALDO_PENDIENTE FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) and a_tipoabono is null")
		If c4.RowCount > 0 Then
			c4.Position = 0
			Dim c5 As Cursor= Starter.skmt.ExecQuery("SELECT Ifnull(a_abono,0) AS SALDO_PENDIENTE FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) and a_tipoabono is null")
			saldopendiente1 = c4.GetDouble("SALDO_PENDIENTE")
		End If
		c4.Close
		
		
		c = Starter.skmt.ExecQuery2("SELECT SUM(SALDO_PENDIENTE) AS SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND NOTA = ?",Array As String(Folio))
		If c.RowCount > 0 Then
			c.Position = 0
			saldopendiente2 = c.GetDouble("SALDO_PENDIENTE")
		End If
		c.Close
		
		Dim saldopendiente3 As Double = 0
		Dim c4 As Cursor= Starter.skmt.ExecQuery2("SELECT Ifnull(SUM(a_abono),0) AS SALDO_PENDIENTE FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) and a_tipoabono is null AND a_ticket = ?",Array As String(Folio))
		If c4.RowCount > 0 Then
			c4.Position = 0
'			Dim c5 As Cursor= Starter.skmt.ExecQuery("SELECT Ifnull(a_abono,0) AS SALDO_PENDIENTE FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) and a_tipoabono is null")
			saldopendiente3 = c4.GetDouble("SALDO_PENDIENTE")
		End If
		c4.Close
		
	End If
	
	
	
'	c = Starter.skmt.ExecQuery("SELECT NOTA FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'	If c.RowCount > 0 Then
'		c.Position = 0
'		notaabono = c.GetString("NOTA")
'	End If
	Dim numpago As Int = c5.RowCount + 1
	Log(notaabono)
	Log(et_abono.Text)
	Printer1.WriteString("Comprobante de pago del pagare" &  CRLF)
	Printer1.WriteString("Folio:  " & NOTA &"-"&(numpago)&  CRLF)
	Printer1.WriteString("Monto deuda: " & (NumberFormat2(l_total.Text.Replace(",",""),0,2,2,False)) &  CRLF)
	Printer1.WriteString("Monto abono:  " & (NumberFormat2((l_total.Text.Replace(",","")-limite_credito),0,2,2,False)) &  CRLF)
	Printer1.WriteString("Restante "&NOTA&": " &(NumberFormat(limite_credito,0,2)) &  CRLF)
	Printer1.WriteString("Fecha Abono: " & sDate &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString("-------------FIRMA------------" &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	DateTime.DateFormat = "ddMMyyyy"
	sDate=DateTime.Date(DateTime.Now)
	itemselect = "EFECTIVO"
	
'	Items.Add("TRANSFERENCIA")
'	Items.Add("EFECTIVO")
'	Items.Add("CHEQUE")
	Dim tipopagotick As String = ""
	If itemselect = "TRANSFERENCIA" Then
		tipopagotick = "T"
	Else If itemselect = "EFECTIVO" Then
		tipopagotick = "E"
	Else If itemselect = "CHEQUE" Then
		tipopagotick = "C"
	End If
	
	Printer1.WriteBarCode("I",NOTA&sDate&tipopagotick&numpago)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Sleep(1000)
	Printer1.DisConnect
	ProgressDialogHide
	

'	Msgbox2Async("Deseas imprimir de nuevo el ticket?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
'	
'	Wait For Msgbox_Result (resultado As Int)
'	If resultado = DialogResponse.POSITIVE Then
'		imprime_abonopagare
'	Else
'		p_abono.Visible = False
'		Starter.skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha,a_tipoabono,TIPO_PAGO,a_ticket,a_numpago) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${NumberFormat2((l_total.Text.Replace(",","")-limite_credito),0,2,2,False) }', '${Subs.fechaKMT(DateTime.now)}', 1,'${itemselect}','${Folio}','${numpago}')"$)
'		ToastMessageShow("Abono guardado", False)
'	End If

	If banderaimp = 1 Then
		Msgbox2Async("Deseas imprimir de nuevo el abono?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
		Wait For Msgbox_Result (resultado As Int)
		If resultado = DialogResponse.POSITIVE Then
			imprime_abonopagare2
		Else
			Starter.skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha,a_tipoabono,TIPO_PAGO,a_ticket,a_numpago) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${NumberFormat2((l_total.Text.Replace(",","")-limite_credito),0,2,2,False) }', '${Subs.fechaKMT(DateTime.now)}', 1,'EFECTIVO','${NOTA}','${numpago}')"$)
			ToastMessageShow("Abono guardado", False)
			Guardado
		End If
'	printer.Flush
		'	printer.Close
	Else If banderaimp = 0 Then
		Msgbox2Async("Deseas imprimir de nuevo el PAGARE?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
		Wait For Msgbox_Result (resultado As Int)
		If resultado = DialogResponse.POSITIVE Then
			imprime_abonopagare2
		End If
	End If
	
		

End Sub

'Sub hazpago
'	h = Starter.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
'	h.Position = 0
'	Log(h.GetString("CUENTA"))
'	j = Starter.skmt.ExecQuery2("SELECT a_abono FROM ABONOS WHERE a_cliente = ?", Array As String(h.GetString("CUENTA")))
'	j.position = 0
'	If j.RowCount = 0 Then
'		p_abono.Visible = False
'		Starter.skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${et_abono.text}', '${Subs.fechaKMT(DateTime.now)}')"$)
'		ToastMessageShow("Abono guardado", False)
'		et_abono.Text = ""
'	Else
'		p_abono.Visible = False
''			skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${et_abono.text}', '${Subs.fechaKMT(DateTime.now)}')"$)
'		Starter.skmt.ExecNonQuery($"UPDATE ABONOS set a_abono = '${et_abono.text}' where  a_usuario = '${Subs.traeUsuarioDeBD}' and a_ruta = '${Subs.traeRuta(Subs.traeCliente)}' and  a_cliente In (select cuenta from cuentaa)"$)
'		ToastMessageShow("Abono guardado", False)
'		et_abono.Text = ""
'	End If
'End Sub

Sub imprime_abonopagare
	c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	DateTime.DateFormat = "MM/dd/yyyy"
	DateTime.TimeFormat = "HH:mm:ss"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	ProgressDialogShow("Imprimiendo, un momento ...")
'	Printer1.DisConnect
'	If Not(Printer1.IsConnected) Then
'		Log("Conectando a impresora ...")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada)
'			Sleep(1000)
'			Log("++++++  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect 'Tratamos de reconectar
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	Else
'		Log("conectando 2")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
'			Sleep(1000)
'			Log("******  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	End If
	bc.Initialize
	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	TAMANO = 0
	ESPACIO = 22
	BLANCO = " "
	Dim bmp As Bitmap
	bmp.InitializeResize(File.DirAssets, "logo-guna-18.jpg", 192, 192, True) 'ignore
	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
	myimage = Printer1.DitherImage2D(myimage, 128)
	myimage= Printer1.PackImage(myimage)
	Printer1.WriteString(CRLF) ' nudge the printer to show the user something is happening
	Printer1.WriteString(Printer1.REVERSE)
	Printer1.PrintImage(myimage)
	Printer1.WriteString(Printer1.UNREVERSE)
	Dim telefono As String = ""
	Dim c7 As Cursor = Starter.skmt.ExecQuery("select IFNULL(CAT_CL_TELEFONO,' ') AS CAT_CL_TELEFONO FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	If c7.RowCount > 0 Then
		c7.Position = 0
		telefono = c7.GetString("CAT_CL_TELEFONO")
	End If
	c7.Close
	
	

	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  CRLF)
'	Printer1.WriteString(sucursal &  CRLF)
	Printer1.WriteString(sDate &  CRLF)
	Printer1.WriteString(sTime &  CRLF)
	Printer1.WriteString("Reparto:" & usuario &  CRLF)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  CRLF)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  CRLF)
	Printer1.WriteString("Calle: " & la_Calle.Text &  CRLF)
	Printer1.WriteString("Colonia: " & la_col.Text &  CRLF)
	Printer1.WriteString("Telefono: " & telefono &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Dim notaabono As String
	Dim saldopendiente As Double
	Dim saldopendiente2 As Double
	
	If tipo_abonox = "abono" Then
		
	
		c = Starter.skmt.ExecQuery($"select distinct hvd_num_ticket from hist_ventas where hvd_cliente = '${la_cuenta.Text}'  and HVD_PRONOMBRE <> 'Cobranza Pendiente' "$)
		If c.RowCount > 0 Then
			c.Position = 0
			notaabono = c.GetString("HVD_NUM_TICKET")
		End If
		c.Close
		
		c = Starter.skmt.ExecQuery($"select iFNULL(sum(PA_MONTO),0) AS SALDO_PENDIENTE from PAGARES where PA_CLIENTE = '${la_cuenta.Text}'"$)
		If c.RowCount > 0 Then
			c.Position = 0
			saldopendiente = c.GetDouble("SALDO_PENDIENTE")
			Log(c.GetString("SALDO_PENDIENTE"))
		End If
		c.Close
		
		
		Dim saldopendiente1 As Double = 0
		Dim c4 As Cursor= Starter.skmt.ExecQuery("SELECT Ifnull(SUM(a_abono),0) AS SALDO_PENDIENTE FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) and a_tipoabono is not null")
		If c4.RowCount > 0 Then
			c4.Position = 0
			Dim c5 As Cursor= Starter.skmt.ExecQuery("SELECT Ifnull(a_abono,0) AS SALDO_PENDIENTE FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) and a_tipoabono is not null")
			saldopendiente1 = c4.GetDouble("SALDO_PENDIENTE")
			
			
		End If
		c4.Close
		
	Else If tipo_abonox = "cxc" Then
		c = Starter.skmt.ExecQuery("SELECT NOTA, SUM(SALDO_PENDIENTE) AS SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
		If c.RowCount > 0 Then
			c.Position = 0
			notaabono = c.GetString("NOTA")
			saldopendiente = c.GetDouble("SALDO_PENDIENTE")
		End If
		c.Close
		
		Dim saldopendiente1 As Double = 0
		Dim c4 As Cursor= Starter.skmt.ExecQuery("SELECT Ifnull(SUM(a_abono),0) AS SALDO_PENDIENTE FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) and a_tipoabono is null")
		If c4.RowCount > 0 Then
			c4.Position = 0
			Dim c5 As Cursor= Starter.skmt.ExecQuery("SELECT Ifnull(a_abono,0) AS SALDO_PENDIENTE FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) and a_tipoabono is null")
			saldopendiente1 = c4.GetDouble("SALDO_PENDIENTE")
		End If
		c4.Close
		
		
		c = Starter.skmt.ExecQuery2("SELECT SUM(SALDO_PENDIENTE) AS SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND NOTA = ?",Array As String(Folio))
		If c.RowCount > 0 Then
			c.Position = 0
			saldopendiente2 = c.GetDouble("SALDO_PENDIENTE")
		End If
		c.Close
		
		Dim saldopendiente3 As Double = 0
		Dim c4 As Cursor= Starter.skmt.ExecQuery2("SELECT Ifnull(SUM(a_abono),0) AS SALDO_PENDIENTE FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) and a_tipoabono is null AND a_ticket = ?",Array As String(Folio))
		If c4.RowCount > 0 Then
			c4.Position = 0
'			Dim c5 As Cursor= Starter.skmt.ExecQuery("SELECT Ifnull(a_abono,0) AS SALDO_PENDIENTE FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) and a_tipoabono is null")
			saldopendiente3 = c4.GetDouble("SALDO_PENDIENTE")
		End If
		c4.Close
		
	End If
	
	
	
'	c = Starter.skmt.ExecQuery("SELECT NOTA FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'	If c.RowCount > 0 Then
'		c.Position = 0
'		notaabono = c.GetString("NOTA")
'	End If
	Dim numpago As Int = c5.RowCount + 1
	Log(notaabono)
	Log(et_abono.Text)
	Printer1.WriteString("Comprobante de pago del pagare" &  CRLF)
	Printer1.WriteString("Folio:  " & Folio &"-"&(numpago)&  CRLF)
	Printer1.WriteString("Monto deuda: " & (NumberFormat(saldopendiente2 - saldopendiente3,0,2)) &  CRLF)
	Printer1.WriteString("Monto abono:  " & (NumberFormat(et_abono.Text,0,2)) &  CRLF)
	Printer1.WriteString("Restante "&Folio&": " &(NumberFormat(saldopendiente2-et_abono.Text - saldopendiente3,0,2)) &  CRLF)
	Printer1.WriteString("Restante pagares: " &(NumberFormat(saldopendiente-et_abono.Text - saldopendiente1,0,2)) &  CRLF)
	Printer1.WriteString("Fecha Abono: " & sDate &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString("-------------FIRMA------------" &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	DateTime.DateFormat = "ddMMyyyy"
	sDate=DateTime.Date(DateTime.Now)
	
	
'	Items.Add("TRANSFERENCIA")
'	Items.Add("EFECTIVO")
'	Items.Add("CHEQUE")
	Dim tipopagotick As String = ""
	If itemselect = "TRANSFERENCIA" Then
		tipopagotick = "T"
	Else If itemselect = "EFECTIVO" Then
		tipopagotick = "E"
	Else If itemselect = "CHEQUE" Then
		tipopagotick = "C"
	End If
	
	Dim Dirp As String = File.DirInternal
	Dim Dir As String
	Dim Dir2 As String
	Try
		File.MakeDir(Dirp,"/md")
		Dir = "/md"
		Log("creado en promotoria " & Dirp & Dir)
	Catch
		Dir = ""
		Log("creado en raiz")
	End Try
	
	Try
		File.MakeDir(Dirp & Dir,"/reduccion")
		Dir2 = "/reduccion"
		Log("creado en promotoria " & Dirp & Dir & Dir2)
	Catch
		Dir = ""
		Log("creado en raiz")
	End Try
	
	
	
	Printer1.WriteBarCode("I",notaabono&sDate&tipopagotick&numpago)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Sleep(1000)
	Printer1.DisConnect
	ProgressDialogHide
	
	If Subs.traeAlmacen = "92" Then
		
''mayoreo
		If tipo_abonox = "abono" Then
			Msgbox2Async("Deseas imprimir de nuevo el ticket?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
	
			Wait For Msgbox_Result (resultado As Int)
			If resultado = DialogResponse.POSITIVE Then
				imprime_abonopagare
			Else
				p_abono.Visible = False
				Starter.skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha,a_tipoabono,TIPO_PAGO,a_ticket,a_numpago) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${et_abono.text}', '${Subs.fechaKMT(DateTime.now)}', 1,'${itemselect}','${Folio}','${numpago}')"$)
				ToastMessageShow("Abono guardado", False)
			End If
	
		Else If tipo_abonox = "cxc" Then
			Msgbox2Async("Deseas imprimir de nuevo el ticket?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
			Wait For Msgbox_Result (resultado As Int)
			If resultado = DialogResponse.POSITIVE Then
				imprime_abonopagare
'			p_abono.Visible = False
'			Starter.skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${et_abono.text}', '${Subs.fechaKMT(DateTime.now)}')"$)
'			ToastMessageShow("Abono guardado", False)
			Else
		
				h = Starter.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
				h.Position = 0
				Log(h.GetString("CUENTA"))
				j = Starter.skmt.ExecQuery2("SELECT a_abono FROM ABONOS WHERE a_cliente = ?", Array As String(h.GetString("CUENTA")))
				j.position = 0
				If j.RowCount = 0 Then
					p_abono.Visible = False
					Starter.skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha,TIPO_PAGO,a_ticket,a_numpago) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${et_abono.text}', '${Subs.fechaKMT(DateTime.now)}','${itemselect}','${Folio}','${numpago}')"$)
					ToastMessageShow("Abono guardado", False)
					Dim rutaactualizar As String
					Dim rut As Cursor = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
					If rut.RowCount > 0 Then
						rut.Position = 0
						rutaactualizar = rut.GetString("CAT_CL_RUTA")
					End If
					Starter.skmt.ExecNonQuery($"UPDATE kmt_info set gestion = 0, HORAENT = '${sDate & " " & sTime}' where CAT_CL_CODIGO In (select cuenta from cuentaa) and CAT_CL_RUTA = '${rutaactualizar}'"$)
					Starter.skmt.ExecNonQuery($"DELETE FROM NOVENTA WHERE NV_CLIENTE IN (select cuenta from cuentaa)"$)
					Private c3 As Cursor = Starter.skmt.ExecQuery("SELECT * FROM PEDIDO WHERE PE_CLIENTEOR IN (SELECT CUENTA FROM CUENTAA)")
					If c3.RowCount = 0 Then
						Starter.skmt.ExecNonQuery($"update HIST_VENTAS set HVD_RECHAZO = 0,  HVD_RECHAZOCANT = 0, BCAJAS = BCAJAS_OR, CANTC = CANTC_OR  WHERE HVD_cliente in (Select CUENTA from cuentaa)"$)
						B4XPage_Appear
					Else
						MsgboxAsync("Hay productos que ya se vendieron, no se puede regresar la venta","Atención")
					End If
					Dim textedit As Double = et_abono.Text
					Dim sumaresta As Double = saldopendiente-textedit-saldopendiente1
					Log(NumberFormat2(sumaresta,0,2,2,False))
					If NumberFormat2(sumaresta,0,2,2,False) <> "-.00" Then
						If NumberFormat2(sumaresta,0,2,2,False) <> ".00" Then
							Dim rutaactualizar As String
							Dim rut As Cursor = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
							If rut.RowCount > 0 Then
								rut.Position = 0
								rutaactualizar = rut.GetString("CAT_CL_RUTA")
							End If
'							Starter.skmt.ExecNonQuery($"UPDATE kmt_info set gestion = 3, HORAENT = '${sDate & " " & sTime}' where CAT_CL_CODIGO In (select cuenta from cuentaa) and CAT_CL_RUTA = '${rutaactualizar}'"$)
'							Starter.skmt.ExecNonQuery($"DELETE FROM NOVENTA WHERE NV_CLIENTE IN (select cuenta from cuentaa)"$)
'							Starter.skmt.ExecNonQuery2("INSERT INTO NOVENTA (NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON,NV_FOTO,NV_REPROGRAMAR) VALUES(?,?,?,?,?,?,?,?,?) ", Array As Object (la_cuenta.Text,sDate & sTime, usuario, "PAGO INCOMPLETO","PAGO INCOMPLETO", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,rutaactualizar,0))
'							Starter.skmt.ExecNonQuery("update HIST_VENTAS SET HVD_RECHAZO = 1, HVD_RECHAZOCANT = HVD_CANT, HVD_RECHAZOCANTC = CANTC, BCAJAS = 0 , CANTC = 0 WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'							Starter.skmt.ExecNonQuery($"update HIST_VENTAS set HVD_RECHAZO = 2,  HVD_RECHAZOCANT = HVD_RECHAZOCANT  WHERE HVD_PROID = HVD_CODPROMO and HVD_CLIENTE in (Select CUENTA from cuentaa)"$)
'							Starter.skmt.ExecNonQuery("DELETE FROM PEDIDO WHERE PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'							d = Starter.skmt.ExecQuery("SELECT RUTAA FROM RUTAA")
'							d.Position = 0
'							Dim ruta As String = d.GetString("RUTAA")
'							d.Close
'							d = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
'							d.Position = 0
'							Dim rutapre As String = d.GetString("CAT_CL_RUTA")
'							d.Close
'							d = Starter.skmt.ExecQuery("SELECT HVD_FECHA FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'							d.Position = 0
'							Dim fechaprev As String = d.GetString("HVD_FECHA")
'							d.Close
'							d = Starter.skmt.ExecQuery("SELECT CUENTA FROM CUENTAA")
'							d.Position = 0
'							Starter.skmt.ExecNonQuery2("INSERT INTO REPARTO_GEO (CLIENTE, USUARIO, FECHA_PUNTEO, LATITUD, LONGITUD, ALMACEN, RUTA_REPARTO, RUTA_PREV, FECHA_PREVENTA, MOTIVO, COMENTARIO,TIPO,ENVIO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,0)",Array As String (cuenta, usuario, sDate &" "&sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,B4XPages.MainPage.almacen,ruta,rutapre,fechaprev, "PAGO INCOMPLETO", "PAGO INCOMPLETO","NO ENTREGADO"))
'							B4XPages.ShowPage("Principal")
						End If
					End If
				Else
					p_abono.Visible = False
					Starter.skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha,TIPO_PAGO,a_ticket,a_numpago) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${et_abono.text}', '${Subs.fechaKMT(DateTime.now)}','${itemselect}','${Folio}','${numpago}')"$)
					ToastMessageShow("Abono guardado", False)
					Dim rutaactualizar As String
					Dim rut As Cursor = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
					If rut.RowCount > 0 Then
						rut.Position = 0
						rutaactualizar = rut.GetString("CAT_CL_RUTA")
					End If
					Starter.skmt.ExecNonQuery($"UPDATE kmt_info set gestion = 0, HORAENT = '${sDate & " " & sTime}' where CAT_CL_CODIGO In (select cuenta from cuentaa) and CAT_CL_RUTA = '${rutaactualizar}'"$)
					Starter.skmt.ExecNonQuery($"DELETE FROM NOVENTA WHERE NV_CLIENTE IN (select cuenta from cuentaa)"$)
					Private c3 As Cursor = Starter.skmt.ExecQuery("SELECT * FROM PEDIDO WHERE PE_CLIENTEOR IN (SELECT CUENTA FROM CUENTAA)")
					If c3.RowCount = 0 Then
						Starter.skmt.ExecNonQuery($"update HIST_VENTAS set HVD_RECHAZO = 0,  HVD_RECHAZOCANT = 0, BCAJAS = BCAJAS_OR, CANTC = CANTC_OR  WHERE HVD_cliente in (Select CUENTA from cuentaa)"$)
						B4XPage_Appear
					Else
						MsgboxAsync("Hay productos que ya se vendieron, no se puede regresar la venta","Atención")
					End If
					Dim textedit As Double = et_abono.Text
					Dim sumaresta As Double = saldopendiente-textedit-saldopendiente1
'			Log(NumberFormat2(sumaresta,0,2,2,False))
					If NumberFormat2(sumaresta,0,2,2,False) <> "-.00"  Then
						If NumberFormat2(sumaresta,0,2,2,False) <> ".00" Then
							Dim rutaactualizar As String
							Dim rut As Cursor = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
							If rut.RowCount > 0 Then
								rut.Position = 0
								rutaactualizar = rut.GetString("CAT_CL_RUTA")
							End If
'							Starter.skmt.ExecNonQuery($"UPDATE kmt_info set gestion = 3, HORAENT = '${sDate & " " & sTime}' where CAT_CL_CODIGO In (select cuenta from cuentaa) and CAT_CL_RUTA = '${rutaactualizar}'"$)
'							Starter.skmt.ExecNonQuery($"DELETE FROM NOVENTA WHERE NV_CLIENTE IN (select cuenta from cuentaa)"$)
'							Starter.skmt.ExecNonQuery2("INSERT INTO NOVENTA (NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON,NV_FOTO,NV_REPROGRAMAR) VALUES(?,?,?,?,?,?,?,?,?) ", Array As Object (la_cuenta.Text,sDate & sTime, usuario, "PAGO INCOMPLETO","PAGO INCOMPLETO", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,rutaactualizar,0))
'							Starter.skmt.ExecNonQuery("update HIST_VENTAS SET HVD_RECHAZO = 1, HVD_RECHAZOCANT = HVD_CANT, HVD_RECHAZOCANTC = CANTC, BCAJAS = 0 , CANTC = 0 WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'							Starter.skmt.ExecNonQuery($"update HIST_VENTAS set HVD_RECHAZO = 2,  HVD_RECHAZOCANT = HVD_RECHAZOCANT  WHERE HVD_PROID = HVD_CODPROMO and HVD_CLIENTE in (Select CUENTA from cuentaa)"$)
'							Starter.skmt.ExecNonQuery("DELETE FROM PEDIDO WHERE PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'							d = Starter.skmt.ExecQuery("SELECT RUTAA FROM RUTAA")
'							d.Position = 0
'							Dim ruta As String = d.GetString("RUTAA")
'							d.Close
'							d = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
'							d.Position = 0
'							Dim rutapre As String = d.GetString("CAT_CL_RUTA")
'							d.Close
'							d = Starter.skmt.ExecQuery("SELECT HVD_FECHA FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'							d.Position = 0
'							Dim fechaprev As String = d.GetString("HVD_FECHA")
'							d.Close
'							d = Starter.skmt.ExecQuery("SELECT CUENTA FROM CUENTAA")
'							d.Position = 0
'							Starter.skmt.ExecNonQuery2("INSERT INTO REPARTO_GEO (CLIENTE, USUARIO, FECHA_PUNTEO, LATITUD, LONGITUD, ALMACEN, RUTA_REPARTO, RUTA_PREV, FECHA_PREVENTA, MOTIVO, COMENTARIO,TIPO,ENVIO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,0)",Array As String (cuenta, usuario, sDate &" "&sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,B4XPages.MainPage.almacen,ruta,rutapre,fechaprev, "PAGO INCOMPLETO", "PAGO INCOMPLETO","NO ENTREGADO"))
'							B4XPages.ShowPage("Principal")
						End If
					End If

				End If
			End If
		End If
		
''mayoreo

	Else
		If tipo_abonox = "abono" Then
			Msgbox2Async("Deseas imprimir de nuevo el ticket?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
	
			Wait For Msgbox_Result (resultado As Int)
			If resultado = DialogResponse.POSITIVE Then
				imprime_abonopagare
			Else
				p_abono.Visible = False
				Starter.skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha,a_tipoabono,TIPO_PAGO,a_ticket,a_numpago) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${et_abono.text}', '${Subs.fechaKMT(DateTime.now)}', 1,'${itemselect}','${Folio}','${numpago}')"$)
				ToastMessageShow("Abono guardado", False)
			End If
	
		Else If tipo_abonox = "cxc" Then
			Msgbox2Async("Deseas imprimir de nuevo el ticket?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
			Wait For Msgbox_Result (resultado As Int)
			If resultado = DialogResponse.POSITIVE Then
				imprime_abonopagare
'			p_abono.Visible = False
'			Starter.skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${et_abono.text}', '${Subs.fechaKMT(DateTime.now)}')"$)
'			ToastMessageShow("Abono guardado", False)
			Else
		
				h = Starter.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
				h.Position = 0
				Log(h.GetString("CUENTA"))
				j = Starter.skmt.ExecQuery2("SELECT a_abono FROM ABONOS WHERE a_cliente = ?", Array As String(h.GetString("CUENTA")))
				j.position = 0
				If j.RowCount = 0 Then
					p_abono.Visible = False
					Starter.skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha,TIPO_PAGO,a_ticket,a_numpago) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${et_abono.text}', '${Subs.fechaKMT(DateTime.now)}','${itemselect}','${Folio}','${numpago}')"$)
					ToastMessageShow("Abono guardado", False)
					Dim rutaactualizar As String
					Dim rut As Cursor = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
					If rut.RowCount > 0 Then
						rut.Position = 0
						rutaactualizar = rut.GetString("CAT_CL_RUTA")
					End If
					Starter.skmt.ExecNonQuery($"UPDATE kmt_info set gestion = 0, HORAENT = '${sDate & " " & sTime}' where CAT_CL_CODIGO In (select cuenta from cuentaa) and CAT_CL_RUTA = '${rutaactualizar}'"$)
					Starter.skmt.ExecNonQuery($"DELETE FROM NOVENTA WHERE NV_CLIENTE IN (select cuenta from cuentaa)"$)
					Private c3 As Cursor = Starter.skmt.ExecQuery("SELECT * FROM PEDIDO WHERE PE_CLIENTEOR IN (SELECT CUENTA FROM CUENTAA)")
					If c3.RowCount = 0 Then
						Starter.skmt.ExecNonQuery($"update HIST_VENTAS set HVD_RECHAZO = 0,  HVD_RECHAZOCANT = 0, BCAJAS = BCAJAS_OR, CANTC = CANTC_OR  WHERE HVD_cliente in (Select CUENTA from cuentaa)"$)
						B4XPage_Appear
					Else
						MsgboxAsync("Hay productos que ya se vendieron, no se puede regresar la venta","Atención")
					End If
					Dim textedit As Double = et_abono.Text
					Dim sumaresta As Double = saldopendiente-textedit-saldopendiente1
					Log(NumberFormat2(sumaresta,0,2,2,False))
					If NumberFormat2(sumaresta,0,2,2,False) <> "-.00" Then
						If NumberFormat2(sumaresta,0,2,2,False) <> ".00" Then
							Dim rutaactualizar As String
							Dim rut As Cursor = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
							If rut.RowCount > 0 Then
								rut.Position = 0
								rutaactualizar = rut.GetString("CAT_CL_RUTA")
							End If
							Starter.skmt.ExecNonQuery($"UPDATE kmt_info set gestion = 3, HORAENT = '${sDate & " " & sTime}' where CAT_CL_CODIGO In (select cuenta from cuentaa) and CAT_CL_RUTA = '${rutaactualizar}'"$)
							Starter.skmt.ExecNonQuery($"DELETE FROM NOVENTA WHERE NV_CLIENTE IN (select cuenta from cuentaa)"$)
							Starter.skmt.ExecNonQuery2("INSERT INTO NOVENTA (NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON,NV_FOTO,NV_REPROGRAMAR) VALUES(?,?,?,?,?,?,?,?,?) ", Array As Object (la_cuenta.Text,sDate & sTime, usuario, "PAGO INCOMPLETO","PAGO INCOMPLETO", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,rutaactualizar,0))
							Starter.skmt.ExecNonQuery("update HIST_VENTAS SET HVD_RECHAZO = 1, HVD_RECHAZOCANT = HVD_CANT, HVD_RECHAZOCANTC = CANTC, BCAJAS = 0 , CANTC = 0 WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
							Starter.skmt.ExecNonQuery($"update HIST_VENTAS set HVD_RECHAZO = 2,  HVD_RECHAZOCANT = HVD_RECHAZOCANT  WHERE HVD_PROID = HVD_CODPROMO and HVD_CLIENTE in (Select CUENTA from cuentaa)"$)
							Starter.skmt.ExecNonQuery("DELETE FROM PEDIDO WHERE PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
							d = Starter.skmt.ExecQuery("SELECT RUTAA FROM RUTAA")
							d.Position = 0
							Dim ruta As String = d.GetString("RUTAA")
							d.Close
							d = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
							d.Position = 0
							Dim rutapre As String = d.GetString("CAT_CL_RUTA")
							d.Close
							d = Starter.skmt.ExecQuery("SELECT HVD_FECHA FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
							d.Position = 0
							Dim fechaprev As String = d.GetString("HVD_FECHA")
							d.Close
							d = Starter.skmt.ExecQuery("SELECT CUENTA FROM CUENTAA")
							d.Position = 0
							Starter.skmt.ExecNonQuery2("INSERT INTO REPARTO_GEO (CLIENTE, USUARIO, FECHA_PUNTEO, LATITUD, LONGITUD, ALMACEN, RUTA_REPARTO, RUTA_PREV, FECHA_PREVENTA, MOTIVO, COMENTARIO,TIPO,ENVIO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,0)",Array As String (cuenta, usuario, sDate &" "&sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,B4XPages.MainPage.almacen,ruta,rutapre,fechaprev, "PAGO INCOMPLETO", "PAGO INCOMPLETO","NO ENTREGADO"))
							B4XPages.ShowPage("Principal")
						End If
					End If
				Else
					p_abono.Visible = False
					Starter.skmt.ExecNonQuery($"INSERT INTO ABONOS(a_usuario, a_ruta, a_cliente, a_abono, a_fecha,TIPO_PAGO,a_ticket,a_numpago) VALUES ('${Subs.traeUsuarioDeBD}', '${Subs.traeRuta(Subs.traeCliente)}', '${Subs.traeCliente}' ,'${et_abono.text}', '${Subs.fechaKMT(DateTime.now)}','${itemselect}','${Folio}','${numpago}')"$)
					ToastMessageShow("Abono guardado", False)
					Dim rutaactualizar As String
					Dim rut As Cursor = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
					If rut.RowCount > 0 Then
						rut.Position = 0
						rutaactualizar = rut.GetString("CAT_CL_RUTA")
					End If
					Starter.skmt.ExecNonQuery($"UPDATE kmt_info set gestion = 0, HORAENT = '${sDate & " " & sTime}' where CAT_CL_CODIGO In (select cuenta from cuentaa) and CAT_CL_RUTA = '${rutaactualizar}'"$)
					Starter.skmt.ExecNonQuery($"DELETE FROM NOVENTA WHERE NV_CLIENTE IN (select cuenta from cuentaa)"$)
					Private c3 As Cursor = Starter.skmt.ExecQuery("SELECT * FROM PEDIDO WHERE PE_CLIENTEOR IN (SELECT CUENTA FROM CUENTAA)")
					If c3.RowCount = 0 Then
						Starter.skmt.ExecNonQuery($"update HIST_VENTAS set HVD_RECHAZO = 0,  HVD_RECHAZOCANT = 0, BCAJAS = BCAJAS_OR, CANTC = CANTC_OR  WHERE HVD_cliente in (Select CUENTA from cuentaa)"$)
						B4XPage_Appear
					Else
						MsgboxAsync("Hay productos que ya se vendieron, no se puede regresar la venta","Atención")
					End If
					Dim textedit As Double = et_abono.Text
					Dim sumaresta As Double = saldopendiente-textedit-saldopendiente1
'			Log(NumberFormat2(sumaresta,0,2,2,False))
					If NumberFormat2(sumaresta,0,2,2,False) <> "-.00"  Then
						If NumberFormat2(sumaresta,0,2,2,False) <> ".00" Then
							Dim rutaactualizar As String
							Dim rut As Cursor = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
							If rut.RowCount > 0 Then
								rut.Position = 0
								rutaactualizar = rut.GetString("CAT_CL_RUTA")
							End If
							Starter.skmt.ExecNonQuery($"UPDATE kmt_info set gestion = 3, HORAENT = '${sDate & " " & sTime}' where CAT_CL_CODIGO In (select cuenta from cuentaa) and CAT_CL_RUTA = '${rutaactualizar}'"$)
							Starter.skmt.ExecNonQuery($"DELETE FROM NOVENTA WHERE NV_CLIENTE IN (select cuenta from cuentaa)"$)
							Starter.skmt.ExecNonQuery2("INSERT INTO NOVENTA (NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON,NV_FOTO,NV_REPROGRAMAR) VALUES(?,?,?,?,?,?,?,?,?) ", Array As Object (la_cuenta.Text,sDate & sTime, usuario, "PAGO INCOMPLETO","PAGO INCOMPLETO", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,rutaactualizar,0))
							Starter.skmt.ExecNonQuery("update HIST_VENTAS SET HVD_RECHAZO = 1, HVD_RECHAZOCANT = HVD_CANT, HVD_RECHAZOCANTC = CANTC, BCAJAS = 0 , CANTC = 0 WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
							Starter.skmt.ExecNonQuery($"update HIST_VENTAS set HVD_RECHAZO = 2,  HVD_RECHAZOCANT = HVD_RECHAZOCANT  WHERE HVD_PROID = HVD_CODPROMO and HVD_CLIENTE in (Select CUENTA from cuentaa)"$)
							Starter.skmt.ExecNonQuery("DELETE FROM PEDIDO WHERE PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
							d = Starter.skmt.ExecQuery("SELECT RUTAA FROM RUTAA")
							d.Position = 0
							Dim ruta As String = d.GetString("RUTAA")
							d.Close
							d = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
							d.Position = 0
							Dim rutapre As String = d.GetString("CAT_CL_RUTA")
							d.Close
							d = Starter.skmt.ExecQuery("SELECT HVD_FECHA FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
							d.Position = 0
							Dim fechaprev As String = d.GetString("HVD_FECHA")
							d.Close
							d = Starter.skmt.ExecQuery("SELECT CUENTA FROM CUENTAA")
							d.Position = 0
							Starter.skmt.ExecNonQuery2("INSERT INTO REPARTO_GEO (CLIENTE, USUARIO, FECHA_PUNTEO, LATITUD, LONGITUD, ALMACEN, RUTA_REPARTO, RUTA_PREV, FECHA_PREVENTA, MOTIVO, COMENTARIO,TIPO,ENVIO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,0)",Array As String (cuenta, usuario, sDate &" "&sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,B4XPages.MainPage.almacen,ruta,rutapre,fechaprev, "PAGO INCOMPLETO", "PAGO INCOMPLETO","NO ENTREGADO"))
							B4XPages.ShowPage("Principal")
						End If
					End If

				End If
			End If
		End If
	End If
	

End Sub

Sub imprime_pagare
	c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	ProgressDialogShow("Imprimiendo, un momento ...")
'	Printer1.DisConnect
'	If Not(Printer1.IsConnected) Then
''		Log("Conectando a impresora ...")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada)
'			Sleep(1000)
''			Log("++++++  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect 'Tratamos de reconectar
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	Else
''		Log("conectando 2")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
'			Sleep(1000)
''			Log("******  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	End If

	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	
	TAMANO = 0
	ESPACIO = 28
	BLANCO = " "
	
	Dim telefono As String = ""
	Dim c7 As Cursor = Starter.skmt.ExecQuery("select IFNULL(CAT_CL_TELEFONO,' ') AS CAT_CL_TELEFONO FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	If c7.RowCount > 0 Then
		c7.Position = 0
		telefono = c7.GetString("CAT_CL_TELEFONO")
	End If
	c7.Close
	
	Dim bmp As Bitmap
	bmp.InitializeResize(File.DirAssets, "logo-guna-18.jpg", 192, 192, True) 'ignore
	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
	myimage = Printer1.DitherImage2D(myimage, 128)
	myimage= Printer1.PackImage(myimage)
	Printer1.WriteString(CRLF) ' nudge the printer to show the user something is happening
	Printer1.WriteString(Printer1.REVERSE)
	Printer1.PrintImage(myimage)
	Printer1.WriteString(Printer1.UNREVERSE)
	
'	Dim Ticket As String = 0
'	Dim c6 As Cursor = Starter.skmt.ExecQuery("select distinct HVD_NUM_TICKET FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'	If c6.RowCount > 0 Then
'		c6.Position = 0
'		Ticket = c6.GetString("HVD_NUM_TICKET")
'	End If
'	c6.Close
	DateTime.DateFormat = "dd/MM/yyyy"
	DateTime.TimeFormat = "HH:mm:ss"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  CRLF)
	Printer1.WriteString(sDate &  CRLF)
	Printer1.WriteString(sTime &  CRLF)
	Printer1.WriteString("Reparto:" & usuario &  CRLF)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  CRLF)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  CRLF)
	Printer1.WriteString("Calle: " & la_Calle.Text &  CRLF)
	Printer1.WriteString("Colonia: " & la_col.Text &  CRLF)
	Printer1.WriteString("Telefono: " & telefono &  CRLF)
	Dim Ticket As String = 0
	Dim c6 As Cursor = Starter.skmt.ExecQuery("select distinct HVD_NUM_TICKET FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND HVD_PRONOMBRE <> 'Cobranza Pendiente'")
	If c6.RowCount > 0 Then
		For k = 0 To c6.RowCount -1
			c6.Position = k
			Ticket = c6.GetString("HVD_NUM_TICKET")
			Printer1.WriteString("Num. Ticket " & (k +1)&": " & Ticket &  CRLF)
		Next
	End If
	c6.Close
	Printer1.WriteString("Fecha: " &  sDate &" " & sTime &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	c = Starter.skmt.ExecQuery("SELECT * FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If c.RowCount > 0 Then
		Printer1.WriteString("------------PAGARE------------" &  CRLF)
		Printer1.WriteString("" &  CRLF)
		Printer1.WriteString("Pagare por los articulos" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		' aqui es donde esta el pedo de julieta de los descuentos quitar el precio2 pero meter un if para saber si es ruta especial o es normal o que show.
		s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, HVD_CANT, length(HVD_CANT) as L_CANT, HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID, HVD_CODPROMO,IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) order by  HVD_PROID"$)
		If S.RowCount>0 Then
			For i=0 To S.RowCount -1
				S.Position=i
				Log(s.GetString("HVD_RECHAZO"))
				If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
					If s.GetString("HVD_CODPROMO") = Subs.traeAlmacen Then
						Printer1.Justify = 0
						Printer1.WriteString((s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") ) &" "&s.GetString("HVD_PRONOMBRE") &  CRLF)
'						Dim punit As String = NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
'						TAMANO = punit.Length + TAMANO
						'
						''						Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
'						Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
'						TAMANO = ptot.Length + TAMANO
'	
'						ESPACIO = (ESPACIO - TAMANO)/2
						''						Log(ESPACIO)
'						For E=0 To ESPACIO -1
'							BLANCO = " " & BLANCO
'						Next
'						Printer1.Justify = 0
'						Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
'						Printer1.Justify = 1
'						Printer1.WriteString( punit & BLANCO)
'						Printer1.Justify = 2
'						Printer1.WriteString( ptot &  CRLF )
'						TAMANO = 0
'						ESPACIO = 29
'						BLANCO = " "
					Else If s.GetString("HVD_RECHAZO") = 1 Then
						Printer1.Justify = 0
						Printer1.WriteString((s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) &" "&s.GetString("HVD_PRONOMBRE") &  CRLF)
						
'						Private vc5 As Cursor = Starter.skmt.ExecQuery($"select iFNULL(CAT_GP_PRECIO,0) AS CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${s.GetString("HVD_PROID")}'"$)
'						vc5.Position = 0
'						Dim punit As String = NumberFormat2((vc5.GetString("CAT_GP_PRECIO")),0,2,2,False)
'						TAMANO = punit.Length + TAMANO
'						vc5.Close
'				
'						Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
'						TAMANO = ptot.Length + TAMANO
'	
'						ESPACIO = (ESPACIO - TAMANO)/2
						''						Log(ESPACIO)
'						For E=0 To ESPACIO -1
'							BLANCO = " " & BLANCO
'						Next
'						Printer1.Justify = 0
'						Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
'						Printer1.Justify = 1
'						Printer1.WriteString( punit & BLANCO)
'						Printer1.Justify = 2
'						Printer1.WriteString(ptot&  CRLF )
'						TAMANO = 0
'						ESPACIO = 29
'						BLANCO = " "
						Printer1.Justify = 0
					End If
				End If
			Next
		End If
	End If
	Printer1.Justify = 0
	s.Close
	Printer1.WriteString(" " &  CRLF)
	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, HVD_CANT, length(HVD_CANT) as L_CANT, HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID, HVD_CODPROMO,IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_RECHAZO = 0 AND HVD_CODPROMO <> '${Subs.traeAlmacen}' order by  HVD_CODPROMO, ESPROMO DESC, HVD_PROID"$)
	If S.RowCount>0 Then
		Printer1.WriteString("-------PROMOS ENTREGA--------" &  CRLF)
		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		For i=0 To S.RowCount -1
			S.Position=i
			If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
				If s.GetString("HVD_CODPROMO") <> Subs.traeAlmacen Then
					Printer1.Justify = 0
					If s.GetString("HVD_CODPROMO") = s.GetString("HVD_PROID") Then
'						Printer1.WriteString("* "&s.GetString("HVD_PRONOMBRE") &  CRLF)
					Else
						If s.GetString("HVD_PRONOMBRE") <> "Cobranza Pendiente" Then
'							Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
							Printer1.WriteString((s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") ) &" "&s.GetString("HVD_PRONOMBRE") &  CRLF)
						End If
					End If
'					Dim punit As String =NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
'					TAMANO = punit.Length + TAMANO
'					Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
'					TAMANO = ptot.Length + TAMANO
'					ESPACIO = (ESPACIO - TAMANO)/2
'					Log(ESPACIO)
'					For E=0 To ESPACIO -1
'						BLANCO = " " & BLANCO
'					Next
'					Printer1.Justify = 0
'					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
'					Printer1.Justify = 1
'					Printer1.WriteString( punit & BLANCO)
'					Printer1.Justify = 2
'					Printer1.WriteString(ptot &  CRLF )
'					TAMANO = 0
'					ESPACIO = 29
'					BLANCO = " "
					Printer1.Justify = 0
				Else
				End If
			End If
		Next
	End If

	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("Por monto de $" &l_total.Text&  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("Debo(mos) y pagare(mos) incon" &  CRLF)
	Printer1.WriteString("dicionalmente en _____________" &  CRLF)
	Printer1.WriteString("o en el lugar donde se me " &  CRLF)
	Printer1.WriteString("requiera por el presente pagare" &  CRLF)
	Printer1.WriteString("a GUNA la cantidad de $"&l_total.Text &  CRLF)
	Printer1.WriteString("valor recibido a entera " &  CRLF)
	Printer1.WriteString("satisfaccion. La falta de pago" &  CRLF)
	Printer1.WriteString("a la fecha indicada causara " &  CRLF)
	Printer1.WriteString("intereses moratorios a razon " &  CRLF)
	Printer1.WriteString("de ______% mensual a la fecha." &  CRLF)
	Printer1.WriteString("" &  CRLF)
	Printer1.WriteString("" &  CRLF)
	Printer1.WriteString("            Recibi            " &  CRLF)
	Printer1.WriteString("" &  CRLF)
	Printer1.WriteString("" &  CRLF)
	Printer1.WriteString("______________________________" &  CRLF)
	
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	DateTime.DateFormat = "ddMMyyyy"
	sDate=DateTime.Date(DateTime.Now)
'	Printer1.WriteString("JHGHGH " &  CRLF)
	Printer1.WriteBarCode("I",Ticket&sDate)
	
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Sleep(1000)
	Printer1.DisConnect
	ProgressDialogHide
	If banderaimp = 1 Then
		Msgbox2Async("Deseas imprimir de nuevo el PAGARE?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
		Wait For Msgbox_Result (resultado As Int)
		If resultado = DialogResponse.POSITIVE Then
			imprime_pagare
		Else
			If banderaabono = 1 Then
				imprime_abonopagare2
			Else
				Guardado
			End If
		End If
'	printer.Flush
		'	printer.Close
	Else If banderaimp = 0 Then
		Msgbox2Async("Deseas imprimir de nuevo el PAGARE?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
		Wait For Msgbox_Result (resultado As Int)
		If resultado = DialogResponse.POSITIVE Then
			imprime_pagare
		End If
	End If
'	Guardado
End Sub

Private Sub b_cancel_pagare_Click
	tipo_abonox = "abono"
'	Msgbox2Async($"¿Que deseas realizar?"$,"Atención", "","", "Abono pagare", Null, True)
'	Wait For Msgbox_Result (resultado As Int)
'	If resultado = DialogResponse.POSITIVE Then
'		Msgbox2Async($"¿Seguro que quieres cancelar el pagare con monto de $${l_total.Text} para este cliente?"$,"Atención", "Aceptar","Cancelar", "", Null, True)
'		Wait For Msgbox_Result (resultado As Int)
'		If resultado = DialogResponse.POSITIVE Then
'			Starter.skmt.ExecNonQuery("update PAGARES SET PA_CANCELADO = 2 WHERE PA_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'			imprime_cancelarpagare
'			
'			d = Starter.skmt.ExecQuery("SELECT RUTAA FROM RUTAA")
'			d.Position = 0
'			Dim ruta As String = d.GetString("RUTAA")
'			d.Close
'			
'			Dim g5 As Cursor = Starter.skmt.ExecQuery("SELECT SUM(HVD_COSTO_TOT) as HVD_COSTO_TOT FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'			g5.Position = 0
'			Dim totaltotal As String = g5.GetString("HVD_COSTO_TOT")
'			g5.Close
'			If totaltotal = l_total.Text.Replace(",","") Then
'				Dim entregatotaloparial As String = "ENTREGA TOTAL"
'			Else
'				Dim entregatotaloparial As String = "ENTREGA PARCIAL"
'			End If
'			Dim cmd As DBCommand
'			cmd.Initialize
'			cmd.Name = "UPDATE_ACTUAL_GEO_GUNA_VN"
''			cmd.Parameters = Array As String(l_total.Text.Replace(",",""),"0", "",B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,"","",usuario,ruta,"ENTREGA", entregatotaloparial,"EFECTIVO", distance, L_CANT.text,la_cuenta.Text,fechaprev,almacen,Subs.traerUTAPREV)
'			cmd.Parameters = Array As String(l_total.Text.Replace(",",""),"0", "",B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,"","",usuario,ruta,"ENTREGA", entregatotaloparial,"EFECTIVO", distance, L_CANT.text,la_cuenta.Text,fechaprev,almacen,Subs.traerUTAPREV)
'			Starter.skmt.ExecNonQuery2("INSERT INTO HIST_REPARTO_GEO(HIST_RG_MONTO , HIST_RG_CREDITO , HIST_RG_MONTO_CREDITO , HIST_RG_LAT , HIST_RG_LONG , HIST_RG_RECHAZO , HIST_RG_MOTIVO , HIST_RG_USUARIO_ENTREGO , HIST_RG_RUTA_REP , HIST_RG_ESTATUS_ENTREGA , HIST_RG_COMENTARIO_ENTREGA , HIST_RG_FORMA_PAGO , HIST_RG_GEOCERCA_MTS , HIST_RG_NO_ART , HIST_RG_CLIENTE , HIST_RG_FECHA , HIST_RG_ALMACEN , HIST_RG_RUTA_PRE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object(l_total.Text.Replace(",",""),"0", "",B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,"","",usuario,ruta,"ENTREGA", entregatotaloparial,"EFECTIVO", distance, L_CANT.text,la_cuenta.Text,fechaprev,almacen,Subs.traerUTAPREV))
'			reqManager.ExecuteCommand(cmd, "up_geo")
'			banderaimp = 1
'		End If
'	Else If resultado = DialogResponse.NEGATIVE Then
		
		h = Starter.skmt.ExecQuery("SELECT CUENTA from CUENTAA")
		h.Position = 0
		Log(h.GetString("CUENTA"))
		j = Starter.skmt.ExecQuery2("SELECT a_abono FROM ABONOS WHERE a_cliente = ? and a_tipoabono is null", Array As String(h.GetString("CUENTA")))
		j.position = 0
		Log(j.RowCount)
		If j.RowCount = 0 Then
			p_abono.Visible = True
			et_abono.text = ""
			Dim total As Double = 0
			f = Starter.skmt.ExecQuery("SELECT CUENTA FROM CUENTAA")
			f.Position = 0
		d = Starter.skmt.ExecQuery2("SELECT distinct PA_TICKET, PA_MONTO,PA_CAPTURA FROM PAGARES WHERE PA_CLIENTE = ? AND PA_CANCELADO IS NULL ORDER BY PA_CAPTURA", Array As String (f.GetString("CUENTA")))
			clv_abonos.Clear
			For i = 0 To d.RowCount - 1
				d.Position = i
			
			Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) AND a_ticket = ?", Array As String(d.GetString("PA_TICKET")))
			Log(Folio)
			y.position = 0
			
			clv_abonos.Add(CreateListItem(d.GetString("PA_TICKET"),"$ " & NumberFormat2((d.GetString("PA_MONTO")-y.GetString("a_abono")),0,2,2,False),d.GetString("PA_CAPTURA")),i)
			
		
				
			total = total + d.GetString("PA_MONTO")
			Log(total)
		Next
			d.Close
			d = Starter.skmt.ExecQuery2("SELECT  a_abono,a_fecha FROM ABONOS WHERE a_cliente = ? and a_tipoabono is not null ORDER BY a_fecha", Array As String (f.GetString("CUENTA")))
			If d.RowCount > 0 Then
				For i = 0 To d.RowCount - 1
					d.Position = i
				clv_abonos.Add(CreateListItem("ABONO","$ " & d.GetString("a_abono"),d.GetString("a_fecha")),i)
					total = total - d.GetString("a_abono")
					Log(total)
				Next
			End If
			l_montoabonostotal.Text = NumberFormat2(total,0,2,2,False)
			d.Close
			f.Close
		Else If j.RowCount > 0 Then
			p_abono.Visible = True
			et_abono.text = ""
			Dim total As Double = 0
			f = Starter.skmt.ExecQuery("SELECT CUENTA FROM CUENTAA")
			f.Position = 0
		d = Starter.skmt.ExecQuery2("SELECT distinct PA_TICKET, PA_MONTO,PA_CAPTURA FROM PAGARES WHERE PA_CLIENTE = ? AND PA_CANCELADO IS NULL ORDER BY PA_CAPTURA", Array As String (f.GetString("CUENTA")))
			clv_abonos.Clear
			For i = 0 To d.RowCount - 1
			d.Position = i
			Dim y As Cursor = Starter.skmt.ExecQuery2("SELECT IFNULL(SUM(a_abono),0) AS a_abono FROM ABONOS WHERE a_cliente IN (SELECT CUENTA FROM CUENTAA) AND a_ticket = ?", Array As String(d.GetString("PA_TICKET")))
			Log(Folio)
			y.position = 0
			
			clv_abonos.Add(CreateListItem(d.GetString("PA_TICKET"),"$ " &NumberFormat2((d.GetString("PA_MONTO")-y.GetString("a_abono")),0,2,2,False),d.GetString("PA_CAPTURA")),i)
				
				total = total + d.GetString("PA_MONTO").Replace(",","")
				Log(total)
			Next
			d.Close
		d = Starter.skmt.ExecQuery2("SELECT  a_abono,a_fecha FROM ABONOS WHERE a_cliente = ? and a_tipoabono is not null ORDER BY a_fecha", Array As String (f.GetString("CUENTA")))
			If d.RowCount > 0 Then
				For i = 0 To d.RowCount - 1
					d.Position = i
				clv_abonos.Add(CreateListItem("ABONO","$ " & d.GetString("a_abono"),d.GetString("a_fecha")),i)
					total = total - d.GetString("a_abono")
					Log(total)
				Next
			End If
			l_montoabonostotal.Text = NumberFormat2(total,0,2,2,False)
			d.Close
			f.Close
'		MsgboxAsync("Este cliente ya tiene un pago capturado","Atención")
		End If
		h.Close
		j.Close
		
'	End If
	

	
	
End Sub

Sub imprime_cancelarpagare
	c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	ProgressDialogShow("Imprimiendo, un momento ...")
'	Printer1.DisConnect
'	If Not(Printer1.IsConnected) Then
''		Log("Conectando a impresora ...")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada)
'			Sleep(1000)
''			Log("++++++  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect 'Tratamos de reconectar
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	Else
''		Log("conectando 2")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
'			Sleep(1000)
''			Log("******  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	End If

	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	
	TAMANO = 0
	ESPACIO = 28
	BLANCO = " "
	Dim telefono As String = ""
	Dim c7 As Cursor = Starter.skmt.ExecQuery("select IFNULL(CAT_CL_TELEFONO,' ') AS CAT_CL_TELEFONO FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	If c7.RowCount > 0 Then
		c7.Position = 0
		telefono = c7.GetString("CAT_CL_TELEFONO")
	End If
	c7.Close
	Dim bmp As Bitmap
	bmp.InitializeResize(File.DirAssets, "logo-guna-18.jpg", 192, 192, True) 'ignore
	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
	myimage = Printer1.DitherImage2D(myimage, 128)
	myimage= Printer1.PackImage(myimage)
	Printer1.WriteString(CRLF) ' nudge the printer to show the user something is happening
	Printer1.WriteString(Printer1.REVERSE)
	Printer1.PrintImage(myimage)
	Printer1.WriteString(Printer1.UNREVERSE)
	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  CRLF)
	Printer1.WriteString(sDate &  CRLF)
	Printer1.WriteString(sTime &  CRLF)
	Printer1.WriteString("Reparto:" & usuario &  CRLF)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  CRLF)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  CRLF)
	Printer1.WriteString("Calle: " & la_Calle.Text &  CRLF)
	Printer1.WriteString("Colonia: " & la_col.Text &  CRLF)
	Printer1.WriteString("Telefono: " & telefono &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("-----CANCELACION DE PAGARE----" &  CRLF)
	Printer1.WriteString("" &  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString("Se cancela el pagare " &  CRLF)
	Printer1.WriteString("Por monto de $" &l_total.Text&  CRLF)
	Printer1.WriteString("por el cual se pagara el " &  CRLF)
	Printer1.WriteString("total en efectivo" &  CRLF)
'	Printer1.WriteString("dicionalmente en _____________" &  CRLF)
'	Printer1.WriteString("o en el lugar donde se me " &  CRLF)
'	Printer1.WriteString("requiera por el presente pagare" &  CRLF)
'	Printer1.WriteString("a GUNA la cantidad de $"&l_total.Text &  CRLF)
'	Printer1.WriteString("valor recibido a entera " &  CRLF)
'	Printer1.WriteString("satisfacciOn. La falta de pago" &  CRLF)
'	Printer1.WriteString("a la fecha indicada causara " &  CRLF)
'	Printer1.WriteString("intereses moratorios a razOn " &  CRLF)
'	Printer1.WriteString("de ______% mensual a la fecha." &  CRLF)
	Printer1.WriteString("" &  CRLF)
	Printer1.WriteString("" &  CRLF)
	Printer1.WriteString("            Recibi            " &  CRLF)
	Printer1.WriteString("" &  CRLF)
	Printer1.WriteString("" &  CRLF)
	Printer1.WriteString("______________________________" &  CRLF)
	
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Sleep(1000)
	Printer1.DisConnect
	ProgressDialogHide
	If banderaimp = 1 Then
		Msgbox2Async("Deseas imprimir de nuevo el PAGARE?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
		Wait For Msgbox_Result (resultado As Int)
		If resultado = DialogResponse.POSITIVE Then
			imprime_cancelarpagare
		Else
			Guardado
		End If
'	printer.Flush
		'	printer.Close
	Else If banderaimp = 0 Then
		Msgbox2Async("Deseas imprimir de nuevo el PAGARE?", "ATENCION","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
		Wait For Msgbox_Result (resultado As Int)
		If resultado = DialogResponse.POSITIVE Then
			imprime_cancelarpagare
		End If
	End If
'	Guardado
End Sub

Private Sub CrearQR(NOTA2 As String)
'	Private texto As String = $"https://wa.me/5215637241894?text=PAGARE ${NOTA2}"$ 'Bow 2.0 G
	Private texto As String = $"https://wa.me/5215611769317?text=PAGARE_${NOTA2}"$ 'Bow2024
	i_qr.Clear
	If texto.Length>0 Then
		i_qr.SetBitmap(qr.Create(texto))
		Log("QR Creado ->"&texto)
	End If
End Sub

Private Sub b_confirmar_Click
	ProgressDialogShow("Un momento por favor!!")
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "selectPagareConfirmado_Demo"
'	cmd.Parameters = Array As Object(Subs.traeCliente, NOTA)
	cmd.Parameters = Array As Object(NOTA)
	reqManager.ExecuteQuery(cmd, 0, $"pagareConfirmado_${NOTA}"$)
End Sub

Private Sub p_transPagare2_Click
	
End Sub

Private Sub b_cerrarqr_Click
	i_qr.Clear
	p_transPagare2.Visible = False
End Sub

Private Sub b_imprimesegun_Click
	
	Dim pagacheca As Cursor = Starter.skmt.ExecQuery("SELECT * FROM PAGARES WHERE PA_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	
	If pagacheca.RowCount > 0 Then
		Tipoentrega = "CREDITO"
	Else
		Tipoentrega = "CONTADO"
	End If
	
	c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	ProgressDialogShow("Imprimiendo, un momento ...")
'	Printer1.DisConnect
'	If Not(Printer1.IsConnected) Then
''		Log("Conectando a impresora ...")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada)
'			Sleep(1000)
''			Log("++++++  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect 'Tratamos de reconectar
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	Else
''		Log("conectando 2")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
'			Sleep(1000)
''			Log("******  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	End If

	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	
	TAMANO = 0
	ESPACIO = 28
	BLANCO = " "
	Dim bmp As Bitmap
	bmp.InitializeResize(File.DirAssets, "logo-guna-18.jpg", 192, 192, True) 'ignore
	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
	myimage = Printer1.DitherImage2D(myimage, 128)
	myimage= Printer1.PackImage(myimage)
	Printer1.WriteString(CRLF) ' nudge the printer to show the user something is happening
	Printer1.WriteString(Printer1.REVERSE)
	Printer1.PrintImage(myimage)
	Printer1.WriteString(Printer1.UNREVERSE)
'	Dim Ticket As String = 0
'	Dim c6 As Cursor = Starter.skmt.ExecQuery("select distinct HVD_NUM_TICKET FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
'	If c6.RowCount > 0 Then
'		c6.Position = 0
'		Ticket = c6.GetString("HVD_NUM_TICKET")
'	End If
'	c6.Close
	Dim telefono As String = ""
	Dim c7 As Cursor = Starter.skmt.ExecQuery("select IFNULL(CAT_CL_TELEFONO,' ') AS CAT_CL_TELEFONO FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
	If c7.RowCount > 0 Then
		c7.Position = 0
		telefono = c7.GetString("CAT_CL_TELEFONO")
	End If
	c7.Close
	
	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  CRLF)
	Printer1.WriteString(sDate &  CRLF)
	Printer1.WriteString(sTime &  CRLF)
	Printer1.WriteString("Reparto:" & usuario &  CRLF)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  CRLF)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  CRLF)
	Printer1.WriteString("Calle: " & la_Calle.Text &  CRLF)
	Printer1.WriteString("Colonia: " & la_col.Text &  CRLF)
	Printer1.WriteString("Telefono: " & telefono &  CRLF)
	
	Dim Ticket As String = 0
	Dim c6 As Cursor = Starter.skmt.ExecQuery("select distinct HVD_NUM_TICKET FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If c6.RowCount > 0 Then
		For k = 0 To c6.RowCount -1
			c6.Position = k
			Ticket = c6.GetString("HVD_NUM_TICKET")
			Printer1.WriteString("Num. Ticket " & (k +1)&": " & Ticket &  CRLF)
		Next
	End If
	c6.Close

	Printer1.WriteString(" " &  CRLF)
	c = Starter.skmt.ExecQuery("SELECT * FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	
	
	Dim cobranza As Cursor = Starter.skmt.ExecQuery("SELECT * FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA) and HVD_PRONOMBRE = 'Cobranza Pendiente'")
	Dim restacobranza As Int = 0
	If cobranza.RowCount > 0 Then
		restacobranza = 1
	End If
	If c.RowCount > 0 Then
		' aqui es donde esta el pedo de julieta de los descuentos quitar el precio2 pero meter un if para saber si es ruta especial o es normal o que show.  ''CAT_TIPO_BONIFICACIONES
'		s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, HVD_CANT, length(HVD_CANT) as L_CANT, HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID, HVD_CODPROMO,IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) and (HVD_CODPROMO <> 'MI RETO' or HVD_CODPROMO <> 'MI RETO' or HVD_CODPROMO <> 'MI RETO') AND (HVD_COSTO_TOT/HVD_CANT) > 0.01 order by  HVD_PROID"$)
		s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) and (HVD_CODPROMO <> 'MIRETO' or HVD_CODPROMO <> 'SOCIOBAT' or HVD_CODPROMO <> 'CONECTADOS')  AND (HVD_COSTO_TOT/HVD_CANT) > 0.01 GROUP by  HVD_PROID"$)
		If S.RowCount>0 Then
			Printer1.WriteString("-------ENTREGA A "& Tipoentrega &"------" &  CRLF)
'		Printer1.WriteString("--------------------------------" &  CRLF)
			Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
			Printer1.WriteString("------------------------------" &  CRLF)
			For i=0 To S.RowCount -1
				S.Position=i
				Log(s.GetString("HVD_RECHAZO"))
				If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
					If s.GetInt("HVD_RECHAZO") = 0 Then
						Printer1.Justify = 0
						Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
						Dim punit As String = NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
						TAMANO = punit.Length + TAMANO
'						Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
						Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
						TAMANO = ptot.Length + TAMANO
						ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
						For E=0 To ESPACIO -1
							BLANCO = " " & BLANCO
						Next
						Printer1.Justify = 0
						Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
						Printer1.Justify = 1
						Printer1.WriteString( punit & BLANCO)
						Printer1.Justify = 2
						Printer1.WriteString( ptot &  CRLF )
						TAMANO = 0
						ESPACIO = 28
						BLANCO = " "
					Else If s.GetInt("HVD_RECHAZO") > 0 Then
						Printer1.Justify = 0
						Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
						Private vc5 As Cursor = Starter.skmt.ExecQuery($"select iFNULL(CAT_GP_PRECIO,0) AS CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${s.GetString("HVD_PROID")}'"$)
						vc5.Position = 0
						Dim punit As String = NumberFormat2((vc5.GetString("CAT_GP_PRECIO")),0,2,2,False)
						TAMANO = punit.Length + TAMANO
						vc5.Close
						Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
						TAMANO = ptot.Length + TAMANO
						ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
						For E=0 To ESPACIO -1
							BLANCO = " " & BLANCO
						Next
						Printer1.Justify = 0
						Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
						Printer1.Justify = 1
						Printer1.WriteString( punit & BLANCO)
						Printer1.Justify = 2
						Printer1.WriteString(ptot&  CRLF )
						TAMANO = 0
						ESPACIO = 28
						BLANCO = " "
						Printer1.Justify = 0
					End If
				End If
			Next
		End If
	End If
	Printer1.Justify = 0
	s.Close
	Printer1.WriteString(" " &  CRLF)
	
	
'	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, HVD_CANT, length(HVD_CANT) as L_CANT, HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID, HVD_CODPROMO,IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_RECHAZO = 0 AND HVD_CODPROMO <> '${Subs.traeAlmacen}' order by  HVD_CODPROMO, ESPROMO DESC, HVD_PROID"$)
	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) and (HVD_CODPROMO <> 'MIRETO' or HVD_CODPROMO <> 'SOCIOBAT' or HVD_CODPROMO <> 'CONECTADOS')  AND (HVD_COSTO_TOT/HVD_CANT) = 0.01 GROUP by  HVD_PROID"$)
	

	If S.RowCount>0 Then
		Printer1.WriteString("------- BONIFIACIONES --------" &  CRLF)
		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		For i=0 To S.RowCount -1
			S.Position=i
			
				
			
			If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
'				If s.GetString("HVD_CODPROMO") <> Subs.traeAlmacen Then
				Printer1.Justify = 0
'					If s.GetString("HVD_CODPROMO") = s.GetString("HVD_PROID") Then
				''						Printer1.WriteString("* "&s.GetString("HVD_PRONOMBRE") &  CRLF)
'						
'					Else
						
				Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
						
				Dim punit As String =NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
				TAMANO = punit.Length + TAMANO
				Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
				TAMANO = ptot.Length + TAMANO
				ESPACIO = (ESPACIO - TAMANO)/2
				Log(ESPACIO)
				For E=0 To ESPACIO -1
					BLANCO = " " & BLANCO
				Next
				Printer1.Justify = 0
				Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
				Printer1.Justify = 1
				Printer1.WriteString( punit & BLANCO)
				Printer1.Justify = 2
				Printer1.WriteString(ptot &  CRLF )
				TAMANO = 0
				ESPACIO = 29
				BLANCO = " "
				Printer1.Justify = 0
'					End If
'				Else
'				End If
			End If
			
		Next
	End If
	
'	Printer1.WriteString(" " &  CRLF)
'	s=Starter.skmt.ExecQuery($"select PE_PRONOMBRE, PE_CANT, length(PE_CANT) as L_CANT, PE_COSTO_TOT, length(PE_COSTO_TOT) as L_COSTOU,PE_PROID FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) order BY PE_PROID"$)
	'
'	If S.RowCount>0 Then
'		Printer1.WriteString("-----------VENTA------------" &  CRLF)
'		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
'		Printer1.WriteString("------------------------------" &  CRLF)
'		
'		For i=0 To S.RowCount -1
'			S.Position=i
	'
'			Printer1.Justify = 0
'			Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  CRLF)
'			Dim punit As String =NumberFormat2( (s.GETSTRING("PE_COSTO_TOT")/s.GetString("PE_CANT")),0,2,2,False)
'			TAMANO = punit.Length + TAMANO
'			Private ptot As String = NumberFormat2((punit*s.GetString("PE_CANT")),0,2,2,False)
'			TAMANO = ptot.Length + TAMANO
'			ESPACIO = (ESPACIO - TAMANO)/2
'			Log(ESPACIO)
'			For E=0 To ESPACIO -1
'				BLANCO = " " & BLANCO
'			Next
'			Printer1.Justify = 0
'			Printer1.WriteString( s.GetString("PE_CANT") & BLANCO)
'			Printer1.Justify = 1
'			Printer1.WriteString( punit & BLANCO)
'			Printer1.Justify = 2
'			Printer1.WriteString(ptot &  CRLF )
'			TAMANO = 0
'			ESPACIO = 29
'			BLANCO = " "
'			Printer1.Justify = 0
'		Next
'	End If
	Printer1.WriteString(" " &  CRLF)
	
	
	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_CODPROMO = 'MIRETO' GROUP by  HVD_PROID"$)
	If S.RowCount>0 Then
		Printer1.WriteString("----------- MI RETO ------------" &  CRLF)
'		Printer1.WriteString("--------------------------------" &  CRLF)
		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		For i=0 To S.RowCount -1
			S.Position=i
			Log(s.GetString("HVD_RECHAZO"))
			If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
				If s.GetInt("HVD_RECHAZO") = 0 Then
					Printer1.Justify = 0
					Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
					Dim punit As String = NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
'						Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
					Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString( ptot &  CRLF )
					TAMANO = 0
					ESPACIO = 28
					BLANCO = " "
				Else If s.GetInt("HVD_RECHAZO") > 0 Then
					Printer1.Justify = 0
					Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
					Private vc5 As Cursor = Starter.skmt.ExecQuery($"select iFNULL(CAT_GP_PRECIO,0) AS CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${s.GetString("HVD_PROID")}'"$)
					vc5.Position = 0
					Dim punit As String = NumberFormat2((vc5.GetString("CAT_GP_PRECIO")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
					vc5.Close
					Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString(ptot&  CRLF )
					TAMANO = 0
					ESPACIO = 28
					BLANCO = " "
					Printer1.Justify = 0
				End If
			End If
		Next
	End If
	Printer1.Justify = 0
	s.Close
	
	Printer1.WriteString(" " &  CRLF)
	
	
	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_CODPROMO = 'CONECTADOS' GROUP by  HVD_PROID"$)
'	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_CODPROMO = 'SOCIOBAT' GROUP by  HVD_PROID"$)
	If S.RowCount>0 Then
		Printer1.WriteString("---------- CONECTADOS ----------" &  CRLF)
'		Printer1.WriteString("--------------------------------" &  CRLF)
		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		For i=0 To S.RowCount -1
			S.Position=i
			Log(s.GetString("HVD_RECHAZO"))
			If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
				If s.GetInt("HVD_RECHAZO") = 0 Then
					Printer1.Justify = 0
					Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
					Dim punit As String = NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
'						Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
					Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString( ptot &  CRLF )
					TAMANO = 0
					ESPACIO = 28
					BLANCO = " "
				Else If s.GetInt("HVD_RECHAZO") > 0 Then
					Printer1.Justify = 0
					Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
					Private vc5 As Cursor = Starter.skmt.ExecQuery($"select iFNULL(CAT_GP_PRECIO,0) AS CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${s.GetString("HVD_PROID")}'"$)
					vc5.Position = 0
					Dim punit As String = NumberFormat2((vc5.GetString("CAT_GP_PRECIO")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
					vc5.Close
					Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString(ptot&  CRLF )
					TAMANO = 0
					ESPACIO = 28
					BLANCO = " "
					Printer1.Justify = 0
				End If
			End If
		Next
	End If
	Printer1.Justify = 0
	s.Close
	
'	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_CODPROMO = 'CONECTADOS' GROUP by  HVD_PROID"$)
	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, sum(HVD_CANT) as HVD_CANT, length(HVD_CANT) as L_CANT, sum(HVD_COSTO_TOT) as HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID,SUM(IFNULL(HVD_RECHAZOCANT,0)) AS HVD_RECHAZOCANT, SUM(HVD_RECHAZO) AS HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_CODPROMO = 'SOCIOBAT' GROUP by  HVD_PROID"$)
	If S.RowCount>0 Then
		Printer1.WriteString("---------- SOCIO BAT ----------" &  CRLF)
'		Printer1.WriteString("--------------------------------" &  CRLF)
		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		For i=0 To S.RowCount -1
			S.Position=i
			Log(s.GetString("HVD_RECHAZO"))
			If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
				If s.GetInt("HVD_RECHAZO") = 0 Then
					Printer1.Justify = 0
					Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
					Dim punit As String = NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
'						Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
					Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString( ptot &  CRLF )
					TAMANO = 0
					ESPACIO = 28
					BLANCO = " "
				Else If s.GetInt("HVD_RECHAZO") > 0 Then
					Printer1.Justify = 0
					Printer1.WriteString(s.GetString("HVD_PRONOMBRE") &  CRLF)
					Private vc5 As Cursor = Starter.skmt.ExecQuery($"select iFNULL(CAT_GP_PRECIO,0) AS CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${s.GetString("HVD_PROID")}'"$)
					vc5.Position = 0
					Dim punit As String = NumberFormat2((vc5.GetString("CAT_GP_PRECIO")),0,2,2,False)
					TAMANO = punit.Length + TAMANO
					vc5.Close
					Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
					TAMANO = ptot.Length + TAMANO
					ESPACIO = (ESPACIO - TAMANO)/2
'						Log(ESPACIO)
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.Justify = 0
					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
					Printer1.Justify = 1
					Printer1.WriteString( punit & BLANCO)
					Printer1.Justify = 2
					Printer1.WriteString(ptot&  CRLF )
					TAMANO = 0
					ESPACIO = 28
					BLANCO = " "
					Printer1.Justify = 0
				End If
			End If
		Next
	End If
	Printer1.Justify = 0
	s.Close

	
	Printer1.WriteString(" " &  CRLF)
	
	
	
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString("Total Articulos:   " & (L_CANT.Text.Replace(",","") -restacobranza) &  CRLF)
	Printer1.WriteString("Total:   $" & l_total.Text)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString("----ESTE TICKET NO ES UN -----" &  CRLF)
	Printer1.WriteString("--COMPROBANTE FISCAL, SOLO ES-" &  CRLF)
	Printer1.WriteString("--------INFORMATIVO-----------" &  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Sleep(1000)
	Printer1.DisConnect
	ProgressDialogHide
End Sub



Private Sub l_telefono_LongClick As ResumableSub
	Dim numeroTel As String = l_telefono.Text
    
	numeroTel = numeroTel.Replace(" ", "").Replace("-", "").Replace("(", "").Replace(")", "")
    
	If numeroTel.Length > 0 Then
		Dim Intent1 As Intent
		Intent1.Initialize("android.intent.action.DIAL", "tel:" & numeroTel)
		StartActivity(Intent1)
	Else
		ToastMessageShow("Número no válido", False)
	End If
    
	Return True
End Sub

Private Sub HIST_LongClick
	c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	ProgressDialogShow("Imprimiendo, un momento ...")
'	Printer1.DisConnect
'	If Not(Printer1.IsConnected) Then
	''		Log("Conectando a impresora ...")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada)
'			Sleep(1000)
	''			Log("++++++  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect 'Tratamos de reconectar
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	Else
	''		Log("conectando 2")
'		Printer1.Connect
'		Private cont As Int = 0
'		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
'			Sleep(1000)
	''			Log("******  " & cont)
'			cont = cont + 1
'			If cont = 2 Then Printer1.Connect
'			If cont > 3 Then impresoraConectada = True
'		Loop
'		Sleep(500)
'		impresoraConectada = False
'	End If

	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	TAMANO = 0
	ESPACIO = 28
	BLANCO = " "
	Dim Ticket As String = 0
	Dim c6 As Cursor = Starter.skmt.ExecQuery("select distinct HVD_NUM_TICKET FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If c6.RowCount > 0 Then
		c6.Position = 0
		Ticket = c6.GetString("HVD_NUM_TICKET")
	End If
	c6.Close
	DateTime.DateFormat = "dd/MM/yyyy"
	DateTime.TimeFormat = "HH:mm:ss"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	Printer1.WriteString("Tienda: " & B4XPages.MainPage.cliente.La_nombre.Text &  CRLF)
	Printer1.WriteString("ID.Cliente: " &  B4XPages.MainPage.cliente.la_cuenta.Text &  CRLF)
	Printer1.WriteString("Num. Ticket: " & Ticket &  CRLF)
	Printer1.WriteString("Fecha: " &  sDate &" " & sTime &  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	c = Starter.skmt.ExecQuery("SELECT * FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If c.RowCount > 0 Then
		Printer1.WriteString("------------Picking------------" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		Printer1.WriteString("ESTE NO ES UN TICKET DE ENTREGA" &  CRLF)
		Printer1.WriteString("SOLO ES INFORMATIVO" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		Printer1.WriteString(" " &  CRLF)
		' aqui es donde esta el pedo de julieta de los descuentos quitar el precio2 pero meter un if para saber si es ruta especial o es normal o que show.
		s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, HVD_CANT, length(HVD_CANT) as L_CANT, HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID, HVD_CODPROMO,IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT, HVD_RECHAZO FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) order by  HVD_PROID"$)
		If S.RowCount>0 Then
			For i=0 To S.RowCount -1
				S.Position=i
				Log(s.GetString("HVD_RECHAZO"))
				If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
					If s.GetString("HVD_CODPROMO") = Subs.traeAlmacen Then
						Printer1.Justify = 0
						Printer1.WriteString((s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") )&" "&s.GetString("HVD_PRONOMBRE") &  CRLF)
						

'						Dim punit As String = NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
'						TAMANO = punit.Length + TAMANO
						'
						''						Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
'						Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
'						TAMANO = ptot.Length + TAMANO
'	
'						ESPACIO = (ESPACIO - TAMANO)/2
						''						Log(ESPACIO)
'						For E=0 To ESPACIO -1
'							BLANCO = " " & BLANCO
'						Next
'						Printer1.Justify = 0
'						Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
'						Printer1.Justify = 1
'						Printer1.WriteString( punit & BLANCO)
'						Printer1.Justify = 2
'						Printer1.WriteString( ptot &  CRLF )
'						TAMANO = 0
'						ESPACIO = 29
'						BLANCO = " "
					Else If s.GetString("HVD_RECHAZO") = 1 Then
						Printer1.Justify = 0
						Printer1.WriteString((s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) &" "&s.GetString("HVD_PRONOMBRE") &  CRLF)
						
'						Private vc5 As Cursor = Starter.skmt.ExecQuery($"select iFNULL(CAT_GP_PRECIO,0) AS CAT_GP_PRECIO from CAT_GUNAPROD where CAT_GP_ID = '${s.GetString("HVD_PROID")}'"$)
'						vc5.Position = 0
'						Dim punit As String = NumberFormat2((vc5.GetString("CAT_GP_PRECIO")),0,2,2,False)
'						TAMANO = punit.Length + TAMANO
'						vc5.Close
'				
'						Private ptot As String = NumberFormat2(( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT")) * punit ),0,2,2,False)
'						TAMANO = ptot.Length + TAMANO
'	
'						ESPACIO = (ESPACIO - TAMANO)/2
						''						Log(ESPACIO)
'						For E=0 To ESPACIO -1
'							BLANCO = " " & BLANCO
'						Next
'						Printer1.Justify = 0
'						Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
'						Printer1.Justify = 1
'						Printer1.WriteString( punit & BLANCO)
'						Printer1.Justify = 2
'						Printer1.WriteString(ptot&  CRLF )
'						TAMANO = 0
'						ESPACIO = 29
'						BLANCO = " "
						Printer1.Justify = 0
					End If
				End If
			Next
		End If
	End If
	Printer1.Justify = 0
	s.Close
	Printer1.WriteString(" " &  CRLF)
	s=Starter.skmt.ExecQuery($"select HVD_PRONOMBRE, HVD_CANT, length(HVD_CANT) as L_CANT, HVD_COSTO_TOT, length(HVD_COSTO_TOT) as L_COSTOU,HVD_PROID, HVD_CODPROMO,IFNULL(HVD_RECHAZOCANT,0) AS HVD_RECHAZOCANT FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) AND HVD_RECHAZO = 0 AND HVD_CODPROMO <> '${Subs.traeAlmacen}' AND HVD_PRONOMBRE <> 'Cobranza Pendiente' order by  HVD_CODPROMO, ESPROMO DESC, HVD_PROID"$)

	If S.RowCount>0 Then
		Printer1.WriteString("-------PROMOS ENTREGA--------" &  CRLF)
		Printer1.WriteString("Cant.      Precio        Importe" &  CRLF)
		Printer1.WriteString("------------------------------" &  CRLF)
		
		For i=0 To S.RowCount -1
			S.Position=i
			If s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT") > 0 Then
				If s.GetString("HVD_CODPROMO") <> Subs.traeAlmacen Then
					Printer1.Justify = 0
					If s.GetString("HVD_CODPROMO") = s.GetString("HVD_PROID") Then
						Printer1.WriteString("* "&s.GetString("HVD_PRONOMBRE") &  CRLF)
					Else
						Printer1.WriteString((s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))&" "&s.GetString("HVD_PRONOMBRE") &  CRLF)
					End If
'					Dim punit As String =NumberFormat2((s.GETSTRING("HVD_COSTO_TOT")/s.GetString("HVD_CANT")),0,2,2,False)
'					TAMANO = punit.Length + TAMANO
					'
'					Private ptot As String = NumberFormat2((punit*s.GetString("HVD_CANT")),0,2,2,False)
'					TAMANO = ptot.Length + TAMANO
'					ESPACIO = (ESPACIO - TAMANO)/2
'					Log(ESPACIO)
'					For E=0 To ESPACIO -1
'						BLANCO = " " & BLANCO
'					Next
'					Printer1.Justify = 0
'					Printer1.WriteString( (s.GetString("HVD_CANT") - s.GetString("HVD_RECHAZOCANT"))& BLANCO)
'					Printer1.Justify = 1
'					Printer1.WriteString( punit & BLANCO)
'					Printer1.Justify = 2
'					Printer1.WriteString(ptot &  CRLF )
'					TAMANO = 0
'					ESPACIO = 29
'					BLANCO = " "
					Printer1.Justify = 0
				Else
				End If
			End If
		Next
	End If
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString("ESTE NO ES UN TICKET DE ENTREGA" &  CRLF)
	Printer1.WriteString("SOLO ES INFORMATIVO" &  CRLF)
	Printer1.WriteString("------------------------------" &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Printer1.WriteString(" " &  CRLF)
	Sleep(1000)
	Printer1.DisConnect
	ProgressDialogHide
'	Guardado
End Sub