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 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 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
	Dim distance As Long
	Private b_visitasinentrega As Button
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")
	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
	Subs.centraPanel(p_principal, Root.Width)
	Starter.skmt.Initialize(Starter.ruta,"kmt.db", True)
	reqManager.Initialize(Me, B4XPages.MainPage.SERVER)
	Tar.Visible = False
	gest.Visible = False
	b_noEntrega.Visible = False
	HIST.Visible = False
	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")
	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")
	
	
	Private cym As Map = Subs.traeCantYMonto2(Subs.traeCliente)
	L_CANT.Text = cym.Get("cantidad")
	l_total.Text = Round2(cym.Get("monto"), 2)
			 
'	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)
	
	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

	Starter.distanciaGeo = ""
	c = Starter.skmt.ExecQuery("SELECT HABILITADO FROM GPS")
	If c.RowCount = 0 Then
		Starter.skmt.ExecNonQuery2("INSERT INTO GPS VALUES (?)", Array As Object(1))
	End If
	c = Starter.skmt.ExecQuery("SELECT HABILITADO FROM GPS")
	If c.RowCount >  0 Then
		c.Position = 0
		If c.GetString("HABILITADO") = 0 Then
			Starter.distanciaGeo = "500000000000"
			Log("Esto es la distancia si esta desactivada la Geo: " & Starter.distanciaGeo)
		Else If c.GetString("HABILITADO") = 1 Then
			Starter.distanciaGeo = "50"
			Log("Esto es la distancia si esta activada la Geo: " & Starter.distanciaGeo)
		End If
	Else
'		B4XSwitch1.Value = False
	End If

	Private ubicacionActual, l2 As Location
	ubicacionActual.Initialize2(B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps)
	l2.Initialize2(LATITUD, LONGITUD)
	distance = ubicacionActual.DistanceTo(l2)
'	Log("Esto es la distancia?<<<<<<<<<<<<<" & Starter.distanciaGeo)
	If distance < Starter.distanciaGeo Then
		Tar.Visible = True
		gest.Visible = True
		b_noEntrega.Visible = True
		HIST.Visible = True
	Else
		Tar.Visible = False
		gest.Visible = False
		b_noEntrega.Visible = False
		HIST.Visible = False
	End If
	Log(distance)
	Tar.Visible = True
	gest.Visible = True
	b_noEntrega.Visible = True
	HIST.Visible = True
End Sub

Sub Activity_Pause (UserClosed As Boolean)

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
		
		c = Starter.skmt.ExecQuery("SELECT HABILITADO FROM GPS")
		If c.RowCount > 0 Then
			c.Position = 0
			Dim habi As String = c.GetString("HABILITADO")
		End If
'		If distance < Starter.distanciaGeo Then
'			Tar.Visible = True
'			gest.Visible = True
'			b_noEntrega.Visible = True
'			HIST.Visible = True
'		Else
'			Tar.Visible = False
'			gest.Visible = False
'			b_noEntrega.Visible = False
'			HIST.Visible = False
'		End If
	
		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
	B_IMP_Click
	banderaimp = 1
End Sub

Sub Guardado
	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) AND NV_RUTA ='${rutaactualizar}' "$)
	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
	
	Msgbox2Async("Pedido entregado","Atención","Ok","", "",LoadBitmap(File.DirAssets,"alert2.png"), False)
	Wait For Msgbox_Result (resultado As Int)
	If resultado = DialogResponse.POSITIVE Then
		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 If
	
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
	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
'	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
	
'	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
''	c=Starter.skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION =?", Array As String ("SUCURSAL"))
''	c.Position = 0
''	sucursal = c.GetString("CAT_VA_VALOR")
''	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
'	
'	TAMANO = 0
'	ESPACIO = 28
'	BLANCO = " "
''	Dim bmp As Bitmap
''	bmp.InitializeResize(File.DirAssets, "mariana.jpg", 192, 250, True) 'ignore
''	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
'	
''	myimage = Printer1.DitherImage2D(myimage, 128)
''	
''	myimage= Printer1.PackImage(myimage)
''	Printer1.WriteString(CRLF) ' nudge the Printer1 to show the user something is happening
''	Printer1.WriteString(Printer1.REVERSE)
''	
''	Printer1.PrintImage(myimage)
''	Printer1.WriteString(Printer1.UNREVERSE)
'
''	Printer1.Justify = 1
'	'Printer1.Initialize(cmp20.OutputStream)
''	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  CRLF)
'	Printer1.WriteString("MAZAPA Distribuciones" &  CRLF)
''	Printer1.WriteString(sucursal &  CRLF)
'	Printer1.WriteString(sDate &  CRLF)
'	Printer1.WriteString(sTime &  CRLF)
'	Printer1.WriteString("Vendedor:" & 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("C.P.: " & la_cp.Text &  CRLF)
''	Printer1.WriteString("Entre calle1: " & l_entre1.Text &  CRLF)
''	Printer1.WriteString("Entre Calle2: " & l_entre2.Text &  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("------------ENTREGA-----------" &  CRLF)
'		
''		Printer1.WriteString("--------------------------------" &  CRLF)
'	Printer1.WriteString("Cant.      Precio        Importe" &  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_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_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
'						Printer1.WriteString(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)
'	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)
'	Printer1.WriteString("------------------------------" &  CRLF)
'	
'
'	Printer1.WriteString("Total Articulos:   " & L_CANT.Text &  CRLF)
'	Printer1.WriteString("Total:   $" & l_total.Text)
'
'	
'	Printer1.WriteString(" " &  CRLF)
'	Printer1.WriteString("------------------------------" &  CRLF)
''	Printer1.WriteString("ENTREGA EN :" &  CRLF)
''	Printer1.WriteString(la_Calle.Text &  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
'			Guardado
'		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))
		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 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))
	
	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_MAZAPA"
			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
		End If
		Job.Release
	End If
	
End Sub

Private Sub b_visitasinentrega_Click
	
	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) AND NV_RUTA ='${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, "VISITA PENDIENTE"))
	B4XPages.ShowPage("Principal")
End Sub