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 LONGITUD As String
	Dim LATITUD As String
	Dim NOMBRE As String
	Dim c As Cursor
	Dim s As Cursor
	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 Tar As Button
	Private L_QR As Label
	Private BT_QR As Button
	
	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 b_mapa 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
	Dim limiteDeCredito As String = "0"
	Dim pagarePendiente As Boolean = False
	Private p_principal As Panel
	Private B_PASO2 As Button
	Private L_CANT As Label
	Private b_aceptaCredito As Button
	Private b_cancelaCredito As Button
	Private et_montoacredito As EditText
	Private l_limite As Label
	Private p_transPagares As Panel
	Private p_pagares As Panel
	Private total As String
	Private l_montoEfectivo As Label
	Private i_qr As B4XImageView
	Private p_qr As Panel
	Private b_cerrarqr As Button
	Private qr As QRGenerator
	Private l_numeroRegistrado As Label
	Private b_confirmar As Button
	Private NOTA As String = ""
	Private l_estaVenta As Label
	Private p_transPagare2 As Panel
	Private b_abonar As Button
	Private p_abonoPagare As Panel
	Private b_aceptaAbono As Button
	Private b_cancelaAbono As Button
	Private l_montoRestante As Label
	Private et_montoAbono As EditText
	Private Label15 As Label
	Private l_totalPagare As Label
	Private l_numRegistradoAbono As Label
	Private p_transAbonoPagare As Panel
	Private saldoPendiente As String
	Private l_tituloAbono As Label
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")
	p_transPagares.left = 0 : p_transPagares.Top = 0
	p_transPagares.Width = Root.Width : p_transPagares.Height = Root.Height
	p_transPagare2.left = 0 : p_transPagare2.Top = 0
	p_transPagare2.Width = Root.Width : p_transPagare2.Height = Root.Height
	p_transAbonoPagare.left = 0 : p_transAbonoPagare.Top = 0
	p_transAbonoPagare.Width = Root.Width : p_transAbonoPagare.Height = Root.Height
	Subs.centraPanel(p_pagares, Root.Width)
	Subs.centraPanel(p_qr, p_transPagare2.Width)
	Subs.centraPanel(p_abonoPagare, p_transAbonoPagare.Width)
	Subs.centraEtiqueta(l_tituloAbono, p_abonoPagare.Width)
	qr.Initialize(i_qr.mBase.Width)
	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")
	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
	total = "0"
	et_montoacredito.Text = ""
	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, CAT_CL_IDALMACEN 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
	l_montoEfectivo.Text = ""
	et_montoacredito.Text = ""
	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_numeroRegistrado.Text = "Num. Registrado: " & c.GetString("CAT_CL_TELEFONO")
	l_numRegistradoAbono.Text = "Num. Registrado: " & c.GetString("CAT_CL_TELEFONO")
	B4XPages.MainPage.almacen = c.GetString("CAT_CL_IDALMACEN")
	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")
	
	c=Starter.skmt.ExecQuery("select count(*) as EXISTE from HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) and HVD_RECHAZO = 0 ")
	C.Position=0
	Dim Existe As String = C.GetString("EXISTE")
	C.Close
	If Existe <> 0 Then
		c = Starter.skmt.ExecQuery("select SUM(HVD_CANT) AS PC_NOART, SUM(HVD_COSTO_TOT) AS PC_MONTO from HIST_VENTAS where HVD_CLIENTE in (Select CUENTA from cuentaa) and HVD_RECHAZO = 0 and hvd_codpromo <> HVD_PROID ")
		C.Position = 0
		L_CANT.Text = c.GetString("PC_NOART")
		l_total.Text = Round2(c.GetString("PC_MONTO"), 2)
		total = Round2(c.GetString("PC_MONTO"), 2)
	End If
'	Private cym As Map = Subs.traeCantYMonto2(Subs.traeCliente)
'	L_CANT.Text = cym.Get("cantidad")
'	l_total.Text = Round2(cym.Get("monto"), 2)
	p_transPagares.Visible = False
	If CREDITO = "1" Then
