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 c As Cursor
	Dim COMENTARIO As String
	Dim CANCELA As Button
	Dim GUARDA As Button
	Dim r_1 As RadioButton
	Dim r_2 As RadioButton
	Dim r_3 As RadioButton
	Dim e_comm As EditText
	Dim motivo As String
	Dim cuenta As String
	Dim usuario As String
	Dim sDate,sTime As String
	Dim r_4 As RadioButton
	Private p_principal As Panel
	Dim d As Cursor
	Dim reqManager As DBRequestManager
	Private cb_reprogramar As CheckBox
	Dim reprogramar As Int = 0
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
	Root.LoadLayout("no_venta")
	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
	reqManager.Initialize(Me, B4XPages.MainPage.SERVER)
	e_comm.Text=""
	r_1.Checked = False
	r_2.Checked = False
	r_3.Checked = False
	r_4.Checked = False
	cb_reprogramar.Checked = False
End Sub

Sub GPS_LocationChanged (Location1 As Location)
'	lat_gps=Location1.ConvertToSeconds(Location1.Latitude)
'	lon_gps=Location1.ConvertToSeconds(Location1.Longitude)
End Sub

Sub CANCELA_Click
	B4XPages.ShowPage("Cliente")
End Sub

Sub GUARDA_Click
	If r_1.Checked = False And r_2.Checked = False And r_3.Checked = False And r_4.Checked = False Then
		MsgboxAsync("Selecciona un motivo de rechazo","Atención")
	Else
	
		If r_1.Checked Then
			motivo = "CERRADO"
		Else If r_2.Checked Then
			motivo = "NO PIDIO"
		Else If r_3.Checked Then
			motivo = "CANCELA"
		Else
			motivo = "NO ESTA EL ENCARGADO"
		End If
	
		If motivo <> "CERRADO"  Or motivo = "CERRADO" Then
			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
			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}' "$)
			'Traemos los productos del pedido.
			c=Starter.skmt.ExecQuery("select HVD_NUM_REGISTRO, HVD_CLIENTE, HVD_PRONOMBRE, HVD_CANT, HVD_COSTO_TOT, HVD_FECHA, HVD_PROID, CAT_GP_PRECIO from HIST_VENTAS2 join CAT_GUNAPROD on CAT_GP_ID = HVD_PROID WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) order by HVD_PRONOMBRE asc")
			If c.RowCount > 0 Then 'Si  hay pedido en HIST_VENTAS ...
			
				'Revisamos si se le ha agregado venta al pedido.
				Private esteCliente As String = Subs.traeCliente
				Private rv As Cursor = Starter.skmt.ExecQuery($"select * from REPARTO where REP_CLIENTE = '${esteCliente}' and REP_CLI_ORIG <> '${esteCliente}' and REP_RECHAZO = 0"$)
				If rv.RowCount > 0 Then 'Si tenemos venta en el pedido ...
					For i2=0 To rv.RowCount - 1
						rv.Position = i2
						Log($"Actualizamos REPARTO - cliente=${rv.GetString("REP_CLIENTE")}, cliente orignal=${rv.GetString("REP_CLI_ORIG")}, le agregamos ${rv.GetString("REP_CANT")}"$)
						Starter.skmt.ExecNonQuery($"update REPARTO set REP_CANT = REP_CANT + ${rv.GetString("REP_CANT")} where REP_RECHAZO = '1' and REP_CLIENTE = '${rv.GetString("REP_CLI_ORIG")}' and REP_CLI_ORIG = '${rv.GetString("REP_CLI_ORIG")}'"$)
					Next
				End If
			
				Starter.skmt.ExecNonQuery("delete from reparto where REP_CLIENTE IN (Select CUENTA from cuentaa)")
				For i=0 To c.RowCount - 1 'Insertamos los productos en REPARTO.
					c.Position=i
					Log($"REGISTRO= ${c.GetString("HVD_NUM_REGISTRO")}"$)
					Starter.skmt.ExecNonQuery2("insert into reparto(REP_CLIENTE, REP_PRONOMBRE, REP_CANT, REP_COSTO_TOT, REP_FECHA, REP_RECHAZO, REP_PRODID, REP_PRECIO, REP_PRODREGISTRO, REP_CLI_ORIG) VALUES (?,?,?,?,?,1,?,?,?,?) ", Array As String(c.GetString("HVD_CLIENTE"),c.GetString("HVD_PRONOMBRE"),c.GetString("HVD_CANT"),c.GetString("HVD_COSTO_TOT"),c.GetString("HVD_FECHA"), c.GetString("HVD_PROID"), c.GetString("CAT_GP_PRECIO"), c.GetString("HVD_NUM_REGISTRO"), c.GetString("HVD_CLIENTE")))
					Starter.skmt.ExecNonQuery2("insert into reparto(REP_CLIENTE, REP_PRONOMBRE, REP_CANT, REP_COSTO_TOT, REP_FECHA, REP_RECHAZO, REP_PRODID, REP_PRECIO, REP_PRODREGISTRO, REP_CLI_ORIG) VALUES (?,?,?,?,?,0,?,?,?,?) ", Array As String(c.GetString("HVD_CLIENTE"),c.GetString("HVD_PRONOMBRE"),0,c.GetString("HVD_COSTO_TOT"),c.GetString("HVD_FECHA"), c.GetString("HVD_PROID"), c.GetString("CAT_GP_PRECIO"), c.GetString("HVD_NUM_REGISTRO"), c.GetString("HVD_CLIENTE")))
					Starter.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_nombre = ?", Array As Object(c.GetString("HVD_CANT"),c.GetString("HVD_PRONOMBRE")))
				Next
			End If

			Starter.skmt.ExecNonQuery2("INSERT INTO NOVENTA (NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_COMM,NV_LAT,NV_LON,NV_FOTO,NV_REPROGRAMAR) VALUES(?,?,?,?,?,?,?,?,?) ", Array As Object (cuenta,sDate & sTime, usuario, motivo,e_comm.text, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,rutaactualizar,reprogramar))
			Starter.skmt.ExecNonQuery($"UPDATE kmt_info set gestion = 3, HORAENT = '${sDate & " " & sTime}' where CAT_CL_CODIGO In (select cuenta from cuentaa) and CAT_CL_RUTA = '${rutaactualizar}'"$)
			Starter.skmt.ExecNonQuery("update HIST_VENTAS SET HVD_RECHAZO = 1, HVD_RECHAZOCANT = HVD_CANT, HVD_RECHAZOCANTC = CANTC, BCAJAS = 0 , CANTC = 0 WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
			Starter.skmt.ExecNonQuery($"update HIST_VENTAS set HVD_RECHAZO = 2,  HVD_RECHAZOCANT = HVD_RECHAZOCANT  WHERE HVD_PROID = HVD_CODPROMO and HVD_CLIENTE in (Select CUENTA from cuentaa)"$)
			Starter.skmt.ExecNonQuery("DELETE FROM PEDIDO WHERE PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
			d = Starter.skmt.ExecQuery("SELECT RUTAA FROM RUTAA")
			d.Position = 0
			Dim ruta As String = d.GetString("RUTAA")
			d.Close
			d = Starter.skmt.ExecQuery("SELECT CAT_CL_RUTA FROM kmt_info WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
			d.Position = 0
			Dim rutapre As String = d.GetString("CAT_CL_RUTA")
			d.Close
			d = Starter.skmt.ExecQuery("SELECT HVD_FECHA FROM HIST_VENTAS WHERE HVD_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
			d.Position = 0
			Dim fechaprev As String = d.GetString("HVD_FECHA")
			d.Close
			d = Starter.skmt.ExecQuery("SELECT CUENTA FROM CUENTAA")
			d.Position = 0
			Starter.skmt.ExecNonQuery2("INSERT INTO REPARTO_GEO (CLIENTE, USUARIO, FECHA_PUNTEO, LATITUD, LONGITUD, ALMACEN, RUTA_REPARTO, RUTA_PREV, FECHA_PREVENTA, MOTIVO, COMENTARIO,TIPO,ENVIO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,0)",Array As String (cuenta, usuario, sDate &" "&sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,B4XPages.MainPage.almacen,ruta,rutapre,fechaprev, motivo, e_comm.Text,"NO ENTREGADO"))
		
'			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
		Else
			COMENTARIO = e_comm.Text
'		B4XPages.ShowPage("Foto")
'		StartActivity(foto)
		End If
	End If
End Sub


Sub mandaPendientesreparto
'	c=Starter.skmt.ExecQuery("SELECT  CLIENTE, USUARIO, FECHA_PUNTEO, LATITUD, LONGITUD, ALMACEN, RUTA_REPARTO, RUTA_PREV, FECHA_PREVENTA, MOTIVO, COMENTARIO,TIPO FROM REPARTO_GEO where ENVIO <> 1")
'	Log($"REPARTO_Cliente PENDIENTE: ${c.RowCount}"$)
'	If c.RowCount>0 Then
'		For i=0 To c.RowCount -1
'			c.Position=i
'			
'			Dim cmd As DBCommand
'			cmd.Initialize
'			cmd.Name = "insert_REPARTO_MARDS"
'			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 cb_reprogramar_CheckedChange(Checked As Boolean)
	If Checked Then
		reprogramar = 1
	Else
		reprogramar = 0
	End If
End Sub