B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=9.85
@EndOfDesignText@
#Region Shared Files
#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
#End Region

'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip

Sub Class_Globals
	Private Root As B4XView
	Private xui As XUI
'	Private b_cargar As Button
	Private b_enviar As Button
	Dim skmt As SQL
	Dim reqManager As DBRequestManager
	Private l_pedidos2 As Label
	Private l_diasVenta As Label
	Private l_totalVenta As Label
	Private l_cantsEnCero As Label
	Private l_clienteNoNumerico As Label
	Dim cuantos_pedido As String
'	Dim datos_iguales As String
	Dim cuantos_pedidosc As String
	Dim cuantos_noventa As String
	Dim reqsPendientes As List
	Private l_ruta2 As Label
	Dim ruta As String = ""
	Private l_usuario2 As Label
	Dim usuario As String = ""
	Private l_almacen2 As Label
	Dim almacen As String = ""
	Private p_progressDialog As Panel
	Private l_progressDialog As Label
	Private p_editaRuta As Panel
	Private p_editaAlmacen As Panel
End Sub

Public Sub Initialize
'	B4XPages.GetManager.LogEvents = True
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	Root = Root1
	Root.LoadLayout("MainPage")
	reqManager.Initialize(Me, "http://187.189.244.154:1782")
	B4XPages.SetTitle(Me, "Mariana revisión de BD")
	Subs.centraPanel(p_progressDialog, Root.Width)
	Subs.centraPanel(p_editaRuta, Root.Width)
	Subs.centraPanel(p_editaAlmacen, Root.Width)
'	Subs.centraPanel(p_progressDialog, Root.Width)
End Sub

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

Sub B4XPage_Appear
	Log("INICIO")
	'		Dim usuario As String = c.GetString("USUARIO")
	Dim in As Intent = B4XPages.GetNativeParent(Me).GetStartingIntent
	If in <> Null Then
		Log(in.GetData)
		If in.GetData <> Null Then
			Dim XmlData As String
			XmlData = in.GetData
			ToastMessageShow(XmlData, False)
			'       Send_Make_somthing(in)
			'       Activity.Finish
			Try
				Dim OutStr As OutputStream = File.OpenOutput(File.DirInternal,"kmt.db",False)
				Dim InStr As InputStream = File.OpenInput("ContentDir",XmlData)
				File.Copy2(InStr,OutStr)
				Log("BD copiada a interna.")
				OutStr.Close
			Catch
				Log(LastException)
			End Try
'			ExitApplication
		End If
	End If
	Log($"Existe BD: ${File.Exists(File.DirInternal, "kmt.db") }"$)
	If File.Exists(File.DirInternal, "kmt.db") Then
		If Not(skmt.IsInitialized) Then skmt.Initialize(File.DirInternal,"kmt.db", True)
		Dim c As Cursor = skmt.ExecQuery($"select count(distinct pe_cliente) as pedidos, group_concat(distinct substr(pe_fecha, 4,2)) as diasVenta, sum(pe_costo_tot) as total, (select PE_CANT from pedido where PE_CANT = 0) as cantsEnCero, (select count(PE_CLIENTE) from pedido where printf("%d", PE_CLIENTE) <> PE_CLIENTE ) as clienteNoNumerico from pedido"$)
		Log(c.RowCount)
		If c.RowCount > 0 Then
			c.Position = 0
			l_pedidos2.Text = c.GetString("pedidos")
			l_diasVenta.Text = c.GetString("diasVenta")
			l_totalVenta.Text = "$" & NumberFormat2(c.GetString("total"), 1, 2, 2, True)
			l_cantsEnCero.Text = c.GetString("cantsEnCero")
			l_clienteNoNumerico.Text = c.GetString("clienteNoNumerico")
		End If
		Dim c As Cursor = skmt.ExecQuery("select pe_ruta from pedido")
		If c.RowCount > 0 Then
			c.Position = 0
			ruta = c.GetString("PE_RUTA")
			l_ruta2.Text = ruta
		End If
		Dim c As Cursor = skmt.ExecQuery("select USUARIO from usuarioa")
		If c.RowCount > 0 Then
			c.Position = 0
			usuario = c.GetString("USUARIO")
			l_usuario2.Text = usuario
		End If
		Dim c As Cursor = skmt.ExecQuery("select ID_ALMACEN from cat_almacen")
		If c.RowCount > 0 Then
			c.Position = 0
			almacen = c.GetString("ID_ALMACEN")
			l_almacen2.Text = almacen
		End If
		c.Close
	End If
