B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=13
@EndOfDesignText@
Sub Class_Globals
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore
	Dim db As SQL
	Private Root2 As B4XView
	Dim p_transparenteInicioFin2 As Panel
	Dim b_Inicio_Fin_venta2 As Button
	Dim contadorIniciarVenta, precision As Int
	Dim dentroDeGeocerca, enVenta As Boolean
	Dim IniVenNO As Boolean = False
	Dim motivoNoVenta, motivoNoVisita As String
	Private reqManager As DBRequestManager
End Sub

'You can add more parameters here.
Public Sub Initialize (vCallback As Object, vEventName As String, vRoot As B4XView, db1 As SQL, DBReq As DBRequestManager) As Object
	db = db1
	Root2 = vRoot
	reqManager = DBReq
	db.ExecNonQuery("CREATE TABLE IF NOT EXISTS BITACORAGPS(fechab TEXT, usuariob TEXT, almacenb TEXT, rutab TEXT, eventob TEXT, clienteb TEXT, iniciob TEXT, finb TEXT, latitudb TEXT, longitudb TEXT, precision TEXT, motivonoventa TEXT, motivonovisita TEXT)")
'	agregaColumna("BITACORAGPS", "BAN_GEOB", "TEXT")
	contadorIniciarVenta = 0
	cargamosPanel
	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
End Sub

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

'En geocerca si mete la contraseña poner 0 en precision gps y si esta dentro de los 50 mts poner 1 y 2 para eventos que no lo ocupen
'Mandar fecha de sync(sysdate)
Sub mandaBitacora(fechab As String, usuariob As String, almacenb As String, rutab As String, eventob As String, clienteb As String, iniciob As String, finb As String, latitudb As String, longitudb As String, precisionb As String, motivoNoVentab As String, motivoNoVisitab As String)
	Log(motivoNoVisitab)
'	Log("bitacora")
	Private cmd As DBCommand
	cmd.Initialize
	cmd.Name = "mandaBitacora_MEDICOMED_V2"
'	Log("BITACORA3")
	Private nombreCliente As String = traeNombreCliente(clienteb)
	If eventob = "Llega a almacen" Then
		nombreCliente = "BOLETA"
		clienteb = ""
		finb = iniciob
	End If
	If eventob = "Salida almacen" Then nombreCliente = "CHECKLIST"
	If eventob = "Fin Día" Then nombreCliente = "FIN DIA"
	If eventob = "Carga día" Then nombreCliente = "CARGA DIA"
	If eventob = "Carga día suplencia" Then nombreCliente = traeRutasSup
	If eventob <> "Termina Venta" And eventob <> "No Venta" Then
		db.ExecNonQuery($"INSERT INTO BITACORAGPS (fechab, usuariob , almacenb , rutab , eventob , clienteb , iniciob , finb , latitudb, longitudb , precision , motivonoventa , motivonovisita) VALUES ('${fechab}' ,'${usuariob}' , '${almacenb}' , '${rutab}' , '${eventob}' , '${clienteb}' , '${iniciob}' , '${finb}' , '${latitudb}' , '${longitudb}' , '${precisionb}' , '${motivoNoVentab}' , '${motivoNoVisitab}')"$)
	Else
		Private e As Cursor = db.ExecQuery($"select fechab from BITACORAGPS where usuariob = '${usuariob}' and almacenb = '${almacenb}' and rutab = '${rutab}' and clienteb = '${clienteb}' and eventob = 'Inicia Venta' order by fechab desc"$)
		If e.RowCount > 0 Then
			e.Position = 0
			Log("ACTUALIZA BITACORA")
			If eventob = "Termina Venta" Then
				db.ExecNonQuery($"update BITACORAGPS set finb = '${finb}' where rutab = '${rutab}' and almacenb = '${almacenb}' and usuariob = '${usuariob}' and clienteb = '${clienteb}' and fechab = '${e.GetString("fechab")}' "$)
				cmd.Parameters = Array As Object(finb, rutab, almacenb, usuariob, clienteb, "Inicia Venta", e.GetString("fechab"))
			else if  eventob = "No Venta" Then
				db.ExecNonQuery($"update BITACORAGPS set finb = '${finb}', motivonoventa = '${motivoNoVentab}', motivonovisita = '${motivoNoVisitab}' where rutab = '${rutab}' and almacenb = '${almacenb}' and usuariob = '${usuariob}' and clienteb = '${clienteb}' and fechab = '${e.GetString("fechab")}' "$)
				cmd.Parameters = Array As Object(finb, motivoNoVentab, motivoNoVisitab, rutab, almacenb, usuariob, clienteb, "Inicia Venta", e.GetString("fechab"))
			End If
		End If
	End If
	If eventob <> "Inicia Venta" Then
		Private c As Cursor = db.ExecQuery($"select * from BITACORAGPS where usuariob = '${usuariob}' and almacenb = '${almacenb}' and rutab = '${rutab}' and clienteb = '${clienteb}' order by fechab desc"$)
		If c.RowCount > 0 Then
			c.Position = 0
			cmd.Parameters = Array As Object(c.GetString("almacenb"), c.GetString("usuariob"), c.GetString("rutab"), c.GetString("eventob"), c.GetString("clienteb"), nombreCliente, c.GetString("iniciob"), c.GetString("finb"), c.GetString("latitudb"), c.GetString("longitudb"), c.GetString("precision"), c.GetString("motivonoventa"), c.GetString("motivonovisita"), c.GetString("fechab"))
			reqManager.ExecuteCommand(cmd , "mandaBitacora")
		End If
	End If