'		Msgbox("AVISO","SE TIENE QUE IMPRIMIR PAGARÉ") 'ignore
		Dim pa As ResultSet = Starter.skmt.ExecQuery($"select * from pagares where cliente = '${Subs.traeCliente}' and ruta_preventa = (select cat_cl_ruta from kmt_info where cat_cl_codigo = '${Subs.traeCliente}') order by nota desc limit 1"$)
		Log("-------------->>  " & pa.RowCount)
		pagarePendiente = False 'Valor por default
		Do While pa.NextRow
			Log(pa.GetString("NOTA"))
			pagarePendiente = True
			saldoPendiente = pa.GetString("SALDO_PENDIENTE")
			l_totalPagare.Text = $"Total del pagaré: $${NumberFormat2(saldoPendiente, 1, 2, 2, True)}"$
		Loop
		If pagarePendiente Then
			Msgbox2Async("El cliente tiene un pagare pendiente, y es NECESARIO liquidarlo para realizar la entrega, ¿desea liquidarlo?", "PAGARÉ PENDIENTE", "SI", "", "NO", Null, True)
			Wait For Msgbox_Result (result As Int)
			If result=DialogResponse.POSITIVE Then
				liquidarPagare
			End If
			 b_abonar.Visible = True
		Else
			b_abonar.Visible = False
		End If
		Private lc As ResultSet = Starter.skmt.ExecQuery($"select cat_cl_limitecredito from kmt_info where cat_cl_codigo = '${Subs.traeCliente}'"$)
		Do While lc.NextRow
			limiteDeCredito = lc.GetString("CAT_CL_LIMITECREDITO")
		Loop
	End If
'	Private cym As Map = Subs.traemosCantYMonto(clv_pedido)
'	L_CANT.Text = cym.Get("cantidad")
'	l_total.Text = cym.Get("monto")
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 ListView1_ItemLongClick (Position As Int, Value As Object)

End Sub

Sub gest_Click
	Log($"${CREDITO}, ${pagarePendiente}"$)
	Msgbox2Async("¿La venta va a ser a credito?", "AVISO", "SI", "CANCELAR", "NO", Null, True)
	Wait For Msgbox_Result (result As Int)
	If result=DialogResponse.POSITIVE Then
		If CREDITO = 1 And Not(pagarePendiente) Then
			p_transPagares.BringToFront
			p_transPagares.Visible = True
			l_limite.Text = $"Límite de crédito: $${NumberFormat2(limiteDeCredito, 1,2,2,True)}"$
			l_estaVenta.Text = $"Esta venta: $${NumberFormat2(l_total.text, 1,2,2,True)}"$
		Else
			Msgbox2Async("El cliente no es sujeto a crédito o tiene pagares pendientes", "AVISO", "OK", "", "", Null, False)
			Wait For Msgbox_Result (result As Int)
			Log(result)
			If result=DialogResponse.POSITIVE Then
'				guardaVenta
			End If
		End If
	else if result=DialogResponse.NEGATIVE Then
		guardaVenta
	else if result=DialogResponse.CANCEL Then
		
	End If

End Sub