End Sub

Private Sub b_enviar_Click
	Dim resultado = Msgbox2("Se va a enviar la venta de la BD", "AVISO", "Continuar", "Cancelar", "", Null) 'ignore
	If resultado = DialogResponse.POSITIVE Then
		reqsPendientes.Initialize
		l_progressDialog.Text = " Enviando información ..."
		p_progressDialog.Visible = True
		p_progressDialog.BringToFront
		skmt.ExecNonQuery2("delete from PEDIDO WHERE PE_PRONOMBRE = ? ", Array As Object("N/A") )
		skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE not In (select PE_CLIENTE from pedido)")
		' PEDIO_CLIENTE
		Dim c As Cursor = skmt.ExecQuery("SELECT PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT, PC_COSTO_SIN, PC_RUTA, PC_ALMACEN, PC_FACTURA FROM PEDIDO_CLIENTE ")
		Dim d As Cursor = skmt.ExecQuery("SELECT COUNT(*) as CUANTOS_PEDIDOSC FROM PEDIDO_CLIENTE ")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_pedidos_MARDS"
				cmd.Parameters = Array As Object(c.GetString("PC_CLIENTE"), c.GetString("PC_FECHA"), c.GetString("PC_USER"), c.GetString("PC_NOART"), c.GetString("PC_MONTO"), c.GetString("PC_LON"), c.GetString("PC_LAT"), almacen, ruta, c.GetString("PC_COSTO_SIN"), c.GetString("PC_FACTURA"))
				reqManager.ExecuteCommand(cmd , "ins_pedidos_1")
				reqsPendientes.Add("ins_pedidos_1")
			Next
		End If
		c.Close
		d.Position=0