'	Log("Mandamos bitacora")
End Sub

'Regresa el nombre del cliente del id dado.
Sub traeNombreCliente(id As String) As String
	Private c As ResultSet = B4XPages.MainPage.skmt.ExecQuery($"select CAT_CL_NOMBRE from kmt_info where CAT_CL_CODIGO = '${id}'"$)
	Private n As String = "N/A"
	Do While c.NextRow
		n = c.GetString("CAT_CL_NOMBRE")
	Loop
	Return n
End Sub

'Regresa la ruta actual de la base de datos.
Sub traeRutasSup As String
	Dim c As Cursor
	Dim rutas As String
	rutas = ""
    
	c = B4XPages.MainPage.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info")
    
	If c.RowCount > 0 Then
		For i = 0 To c.RowCount - 1
			c.Position = i
			rutas = rutas & c.GetString("CAT_CL_RUTA") & ", "
		Next
		If rutas.Length > 0 Then rutas = rutas.SubString2(0, rutas.Length - 2)
	End If
    
	c.Close
	Return rutas
End Sub

'Muestra u oculta el boton de inicio y fin de venta
Sub inicioFin
	LogColor($">>>>>>>>>>>>   XX EN VENTA : ${enVenta}    <<<<<<<<<<<<"$, Colors.Blue)
'	Log(b_Inicio_Fin_venta2.Text)
	If  enVenta = False Then
		p_transparenteInicioFin2.BringToFront
		p_transparenteInicioFin2.Visible = True
'		b_Inicio_Fin_venta2.Text = "INICIAR VENTA"
'		Log("Hacemos visible el boton de Inicio Venta")
	Else
		If b_Inicio_Fin_venta2.Text <> "TERMINAR VENTA" Then
			p_transparenteInicioFin2.Visible = False
'			b_Inicio_Fin_venta2.Visible = False
		End If
	End If
End Sub

Private Sub b_Inicio_Fin_venta2_Click
'	b_Inicio_Fin_venta.Visible = False
'	Subs.bitacora(Subs.fechanormal(DateTime.Now), usuario, Subs.traeAlmacen, Subs.traeRuta, "Pre-venta", "0", Subs.fechanormal(DateTime.Now), Subs.fechanormal(DateTime.Now), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, precision, "", "")
	contadorIniciarVenta = 0
	IniVenNO = False
	If dentroDeGeocerca Then precision = 1
'	LogColor("-------> "&contadorIniciarVenta & " <-------", Colors.Red)
	LogColor($">>>>>>>>>>>>   EN VENTA : ${enVenta}    <<<<<<<<<<<<"$, Colors.Blue)
	motivoNoVenta = ""
	motivoNoVisita = ""
	p_transparenteInicioFin2.Visible = False
	If b_Inicio_Fin_venta2.Text = "TERMINAR VENTA" Then
		mandaBitacora(Subs.fechanormal(DateTime.Now), Subs.traeUsuarioDeBD, Subs.traeAlmacen, Subs.traeRutaBitacora, "Termina Venta", Subs.traeCliente, "", Subs.fechanormal(DateTime.Now), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, precision, motivoNoVenta, motivoNoVisita)
		enVenta = False
		LogColor($">>>>>> EN VENTA: ${enVenta}"$, Colors.red)
		iniciamosVenta
		Starter.skmt.ExecNonQuery($"UPDATE PEDIDO SET PE_IMPRESO =  '${B4XPages.MainPage.cliente.siimprimio}' WHERE PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA) "$)
		Starter.skmt.ExecNonQuery($"UPDATE PEDIDO_CLIENTE SET PC_IMPRESO =  '${B4XPages.MainPage.cliente.siimprimio}' WHERE PC_CLIENTE IN (SELECT CUENTA FROM CUENTAA) "$)
		B4XPages.MainPage.cliente.siimprimio = 0
		B4XPages.ShowPageAndRemovePreviousPages("Principal")