Sub guardaVenta
	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
	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
	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_IDALMACEN) VALUES (?,?,?,?,?,?,?,?) ", Array As Object (cuenta,sDate &" "& sTime, usuario, "ENTREGA","ENTREGA COMPLETA", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, B4XPages.MainPage.almacen))
	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  where CAT_CL_CODIGO In (select cuenta from cuentaa) ")
	Starter.skmt.ExecNonQuery("update HIST_VENTAS SET HVD_ESTATUS = 1 WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	mandaPendientesreparto
	B4XPages.ShowPage("Principal")
End Sub

Sub b_noEntrega_Click
	' skmt.ExecNonQuery("delete from PEDIDO")
	B4XPages.ShowPage("noVenta")
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
	' BACK key pressed
	' I want to capture the key here so I return True
	B4XPages.ShowPage("Clientes")
	Return False
End Sub

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

Sub DATOS_Click
'	StartActivity(telefonos)
End Sub

Sub Guardar_Click
	B4XPages.ShowPage("Principal")
End Sub

Sub b_mapa_Click
	StartActivity(MAPA_CLIENTE)
End Sub

Sub HIST_Click
'	B4XPages.MainPage.historico.prodsMap.Initialize
''	B4XPages.MainPage.historico.clv_pedido.Clear
'	B4XPages.ShowPage("Historico")
	B4XPages.MainPage.detalleVenta.prodsMap.Initialize
'	B4XPages.MainPage.historico.clv_pedido.Clear
	B4XPages.ShowPage("DetalleVenta")
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)
	TAMANO = 0
	ESPACIO = 21
	BLANCO = " "
	CREDITO ="1"
	If CREDITO = "1" Then
		DateTime.DateFormat = "MM/dd/yyyy"
		sDate=DateTime.Date(DateTime.Now)
		sTime=DateTime.Time(DateTime.Now)
		printer.Initialize(cmp20.OutputStream)
		printer.WriteLine("DBC.")
		printer.WriteLine("RFC: ")
		printer.WriteLine(sDate)
		printer.WriteLine(sTime)
		printer.WriteLine("Tienda: " & La_nombre.Text)
		s=Starter.skmt.ExecQuery("select SUM(HVD_CANT) AS PC_NOART, SUM(HVD_COSTO_TOT) AS PC_MONTO from HIST_VENTAS where HVD_CLIENTE in (Select CUENTA from cuentaa)")
		s.Position=0
		printer.WriteLine("Debo (emos) y pagare (mos)      incondicionamelte a la orden de DBC a la cantidad de $"  & s.GetString("PC_MONTO") & " PESOS _______________________________________________________________________________________________________________ ")
		printer.WriteLine("en esta ciudad o en cualquier   otra que se requiera de pago,   valor recibido a mi entera satisfaccion y que me obligo a cumplir el dia______________________.")
		printer.WriteLine(" ")
		printer.WriteLine("Si este pagare no fuera cubiertoa su vencimiento Me (nos) obligo (amos) a pagar intereses moratorios a razon de 3 % mensual")
		printer.WriteLine(" ")
		printer.WriteLine(" ")
		printer.WriteLine(" ")
		printer.WriteLine(" ")
		printer.WriteLine(" ")
		printer.WriteLine(" ")
		printer.WriteLine(" ")
		printer.WriteLine("------------------------------")
		printer.WriteLine("    NOMBRE Y FIRMA ")
		printer.WriteLine("------------------------------")
		printer.WriteLine(" ")
		printer.Flush
	End If

	printer.Initialize(cmp20.OutputStream)
	printer.WriteLine("PROFINA")
	printer.WriteLine("RFC: ")
	printer.WriteLine("Tel.:")
	printer.WriteLine(sDate)
	printer.WriteLine(sTime)
	printer.WriteLine("Vendedor:" & usuario)
	printer.WriteLine("Tienda: " & La_nombre.Text)
	s=Starter.skmt.ExecQuery("select SUM(HVD_CANT) AS PC_NOART, SUM(HVD_COSTO_TOT) AS PC_MONTO from HIST_VENTAS where HVD_CLIENTE in (Select CUENTA from cuentaa)")
	s.Position=0
	c=Starter.skmt.ExecQuery("select SUM(PE_CANT) AS PE_CANT, SUM(PE_COSTO_TOT) AS PE_COSTO_TOT FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	C.Position=0
	
	printer.WriteLine("Total :   $" & (s.GetString("PC_MONTO") + c.GetString("PE_COSTO_TOT")))
	s.Close
	printer.WriteLine("-----------ENTREGA------------")
	S=Starter.skmt.ExecQuery("select HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,length(HVD_cant) as L_CANT,HVD_COSTO_TOT,length(HVD_COSTO_TOT) as L_COSTO_TOT from HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) ")

	's=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU, PE_COSTO_TOT, length(PE_COSTO_TOT) as L_COSTO_TOT, PE_PROID, PE_CEDIS FROM PEDIDO WHERE  PE_CLIENTE IN (Select CUENTA from cuentaa)", Array As String("VENTA"))
	If S.RowCount>0 Then
		For i=0 To S.RowCount -1
			S.Position=i
			'If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
			'	printer.WriteLine(s.GetString("PE_PRONOMBRE"))
				
			'Else
				
			printer.WriteLine(s.GetString("HVD_CANT") & " " & s.GetString("HVD_PRONOMBRE"))
			TAMANO = s.GetLong("L_CANT") + TAMANO
			'TAMANO = s.GetLong("L_COSTOU") + TAMANO
			TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
	
			ESPACIO = ESPACIO - TAMANO
	
			For E=0 To ESPACIO -1
				BLANCO = " " & BLANCO
			Next
			printer.WriteLine("$" & s.GETSTRING("HVD_COSTO_TOT") )
			TAMANO = 0
			ESPACIO = 21
			BLANCO = " "
			'End If
		Next
	End If
	s.Close
	
	s=Starter.skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU, PE_COSTO_TOT, length(PE_COSTO_TOT) as L_COSTO_TOT, PE_PROID, PE_CEDIS FROM PEDIDO WHERE  PE_CLIENTE IN (Select CUENTA from cuentaa)", Array As String("VENTA"))
	If S.RowCount>0 Then
		For i=0 To S.RowCount -1
			S.Position=i
			'If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
			'	printer.WriteLine(s.GetString("PE_PRONOMBRE"))
				
			'Else
				
			printer.WriteLine(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE"))
			TAMANO = s.GetLong("L_CANT") + TAMANO
			'TAMANO = s.GetLong("L_COSTOU") + TAMANO
			TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
	
			ESPACIO = ESPACIO - TAMANO
	
			For E=0 To ESPACIO -1
				BLANCO = " " & BLANCO
			Next
			printer.WriteLine("$" & s.GETSTRING("PE_COSTO_TOT") )
			TAMANO = 0
			ESPACIO = 21
			BLANCO = " "
			'End If
		Next
	End If
	s.Close
	printer.WriteLine("------------------------------")
	printer.WriteLine("---NO ES UN COMPROBANTE ------")
	printer.WriteLine("---------FISCAL---------------")
	printer.WriteLine("---COMPROBANTE DE ENTREGA-----")
	printer.WriteLine("------------------------------")
	
	printer.Flush
	'	printer.Close
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 L 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
			'FLEOS
			cmp20.ConnectInsecure(btAdmin,PairedDevices.Get(PairedDevices.GetKeyAt(0)),1)
			'cmp20.Connect(PairedDevices.Get(PairedDevices.GetKeyAt(0)))
		Catch
			Msgbox("Connecting","Printer Error") 'ignore
			printer.Close
			cmp20.Disconnect
		End Try
	Else
		L.Initialize
		For i = 0 To PairedDevices.Size - 1
			L.Add(PairedDevices.GetKeyAt(i))
		Next
		resimp = InputList(L, "Choose device", -1) 'ignore
		If resimp <> DialogResponse.CANCEL Then
			cmp20.Connect(PairedDevices.Get(L.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))
	B4XPages.ShowPage("Principal")
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_GUNA2"
'			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
	LogColor("*******  MANDAPENDIENTES COMENTADO POR PRUEBAS ******", Colors.red)
End Sub

Sub JobDone(Job As HttpJob)
	Log("JobDone Cliente: " & 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
				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
				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
					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_cancelaCredito_Click
	p_transPagares.Visible = False
End Sub

Private Sub b_aceptaCredito_Click
	
'	almacen, RUTA, ruta_reparto, clienteid, monto, fecha (yyyy/mm/dd HH:mm:ss)
'	almacen, RUTA, ruta_reparto, clienteid, monto, nota, fecha
	
	p_transPagares.Visible = False
	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 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)
	Starter.skmt.ExecNonQuery($"insert into PAGARES_NUEVOS (NOTA, CLIENTE, ALMACEN, MONTO, RUTA_PREVENTA, REPARTO, FECHA) values ('${NOTA}', '${cliente}', '${Subs.traeAlmacen}', '${et_montoacredito.text}', '${RUTA_PREVENTA}', '${Subs.traeRutaReparto}', '${sDate & " " & sTime}')"$)
	
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "insertaPagareGunaRep"
	cmd.Parameters = Array As Object(Subs.traeAlmacen, RUTA_PREVENTA, Subs.traeRutaReparto, cliente, et_montoacredito.Text, NOTA, sDate & " " & sTime)
	reqManager.ExecuteCommand(cmd, $"insertaPagare_${NOTA}"$)

'	guardaVenta
End Sub

Private Sub p_transPagares_Click
	
End Sub

Private Sub et_montoacredito_TextChanged (Old As String, New As String)
	If New.Length > 0 And et_montoacredito.Text > limiteDeCredito Then ' Si el credito que quieren es mayor al autorizado, solo se permite el autorizado.
		et_montoacredito.Text = limiteDeCredito
	Else If New.Length > 0 And et_montoacredito.Text > total Then ' Si el credito que quieren es mayor al monto de venta, solo se permite el monto de venta.
		et_montoacredito.Text = total
	End If
	If et_montoacredito.Text <> "" And New.Length > 0 Then
		l_montoEfectivo.Text = $"Efectivo: $${NumberFormat2((total - et_montoacredito.text), 1, 2, 2, True)}"$
	End If
End Sub

Private Sub CrearQR(NOTA2 As String)
	Private texto As String = $"https://wa.me/5215637241894?text=PAGARE ${NOTA2}"$
	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_cerrarqr_Click
	i_qr.Clear
'	If y = 1 Then
	p_transPagare2.Visible = False
'		p_gestion.Visible = True
'		p_gestion.BringToFront
'	Else
'		p_qr.Visible = False
'	End If
End Sub

Private Sub b_confirmar_Click
	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_abonar_Click
	liquidarPagare
End Sub

Sub liquidarPagare
	p_transAbonoPagare.Visible = True
	p_transAbonoPagare.BringToFront
End Sub

Private Sub p_transAbonoPagare_Click
	p_transAbonoPagare.Visible = False
End Sub

Private Sub b_cancelaAbono_Click
	p_transAbonoPagare.Visible = False
End Sub

Private Sub b_aceptaAbono_Click
	p_transAbonoPagare.Visible = False
	Private sn As Map
	sn.Initialize
	sn.Put("number","5215545815654")
	sn.Put("message","Hola")
	Dim jg As JSONGenerator
	jg.Initialize(sn)
	Log(jg)
	Dim HTTPTask As HttpJob
	HTTPTask.Initialize("HTTPTask", Me)
	HTTPTask.PostString("http://192.168.0.190:3018/v1/messages", jg.ToString)
	HTTPTask.GetRequest.SetContentType("application/json")
	HTTPTask.GetRequest.SetHeader("Accept","application/json")
	wait for (HTTPTask) JobDone(HTTPTask As HttpJob)
	If HTTPTask.Success Then
		'Json.Initialize(HTTPTask.GetString)
		Log("1:" & HTTPTask.GetString)
		Log("2:" & HTTPTask.ErrorMessage)
	End If
	HTTPTask.Release
End Sub

Private Sub et_montoAbono_TextChanged (Old As String, New As String)
	Private cs As CSBuilder
	cs.Initialize
	If New.Length > 0 And et_montoAbono.Text > saldoPendiente Then ' Si el credito que quieren es mayor al autorizado, solo se permite el autorizado.
		et_montoAbono.Text = saldoPendiente
	End If
	If et_montoAbono.Text <> "" And New.Length > 0 Then
		Private msg As String = ""
		If (saldoPendiente - et_montoAbono.text) > 0 Then
			b_aceptaAbono.Text = "Abonar"
			Private cd1 As ColorDrawable
			cd1.Initialize(Colors.RGB(223, 163, 0), 10dip)
			b_aceptaAbono.Background = cd1
			l_montoRestante.Text = cs.Color(Colors.black).Size(12).append($"Restan: $${NumberFormat2((saldoPendiente - et_montoAbono.text), 1, 2, 2, True)} ${msg} "$).pop.color(Colors.red).Append(CRLF & "¡No se puede realizar la entrega!").PopAll
		Else
			Private cd1 As ColorDrawable
			cd1.Initialize(Colors.RGB(0, 174, 0), 10dip)
			b_aceptaAbono.Background = cd1
			b_aceptaAbono.Text = "Liquidar"
			l_montoRestante.Text = cs.color(Colors.green).Append("¡Listo para liquiar!").PopAll
		End If

'		l_montoRestante.Text = $"Restan: $${NumberFormat2((saldoPendiente - et_montoAbono.text), 1, 2, 2, True)} ${msg}"$
	End If
End Sub

Private Sub p_abonoPagare_Click
	
End Sub