'		Dim cuantos_pedidosc As String = D.GetString("CUANTOS_PEDIDOSC")
		d.Close
	
		' ENVIO DE LOS CODIGOS QR
		c = skmt.ExecQuery("SELECT CODIGOKMTS, CODIGOB, LAT, LON FROM HIST_CODIGO_BARRAS" )
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_QR_2_MARDS"
				cmd.Parameters = Array As Object(C.GetString("CODIGOKMTS"),C.GetString("CODIGOB"),C.GetString("LON"),C.GetString("LAT"),almacen, ruta)
				reqManager.ExecuteCommand(cmd , "ins_QR")
				reqsPendientes.Add("ins_QR")
			Next
		End If
		c.Close
	
		c = skmt.ExecQuery("SELECT HE_CLIE, HE_RES, HE_FECHA, HE_TIPO FROM HIST_ENCUESTA")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_encuesta_MARDS"
				cmd.Parameters = Array As Object(C.GetString("HE_CLIE"),C.GetString("HE_RES"),C.GetString("HE_FECHA"), c.GetString("HE_TIPO"))
				reqManager.ExecuteCommand(cmd , "hist_encuesta")
				reqsPendientes.Add("hist_encuesta")
			Next
		End If
		c.Close

		c = skmt.ExecQuery("SELECT PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO, PE_COSTO_SIN, PE_RUTA, PE_DESC, PE_FOLIO FROM PEDIDO")
		d = skmt.ExecQuery("SELECT COUNT(*) as CUANTOS_PEDIDO FROM PEDIDO")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_pedido_MARDS"
				cmd.Parameters = Array As Object(C.GetString("PE_CEDIS"),almacen,C.GetString("PE_COSTO_TOT"),C.GetString("PE_COSTOU"),C.GetString("PE_CANT"),C.GetString("PE_PRONOMBRE"),C.GetString("PE_PROID"),C.GetString("PE_CLIENTE"),C.GetString("PE_FECHA"),C.GetString("PE_USUARIO"),C.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"),C.GetString("PE_DESC"),c.GetString("PE_FOLIO"))
				reqManager.ExecuteCommand(cmd , "ins_pedido_1")
				reqsPendientes.Add("ins_pedido_1")
			Next
		End If
		c.Close
		d.Position=0
		cuantos_pedido = D.GetString("CUANTOS_PEDIDO")
		d.Close

		' NOVENTA
		c = skmt.ExecQuery("SELECT NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON, NV_NOMBRE, NV_DIRECCION FROM NOVENTA")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_noventa_MARDS"
				cmd.Parameters = Array As Object(C.GetString("NV_CLIENTE"),C.GetString("NV_FECHA"),C.GetString("NV_USER"),C.GetString("NV_MOTIVO"),C.GetString("NV_COMM"),C.GetString("NV_LAT"),C.GetString("NV_LON"), almacen, ruta,C.GetString("NV_NOMBRE"),C.GetString("NV_DIRECCION"))
				reqManager.ExecuteCommand(cmd , "inst_noventa")
				reqsPendientes.Add("inst_noventa")
			Next
		End If
		c.Close

'		D = skmt.ExecQuery("SELECT  COUNT(*) AS CUANTOS_NOVENTA FROM NOVENTA")
'		d.Position=0
'		Dim cuantos_noventa As String = D.GetString("CUANTOS_NOVENTA")
'		d.Close

		' GEO CERCA
		c=skmt.ExecQuery("Select HGCLIENTE, HGDATE, HGLAT, HGLON from HIST_GEOCERCA")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_geocerca_MARDS"
				cmd.Parameters = Array As Object(C.GetString("HGCLIENTE"),C.GetString("HGDATE"),C.GetString("HGLAT"),C.GetString("HGLON"))
				reqManager.ExecuteCommand(cmd , "inst_noventa")
			Next
		End If
		c.Close

		' LO DEL LIKE
		c=skmt.ExecQuery("Select HFCLIENTE, HFALIAS,HFRUTA,HFALMACEN from HIST_FACE")
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_face_like_MARDS"
				cmd.Parameters = Array As Object(C.GetString("HFCLIENTE"),C.GetString("HFALIAS"),C.GetString("HFRUTA"),C.GetString("HFALMACEN"))
				reqManager.ExecuteCommand(cmd , "inst_noventa")
			Next
		End If
		c.Close

		' DROP
'		Dim sDate,sTime As String
'		DateTime.DateFormat = "MM/dd/yyyy"
'		sDate=DateTime.Date(DateTime.Now)
'		sTime=DateTime.Time(DateTime.Now)
'		Dim cmd As DBCommand
'		cmd.Initialize
'		cmd.Name ="insert_drop_MARDS_2"
'		cmd.Parameters = Array As Object(usuario,ruta,sDate & sTime, l_porvisitar.Text,l_drop.Text,l_efectiva.Text,l_cuantosc.Text,l_cuantosn.Text, L_MONTOD.Text,"ENVIO",almacen)
'		reqManager.ExecuteCommand(cmd , "inst_noventa")
		ToastMessageShow("Se Actualizaran los datos, Este proceso podria tardar hasta un minuto, gracias "& ruta , True)
	End If
End Sub

Sub JobDone(Job As HttpJob)
	If Job.Success = False Then
		'ToastMessageShow("Error: " & Job.ErrorMessage, True)
	Else 'If Job Success then ...
		LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green)
		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			reqsPendientes.RemoveAt(reqsPendientes.IndexOf(resultado.Tag))
		End If

		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag.As(String).IndexOf("ins_pedido_") > -1 Then
				Private cliente As String= resultado.Tag
				Log($"Cliente1:${cliente}"$)
				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

		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag.As(String).IndexOf("hist_encuesta") > -1 Then
				Private cliente As String= resultado.Tag
				reqsPendientes.RemoveAt(reqsPendientes.IndexOf(resultado.Tag))
				Log($"Cliente1:${cliente}"$)
				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

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "valida_pedido" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim CUANTOSP As Int = records(RESULT.Columns.Get("CUANTOSP"))
					If cuantos_pedido < = CUANTOSP Then
						' ToastMessageShow("rojo val ok 1 cuantosp." , True)