'		guardadoventa
	Else if b_Inicio_Fin_venta2.Text = "INICIAR VENTA" Then
		contadorIniciarVenta = 0
		IniVenNO = False
		contadorIniciarVenta = contadorIniciarVenta + 1
		If contadorIniciarVenta = 1 And IniVenNO = False And motivoNoVenta <> "NO VENTA" Then
			IniVenNO = True
			mandaBitacora(Subs.fechanormal(DateTime.Now), Subs.traeUsuarioDeBD, Subs.traeAlmacen, Subs.traeRutaBitacora, "Inicia Venta", Subs.traeCliente, Subs.fechanormal(DateTime.Now), "", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, precision, "", "")
			enVenta = True
			LogColor($">>>>>> EN VENTA: ${enVenta}"$, Colors.red)
'			LogColor($">>>>>> INICIA VENTA: ${Starter.enVenta} - ${Subs.traeCliente}"$, Colors.red)
		Else If contadorIniciarVenta = 1 And IniVenNO = False And motivoNoVenta = "NO VENTA" Then
			IniVenNO = True
			mandaBitacora(Subs.fechanormal(DateTime.Now), Subs.traeUsuarioDeBD, Subs.traeAlmacen, Subs.traeRutaBitacora, "Inicia Venta", Subs.traeCliente, Subs.fechanormal(DateTime.Now), "", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, precision, motivoNoVenta, "")
			enVenta = True
			LogColor($">>>>>> EN VENTA: ${enVenta}"$, Colors.red)
		Else If contadorIniciarVenta > 1 Then
			p_transparenteInicioFin2.Visible = False
		End If
	End If
	p_transparenteInicioFin2.Visible = False
	LogColor($">>>>>>>>>>>>   EN VENTA : ${enVenta}    <<<<<<<<<<<<"$, Colors.Blue)
End Sub

'Cargamos el layout del panel.
private Sub cargamosPanel
	Log(p_transparenteInicioFin2.IsInitialized)
'	Log(p_transparenteInicioFin2.)
	If Not(p_transparenteInicioFin2.IsInitialized) Then
'		LogColor(">>>>>>>   CARGAMOS PANEL BITACORA", Colors.red)
		Root2.LoadLayout("inicioFinVenta")
		p_transparenteInicioFin2.Width = Root2.Width
		p_transparenteInicioFin2.Height = Root2.Height
		b_Inicio_Fin_venta2.top = 700
		b_Inicio_Fin_venta2.Left = 5
		b_Inicio_Fin_venta2.Width = Root2.Width - 20
		b_Inicio_Fin_venta2.Text = "INICIAR VENTA"
		p_transparenteInicioFin2.BringToFront
	End If
End Sub

Sub p_transparenteInicioFin2_click
	
End Sub

' Ponemos el texto del boton en "INICIAR VENTA" y enVenta en Falso .
Sub iniciamosVenta
	enVenta = False
	b_Inicio_Fin_venta2.Text = "INICIAR VENTA"
End Sub

Sub agregaColumna(tabla As String, columna As String, tipo As String) 'ignore
	Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna en la tabla
		Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery($"SELECT COUNT(*) AS fCol FROM pragma_table_info('${tabla}') WHERE name='${columna}'"$)
		c.Position = 0
		If c.GetString("fCol") = 0 Then 'Si no esta la columna la agregamos
			B4XPages.MainPage.skmt.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
			Log($"Columna "${columna} ${tipo}", agregada a "${tabla}"."$)
		End If
'		Log(1)
	Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
		Try
			B4XPages.MainPage.skmt.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
			Log($"Columna "${columna} ${tipo}", agregada a "${tabla}".."$)
		Catch
			Log(LastException)
		End Try
		Log(2)
	End Try
End Sub

'Borra los datos de la tabla BITACORAGPS
Sub borraDatosBitacora
	db.ExecNonQuery("DELETE FROM BITACORAGPS")
End Sub

Sub JobDone(Job As HttpJob)
	Log("JOBDONE BITACORA")
	If Job.JobName = "DBRequest" Then
		Dim RESULT As DBResult = reqManager.HandleJob(Job)
		Log($"Tag: ${RESULT.tag}, success=${Job.Success}"$)
	End If
	'Log(Job.Tag)
	If Job.Success = False Then
'		Log("JOBDONE ERROR")
		LogColor("Error: " & Job.ErrorMessage, Colors.red)
	Else 'If Job Success then ...
'		Log("JOBDONE SUCCESS")
	End If
End Sub