'						datos_iguales = "ok"
'						S_CP.Text = "INFO OK"
						ToastMessageShow("INFO OK", True)
					Else
						ToastMessageShow("No se cargo bien la info P. Sync Nuevamente" & CUANTOSP & " " & cuantos_pedido, True)
'						S_CP.Text = "ENVIAR DATOS (K-2)"
						ToastMessageShow("ENVIAR DATOS (K-2)", True)
						Log("No se cargo bien la info P. Sync Nuevamente" & CUANTOSP & " " & cuantos_pedido)
					End If
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "valida_pedidoc" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim CUANTOSC As Int = records(RESULT.Columns.Get("CUANTOSC"))
					If cuantos_pedidosc = CUANTOSC Then
						' ToastMessageShow("rojo val ok 1 cuantosp." , True)
'						datos_iguales = "ok"
					Else
						ToastMessageShow("No se cargo bien la info C. Sync Nuevamente"  & CUANTOSC & " " & cuantos_pedidosc, True)
						Log("No se cargo bien la info C. Sync Nuevamente "  & CUANTOSC & " " & cuantos_pedidosc)
					End If
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "valida_noventa" Then 'query tag
				For Each records() As Object In RESULT.Rows
					Dim CUANTOSN As Int = records(RESULT.Columns.Get("CUANTOSN"))
					If cuantos_noventa = CUANTOSN Then
						' ToastMessageShow("rojo val ok 1 cuantosp." , True)
'						datos_iguales = "ok"
					Else
						ToastMessageShow("No se cargo bien la info N. Sync Nuevamente"  & CUANTOSN & " " & cuantos_noventa, True)
						Log("No se cargo bien la info N. Sync Nuevamente "  & CUANTOSN & " " & cuantos_noventa)
					End If
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = reqManager.HandleJob(Job)
			If RESULT.Tag = "ins_pedido" Then 'query tag
				For Each records() As Object In RESULT.Rows
'					PB2.Progress = PB2.Progress + 5
'					S_CP.Text = "SUBIENDO"
				Next
'				PB2.Progress = 100
'				S_CP.Text = "LISTO"
				Log("5")
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim RESULT As DBResult = B4XPages.MainPage.reqManager.HandleJob(Job)
			If RESULT.Tag = "ins_pedido" Then 'query tag
				For Each records() As Object In RESULT.Rows
'					PB2.Progress = PB2.Progress + 5
'					S_CP.Text = "SUBIENDO"
				Next
'				PB2.Progress = 100
'				S_CP.Text = "LISTO"
'				ToastMessageShow("Listo", False)
				Log("5")
			End If
		End If
	End If
	If reqsPendientes.Size = 0 Then p_progressDialog.Visible = False
	Job.Release
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
	ExitApplication
	Return False
End Sub

Private Sub l_ruta2_LongClick
	p_editaRuta.Top = l_ruta2.top
	p_editaRuta.Visible = True
End Sub

Private Sub l_almacen2_LongClick
	p_editaAlmacen.Top = l_almacen2.top
	p_editaAlmacen.Visible = True
End Sub

Private Sub l_usuario2_LongClick
	
End Sub

Private Sub b_guardaRuta_Click
	p_editaRuta.Visible = False
	skmt.ExecNonQuery($"update "$)
End Sub

Private Sub b_guardaAlmacen_Click
	p_editaAlmacen.Visible = False
End Sub

Private Sub p_principal_Click
	p_editaAlmacen.Visible = False
	p_editaRuta.Visible = False
End Sub