B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=11.5
@EndOfDesignText@
Sub Class_Globals
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore
	Dim ruta As String
	Dim q_buscar As String
	Dim forzarBusqueda As Boolean = False
	Dim skmt As SQL
	Dim c As Cursor
	Dim c2 As Cursor
	Dim C3 As Cursor
	Dim s As Cursor
	Dim lv_catalogos As ListView
	Dim lv_promos As ListView
	Dim entro As String
	Dim gest As Button
	Dim lfila As Label
	Dim marca As String
	Dim tipo As String
	Dim subtipo As String
	Private BUSCA As EditText
	Dim ya_entro As String
	Dim TIENE_PROMOS As String
	Dim RES As String
	Dim S1 As Cursor
	Dim bmp As Bitmap
	Dim ciclo As String
	Private b_qr As Button
	Private p_productos As Panel
	Dim clv_productos As CustomListView
	Private ImageView1 As ImageView
	Private Panel3 As Panel
	Private p_prods As Panel
	Private i_prod As ImageView
	Private l_prodX As Label
	Private b_prodMas As Button
	Private l_pCant As Label
	Private et_pCant As EditText
	Private b_prodMenos As Button
	Dim b_terminar1 As Button
	Dim b_continuar As Button
	Private l_total As Label
	Private l_totProds As Label
	Dim totalProds As Int = 0
	Dim totalCompra As Float = 0
	Dim etCantHasFocus As Boolean = False
	Dim prodsMap As Map
	Private l_Cargando As Label
	Private l_info As Label
	Private b_buscar As Button
	Private p_botonesVenta As Panel
	Private lv_tipo As ListView
	Private lv_subtipo As ListView
	Private p_vistaPreviaTrans As Panel
	Private lv_prodsPedido As ListView
	Private b_rechazar As Button
	Private b_aceptar As Button
	Private p_vistaPrevia As Panel
	Dim folio As String
	Dim result As String
	Private l_cant As Label
	Private l_total2 As Label
	Dim prodsPedidoActual As String
	Dim montoPedidoActual As String
	
	Dim clv_prods_ll As CustomListView
	Private PCLV As PreoptimizedCLV
	Dim listaProds As List
'	Type AirportData (Name As String, AirportID As Int, IATA As String, ICAO As String, City As String, Latitude As Float, Longitude As Float, Altitude As String)
	Dim pedidoMap As Map
	Private p_botMasMen As Panel
	Dim reiniciarlistaProds As Boolean= False
'	Dim listaRenglones As List
	Dim listaTiempos As List
	Dim clienteId As String
	Dim rutaUsuario As String
	Dim hayPedido As Boolean
	Dim listaHints As List
	Dim r As Cursor
	Dim vamoaver As List
	Dim j3 As Cursor
	Dim invTotal As Int
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
'	Activity.RemoveAllViews
	Root.LoadLayout("productos")
	ruta = File.DirInternal
	If File.Exists(ruta, "kmt.db") = False Then
		File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
	End If
	PCLV.Initialize(Me, "PCLV", clv_prods_ll)
	ciclo = 1
	l_info.Width = Root.Width * 0.8
	l_info.Left = (Root.Width/2) - (l_info.Width/2)
	c = B4XPages.MainPage.skmt.ExecQuery("select distinct CAT_GP_TIPO from cat_gunaprod where CAT_GP_TIPO <> 'PROMOS' order by CAT_GP_TIPO")
	If c.RowCount > 0 Then
		Dim label1 As Label
		label1 = lv_tipo.SingleLineLayout.Label
		label1.TextSize = 17
		label1.TextColor = Colors.Black
		lv_tipo.Clear
		For i=0 To c.RowCount-1
			c.Position=i
			Log("ENTRE AQUI EN PROMOS create")
			lv_tipo.AddSingleLine(c.GetString("CAT_GP_TIPO"))
		Next
	End If
	c.Close
'	llenaCatalogo(False)
'	listaRenglones.Initialize
	listaTiempos.Initialize
	listaProds.Initialize
	pedidoMap.Initialize
	listaHints.Initialize
'	Log("Llamamos LlenaProdsLL")
'	LlenaProdsLL(Null)
	clv_prods_ll.Clear
	prodsMap.Initialize
End Sub

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

Sub B4XPage_Appear
	If B4XPages.MainPage.tipo_venta = "PREVENTA" Or B4XPages.MainPage.tipo_venta = "ABORDO" Then
		Starter.tabla = "CAT_GUNAPROD"
	Else If B4XPages.MainPage.tipo_venta = "VENTA" Then
		Starter.tabla = "CAT_GUNAPROD2"
	End If
	clienteId = Subs.traeCliente
	rutaUsuario = Subs.traeRuta
	B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE CAT_GUNAPROD SET CAT_GP_TIPOPROD = (?) WHERE CAT_GP_TIPOPROD = (?) ",Array As Object("PRIORITARIO","1"))
	B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE CAT_GUNAPROD SET CAT_GP_TIPOPROD = (?) WHERE CAT_GP_TIPOPROD = (?) ",Array As Object("ESTRATEGICO","2"))
	B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE CAT_GUNAPROD SET CAT_GP_TIPOPROD = (?) WHERE CAT_GP_TIPOPROD = (?) ",Array As Object("COMPLEMENTARIO","3"))
	B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE CAT_GUNAPROD SET CAT_GP_TIPOPROD = (?) WHERE CAT_GP_TIPOPROD = (?) ",Array As Object("CATALOGO REGULAR","0"))
	B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE CAT_GUNAPROD SET CAT_GP_TIPOPROD = (?) WHERE CAT_GP_CLASIF = (?) ",Array As Object("PROMOS","PROMOS"))
	clv_prods_ll.GetBase.SetLayoutAnimated(0, 5dip, 130dip, Root.Width + 10, Root.Height * 0.74) 'Cambiamos el tamaño y posición de la lista de productos
	clv_prods_ll.Base_Resize(clv_prods_ll.GetBase.Width, clv_prods_ll.GetBase.Height) 'Cambiamos el tamaño del panel interno de la lista para que ajuste al nuevo tamaño.
	If B4XPages.MainPage.bTerminarClicked Then
		lv_catalogos.Visible = True
		lv_promos.Visible = False
		lv_tipo.Visible = False
		lv_subtipo.Visible = False
		clv_prods_ll.AsView.Visible = False
		B4XPages.MainPage.bTerminarClicked = False
	End If
	If ya_entro <> "1" Then
		If BUSCA.Text <> "" Then BUSCA.Text =""
		entro ="3"
		lv_catalogos.Clear
		Sleep(100)
		lfila.Text = "CATALOGOS"
		p_productos.Height = Root.Height
		clv_prods_ll.AsView.Visible = False
		lv_catalogos.Visible = True
		p_botonesVenta.Visible = False
		p_botonesVenta.Top = clv_prods_ll.AsView.top + clv_prods_ll.AsView.Height - 10
		lv_promos.Visible = False
	End If
	Dim label1 As Label
	label1 = lv_catalogos.SingleLineLayout.Label
	label1.TextSize = 17
	label1.TextColor = Colors.Black
	lv_catalogos.Clear
	lv_catalogos.AddSingleLine("CATALOGO")
'	c = B4XPages.MainPage.skmt.ExecQuery($"select count(*) as hayPromos from ${Starter.tabla} where CAT_GP_TIPOPROD = 'PROMOS'"$)
	c = B4XPages.MainPage.skmt.ExecQuery($"select count(*) as hayPromos from ${Starter.tabla} where CAT_GP_TIPO = 'PROMOS'"$)
	c.Position = 0
	
	
	c = B4XPages.MainPage.skmt.ExecQuery($"SELECT CUENTA FROM CUENTAA"$)
	c.Position = 0
	If c.GetString("CUENTA") <> "0" Then
		c2=B4XPages.MainPage.skmt.ExecQuery2($"select  CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_IMG from ${Starter.tabla} where CAT_GP_PRECIO > 0 AND  CAT_GP_ALMACEN > 0 AND CAT_GP_TIPO = ? AND CAT_GP_SUBTIPO = ?  AND CAT_GP_ID NOT IN (SELECT PE_PROID FROM PEDIDO WHERE PE_CLIENTE IN (Select cuenta from cuentaa) )"$, Array As String("PROMOS", "PROMOS"))
'	Log($"res:${c2.RowCount}, ${Value}, ${marca}, ${tipo}"$)
		Private hayPromos As Boolean = False
		If c2.RowCount > 0 Then
			For i=0 To c2.RowCount -1
				c2.Position=i
				Private tm As Map = Subs.procesaPromocion(c2.GetString("CAT_GP_ID"), clienteId)
				If tm.Get("status") = "ok" Then 'Solo muestrala si hay producto.
					hayPromos = True
				End If
			Next
			If hayPromos Then lv_catalogos.AddSingleLine("PROMOS")
		Else
			Log("NO HAY PROMOS")
		End If
		c2.Close
	End If
	
	Sleep(100)
	l_total.Visible = False
	l_totProds.Visible = False
	l_total.Left = 5dip
	l_totProds.Width = Root.Width * 0.19
	l_total.Left = l_totProds.Width + 20
	l_total.Width = Root.Width * 0.25
'	Log(Subs.traeTotalesClienteActual)
	Dim m As Map = Subs.traeTotalesClienteActual
	prodsPedidoActual = m.Get("productos")
	montoPedidoActual = m.Get("monto")
	hayPedido = Subs.hayPedido
'	LogColor("Pedido ant? - "&hayPedido, Colors.Magenta)
		B4XPages.MainPage.productos.clv_prods_ll.Clear
	If reiniciarlistaProds Then
'		Log("Llamamos LlenaProdsLL")
'		LlenaProdsLL(Null)
		clv_prods_ll.Clear
	else If hayPedido Then
'		LogColor("HAY PEDIDO ANTERIOR", Colors.red)
'		Log("Llamamos LlenaProdsLL")
'		LlenaProdsLL(Null)
		clv_prods_ll.Clear
	End If
	If clv_prods_ll.Size = 0 Then LlenaProdsLL(Null)
	clv_prods_ll.JumpToItem(0) 'Vamos al primer artículo de la lista.
	PCLV.lblHint.SetTextSizeAnimated(0,13)
	PCLV.B4XSeekBar1.Color1=Colors.DarkGray
	PCLV.B4XSeekBar1.Color2=Colors.DarkGray
	PCLV.B4XSeekBar1.ThumbColor=Colors.red
	PCLV.B4XSeekBar1.mBase.Left=Root.Width *0.91
'	PCLV.B4XSeekBar1.mBase.Top=-50
	PCLV.B4XSeekBar1.mBase.Height=clv_prods_ll.AsView.Height
	PCLV.pnlOverlay.Height = clv_prods_ll.AsView.Height
	PCLV.B4XSeekBar1.Update
	
	

End Sub

Sub PCLV_AddProds

End Sub

Sub lv_catalogos_ItemClick (Position As Int, Value As Object)
	If Value = "CATALOGO" Then
'		lfila.text = "TIPO"
		lfila.text = "PRODUCTOS"
		lv_catalogos.Visible = False
'		lv_tipo.Visible = True
		If clv_prods_ll.Size = 0 Then LlenaProdsLL(Null)
		clv_prods_ll.AsView.Visible = True
		If hayPedido Then p_botonesVenta.Visible = True 'Si ya hay pedido, entonces mostramos los botones.
	Else
		clv_prods_ll.AsView.Visible = False
		lv_promos.Visible = True
		lfila.text = "PROMOCIONES"
		lv_catalogos.Visible = False
		lv_promos.Clear
		Dim label1 As Label
		label1 = lv_promos.TwoLinesLayout.Label
		label1.TextSize = 12
		label1.TextColor = Colors.Black
		Dim label2 As Label
		label2 = lv_promos.TwoLinesLayout.SecondLabel
		label2.TextSize = 12
		label2.TextColor = Colors.Black
		Dim label13 As Label
		label13 = lv_promos.TwoLinesAndBitmap.Label
		label13.TextSize = 12
		label13.TextColor = Colors.Black
		Dim label14 As Label
		label14 = lv_promos.TwoLinesAndBitmap.SecondLabel
		label14.TextSize = 12
		label14.TextColor = Colors.Black
		lfila.text = "PROMOS"
		
		
		
'		c2=B4XPages.MainPage.skmt.ExecQuery2($"select  CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_IMG from ${Starter.tabla} where CAT_GP_PRECIO > 0 AND  CAT_GP_ALMACEN > 0 and CAT_GP_TIPOPROD = ? AND CAT_GP_TIPO = ? AND CAT_GP_SUBTIPO = ?  AND CAT_GP_ID NOT IN (SELECT PE_PROID FROM PEDIDO WHERE PE_CLIENTE IN (Select cuenta from cuentaa) )"$, Array As String(Value, Value, Value))
		c2=B4XPages.MainPage.skmt.ExecQuery2($"select  CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_IMG from ${Starter.tabla} where CAT_GP_PRECIO > 0 AND  CAT_GP_ALMACEN > 0 AND CAT_GP_TIPO = ? AND CAT_GP_SUBTIPO = ?  AND CAT_GP_ID NOT IN (SELECT PE_PROID FROM PEDIDO WHERE PE_CLIENTE IN (Select cuenta from cuentaa) )"$, Array As String(Value, Value))
'		Log($"res:${c2.RowCount}, ${Value}, ${marca}, ${tipo}"$)
		If c2.RowCount > 0 Then
			For i=0 To c2.RowCount -1
				c2.Position=i
				Private tm As Map = Subs.procesaPromocion(c2.GetString("CAT_GP_ID"), clienteId)
				If tm.Get("status") = "ok" Then 'Solo muestrala si hay producto.
					lv_promos.AddTwoLines(c2.GetString("CAT_GP_NOMBRE"),"# " & c2.GetString("CAT_GP_ALMACEN") & " $ " & c2.GetString("CAT_GP_PRECIO") & " F:" & tm.Get("mp").As(Map).Get("prodsFijosCant") & " V:" & tm.Get("mp").As(Map).Get("prodsVariablesCant"))
				End If
			Next
		Else
			ToastMessageShow("No hay promociones disponibles.", False)
		End If
		c2.Close
		entro = "4"
	End If
End Sub

Sub lv_catalogos2_ItemClick (Position As Int, Value As Object)
	clv_prods_ll.AsView.Visible = False
	BUSCA.Text = ""
	Dim cliente As C_Cliente = B4XPages.GetPage("Cliente")
	Log($"value=${Value}"$)
	If Value = "PROMOS" And cliente.cuenta <> "N" Then
		entro = "3"
		marca = "PROMOS"
		tipo = "PROMOS"
	Else if Value = "PROMOS" And cliente.cuenta = "N"  Then
		entro = "5"
		B4XPages.ShowPage("Cliente")
	End If
	If Value = "PROMOS" Then
		LogColor("Promos", Colors.red)
		c2=B4XPages.MainPage.skmt.ExecQuery2($"select  CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_IMG from ${Starter.tabla} where CAT_GP_PRECIO > 0 AND  CAT_GP_ALMACEN > 0 and CAT_GP_TIPOPROD = ? AND CAT_GP_TIPO = ? AND CAT_GP_SUBTIPO = ?  AND CAT_GP_ID NOT IN (SELECT PE_PROID FROM PEDIDO WHERE PE_CLIENTE IN (Select cuenta from cuentaa) )"$, Array As String(Value, marca, tipo))
	Else
		LogColor("Catalogo", Colors.red)
		c2=B4XPages.MainPage.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_IMG, CAT_GP_TIPOPROD, CAT_GP_INICIATIVA from ${Starter.tabla} where CAT_GP_PRECIO > 0 AND CAT_GP_ALMACEN > 0 and CAT_GP_TIPOPROD <> 'PROMOS' "$)
	End If
	If Value = "CATALOGO" Then
		lv_catalogos.Visible = False
		lv_promos.Visible = False
		lfila.text = "CATALOGO"
		Log("PGS")
		ProgressDialogShow("Cargando catalogo ...")
		Sleep(100)
		Private inicioContador As String = DateTime.Now
		llenaCatalogo(False)
		clv_prods_ll.AsView.Visible = True
		Log("PGH")
		LogColor("TIEMPO DE PROCESO DEL CATALOGO: " & ((DateTime.Now-inicioContador)/1000), Colors.Red)
		ProgressDialogHide
		c2.Close
	Else
		clv_prods_ll.AsView.Visible = False
		lv_promos.Visible = True
		lv_catalogos.Visible = False
		lv_promos.Clear
		Dim label1 As Label
		label1 = lv_promos.TwoLinesLayout.Label
		label1.TextSize = 15
		label1.TextColor = Colors.Black
		Dim label2 As Label
		label2 = lv_promos.TwoLinesLayout.SecondLabel
		label2.TextSize = 15
		label2.TextColor = Colors.Black
		Dim label13 As Label
		label13 = lv_promos.TwoLinesAndBitmap.Label
		label13.TextSize = 15
		label13.TextColor = Colors.Black
		Dim label14 As Label
		label14 = lv_promos.TwoLinesAndBitmap.SecondLabel
		label14.TextSize = 15
		label14.TextColor = Colors.Black
		lfila.text = "PROMOS"
		If c2.RowCount > 0 Then
			For i=0 To c2.RowCount -1
				c2.Position=i
				Private tm As Map = Subs.procesaPromocion(c2.GetString("CAT_GP_ID"), clienteId)
				If tm.Get("status") = "ok" Then 'Solo muestrala si hay producto.
					lv_promos.AddTwoLines(c2.GetString("CAT_GP_NOMBRE"),"# " & c2.GetString("CAT_GP_ALMACEN") & " $ " & c2.GetString("CAT_GP_PRECIO") & " F:" & tm.Get("mp").As(Map).Get("prodsFijosCant") & " V:" & tm.Get("mp").As(Map).Get("prodsVariablesCant"))
				End If
			Next
		End If
		c2.Close
	End If
	entro = "4"
End Sub

Sub lv_promos_ItemClick (Position As Int, Value As Object)
	clv_prods_ll.AsView.Visible = False
	Dim cliente As C_Cliente = B4XPages.GetPage("Cliente")
'	Log($"Entro=${entro}, value=${Value}, cuenta=${cliente.cuenta}"$)
	If Value = "PROMOS" And cliente.cuenta <> "N" Then
		entro = "3"
		marca = "PROMOS"
		tipo = "PROMOS"
	Else if Value = "PROMOS" And cliente.cuenta = "N"  Then
		entro = "5"
		B4XPages.ShowPage("Cliente")
	End If
	If entro = "3" Then
		'xxxxxxxxxxxxxxxxxxxxx
	Else If entro = "4" Then
'		Log("Entro = 4")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from PROID")
		B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO PROID VALUES (?)", Array As Object(Value))
		Dim promos As C_Promos = B4XPages.GetPage("Promos")
		promos.laPromo = Subs.traeProdIdDeBD.Get("id")
		promos.elCliente = Subs.traeUsuarioDeBD
		B4XPages.ShowPage("Promos")
	End If
End Sub

'Generamos la lista de productos.
Sub llenaCatalogo(subtipo1 As String)
'	Log("LlenaCatalogo")
'	Private c2 As Cursor
'	c2=B4XPages.MainPage.skmt.ExecQuery2("select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_IMG, CAT_GP_TIPOPROD, CAT_GP_INICIATIVA from cat_gunaprod where CAT_GP_PRECIO > 0 AND CAT_GP_ALMACEN > 0 and CAT_GP_TIPOPROD <> 'PROMOS'  and CAT_GP_SUBTIPO = ? ", Array As String(subtipo1))
'	Private bgColor, textColor As Int
'	If c2.RowCount > 0 And clv_productos.Size <> c2.RowCount Then
'		clv_productos.Clear : Log("limpiamos productos")
'		For i=0 To c2.RowCount -1
'			c2.Position=i
'			If c2.GetString("CAT_GP_TIPOPROD") = "PRIORITARIO" Then
'				bgColor = Colors.RGB(255, 212, 163) 'naranja
'			Else If c2.GetString("CAT_GP_TIPOPROD") = "COMPLEMENTARIO" Then
'				bgColor = Colors.RGB(177, 200, 249)'azul
'			else If c2.GetString("CAT_GP_TIPOPROD") = "CATALOGO REGULAR" Then
'				bgColor = Colors.White
'			else If c2.GetString("CAT_GP_TIPOPROD") = "ESTRATEGICO" Then
'				bgColor = Colors.RGB(241, 255, 163) 'amarillo
'			End If
'			textColor = Colors.Black
'			clv_productos.Add(CreateListItem(c2.GetString("CAT_GP_NOMBRE"), c2.GetString("CAT_GP_PRECIO"), c2.GetString("CAT_GP_ALMACEN"), clv_productos.AsView.Width, 60dip, bmp, c2.GetString("CAT_GP_ID"), bgColor, textColor), c2.GetString("CAT_GP_NOMBRE"))
'		Next
'	End If
'	c2.Close
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
'	BACK key pressed
'	Return True To close, False To cancel
	If l_info.Visible Then
		l_info.Visible = False
		Return False
	else if p_vistaPreviaTrans.Visible Then
		p_vistaPreviaTrans.Visible = False
		Return False
	else if lv_promos.visible Then
		lv_promos.Visible = False
		lv_catalogos.Visible = True
		p_botonesVenta.Visible = False
		l_total.Visible = False
		l_totProds.Visible = False
		Return False
	else if clv_prods_ll.AsView.Visible Then
		lfila.text = "CATALOGO"
		clv_prods_ll.AsView.Visible = False
		lv_subtipo.Visible = False
		p_botonesVenta.Visible = False
		l_total.Visible = False
		l_totProds.Visible = False
		lv_catalogos.Visible = True
		Return False
'	else if lv_subtipo.Visible  Then
'		lfila.text = "TIPO"
'		lv_subtipo.Visible = False
'		lv_tipo.Visible = False
'		Return False
'	else if lv_tipo.Visible Then
'		lfila.text = "CATALOGO"
'		lv_tipo.Visible = False
'		lv_catalogos.Visible = True
'		Return False
	else If entro = "4" Then
		entro = "3"
		B4XPage_Appear
		Return True
	Else If entro = "3" Then
		B4XPages.ShowPage("Cliente")
		Return False
	Else
		B4XPages.ShowPage("Cliente")
		Return False
	End If
End Sub



Sub b_QR_Click
	If ciclo = 1 Then
		ciclo = 2
		ya_entro  = "0"
		B4XPage_Appear
	else if ciclo = 2 Then
		ciclo = 3
		ya_entro  = "0"
		B4XPage_Appear
	else if ciclo = 3 Then
		ciclo = 4
		ya_entro  = "0"
		B4XPage_Appear
	else if ciclo = 4 Then
		ciclo = 5
		ya_entro  = "0"
		B4XPage_Appear
	else if ciclo = 5 Then
		ciclo = 1
		ya_entro  = "0"
		B4XPage_Appear
	End If
End Sub

'****************************************************************************
'***************** PARA EL MAS/MENOS *************************************
'****************************************************************************
Sub CreateListItem(Text As String, precioU As String, inv As Int, Width As Int, Height As Int, img As Bitmap, prodId As String, bc As Int, tc As Int) As Panel
'	Dim p As B4XView = xui.CreatePanel("")
'	p.SetLayoutAnimated(0, 0, 0, Width, Height)
'	p.LoadLayout("prodItem")
'	p_prods.Color = bc
'	l_prodX.TextColor = tc
'	l_prodX.TextSize = 15
'	p_prods.Height = Height
'	l_prodX.Height = Height
'	l_prodX.Text = Text&CRLF&"# " & inv & " $ " & precioU
'	l_prodX.Tag = $"ID: ${prodId}${CRLF}${Text}${CRLF}Precio: $$1.2{precioU}${CRLF}Inv: ${inv} pzs"$
'	l_pCant.Tag = precioU&"|"&inv&"|"&prodId
'	et_pCant.Tag = precioU&"|"&inv&"|"&prodId
'	et_pCant.BringToFront
'	Return p
End Sub

Sub b_prodMenos_Click
	etCantHasFocus = False
	Root.RequestFocus
'	LogColor("b_prodMenos_Click", Colors.Magenta)
	Dim index As Int = clv_prods_ll.GetItemFromView(Sender)
	Dim pnl0 As B4XView = clv_prods_ll.GetPanel(index)
	Dim pnl As B4XView = pnl0.GetView(0)
	Dim laCant As B4XView = pnl.GetView(2).GetView(2)
	Dim lProdX As B4XView = pnl.GetView(1)
'	Log($"precio|stock:${laCant.tag}"$)
	If laCant.Text = "" Then laCant.Text = 0
'	Log("lacant.text="&laCant.text)
	laCant.Text = $"${NumberFormat2(laCant.Text-1,0,0,0,False)}"$
	If laCant.Text < 0 Then laCant.Text = 0
	Private tmpMap As Map = clv_prods_ll.GetValue(index).As(Map)
	Private precio As String=clv_prods_ll.GetValue(index).As(Map).Get("precio")
	Private id As String=clv_prods_ll.GetValue(index).As(Map).Get("id")
	Private tmpMap As Map = CreateMap("precio":precio, "cant":laCant.Text, "almacen":Subs.traeAlmacen)
	Private nombreX As String = Subs.traeProdNombre(id)
	Log(tmpMap)
'	prodsMap.Put(id, tmpMap)
	If laCant.Text = 0 Then prodsMap.Remove(id)
	LogColor("prodsMap="&prodsMap, Colors.blue)
'	(Subs.traeAlmacen, p1.Get("precio"), p1.Get("cant"), pn, p, clienteId, Subs.traeFecha, Subs.traeUsuarioDeBD, rutaUsuario, 0, B4XPages.MainPage.tipo_venta)
	Log($"${Subs.traeAlmacen}, ${precio}, ${laCant.text}, ${Subs.traeProdNombre(id)}, ${id}, ${clienteId}"$)
	Subs.actualizaProducto(Subs.traeAlmacen, precio, laCant.text, Subs.traeProdNombre(id), id, clienteId, Subs.traeFecha, Subs.traeUsuarioDeBD, rutaUsuario, 0, B4XPages.MainPage.tipo_venta)
	cuentaProds
	LogColor("prodsMap="&prodsMap, Colors.blue)
	Log($"Total Prods: ${totalProds}, Total Compra: $$1.2{totalCompra}"$)
	If 1 = 1 Then
		Private cs As CSBuilder
		cs.Initialize
		Private o As Cursor = Starter.skmt.ExecQuery($"select CAT_GP_ALMACEN from ${Starter.tabla} where CAT_GP_ID = '${id}'"$)
		Private invActualizado As String = "0"
		If o.RowCount > 0 Then
			o.Position = 0
			invActualizado = o.GetString("CAT_GP_ALMACEN")
		End If
		If 2 = 2 Then lProdX.Text = cs.Color(Colors.red).append(nombreX).pop.Append(CRLF).Append("Existencias: " & invActualizado).Color(0xFF017F01).Append($"   $${NumberFormat2(precio, 1, 2, 2, False)}"$).Popall
'		Log(lProdX.Text)
	End If
	If Subs.totalPedido < 1 Then laCant.Text = "0"
	invTotal = laCant.Text + Subs.traeinventario(id)
'	LogColor("InvTotal PRODMAS: " & invTotal, Colors.Red)
End Sub

Sub b_prodMas_Click
	etCantHasFocus = False
	Root.RequestFocus
'	LogColor("b_prodMas_Click", Colors.Magenta)

	Dim index As Int = clv_prods_ll.GetItemFromView(Sender)
	Dim pnl0 As B4XView = clv_prods_ll.GetPanel(index)
	Dim pnl As B4XView = pnl0.GetView(0)
	Dim laCant As B4XView = pnl.GetView(2).GetView(2)
	Dim lProdX As B4XView = pnl.GetView(1)

'	Private tmpMap As Map = clv_prods_ll.GetValue(index).As(Map)
	Private precio As String=clv_prods_ll.GetValue(index).As(Map).Get("precio")
	Private inv As String=clv_prods_ll.GetValue(index).As(Map).Get("almacen")
	Private existencias As String = clv_prods_ll.GetValue(index).As(Map).Get("almacen")
	Log($"Existencias: ${existencias}"$)
	If laCant.Text = "" Then laCant.Text = 0
	Private id As String=clv_prods_ll.GetValue(index).As(Map).Get("id")
'	If laCant.Text + 1 <= inv Then
''		Log(NumberFormat2(laCant.Text+1,0,0,0,False))
'		laCant.Text = $"${NumberFormat2(laCant.Text+1,0,0,0,False)}"$
''		Private precio As String=clv_prods_ll.GetValue(index).As(Map).Get("precio")
'		Private id As String=clv_prods_ll.GetValue(index).As(Map).Get("id")
''		Private tmpMap As Map = CreateMap("precio":precio, "cant":laCant.Text, "almacen":Subs.traeAlmacen)
''		Log(tmpMap)
''		prodsMap.Put(id, tmpMap)
''		LogColor(prodsMap, Colors.blue)
'	End If
'	Log("Cantidad + exis   " & (laCant.Text + existencias))
'	Log( (laCant.Text + 1 <= (laCant.Text + existencias)))
'	Log("inventario   "&Subs.traeinventario(id))
'	Log((Subs.totalPedido - precio > 1))
'	Log((Subs.totalPedido))
'	Log(precio)
	
	
	If Subs.traeinventario(id) > 0 And (laCant.Text <= (laCant.Text + Subs.traeinventario(id))) Then 'And (Subs.totalPedido - precio > 1)
'		Log(clv_prods_ll.GetValue(index).As(Map))
		clv_prods_ll.GetValue(index).As(Map).Put("almacen", (inv - 1))
		inv = inv - 1
'			laCant.Text = $"$1.0{laCant.Text+1}"$
		laCant.Text = NumberFormat2((laCant.Text + 1), 1, 0, 0, False)
'			Log(clv_prods_ll.GetValue(index).As(Map))
	End If
	Private nombreX As String = Subs.traeProdNombre(id)
'	Subs.actualizaProducto(Subs.traeAlmacen, laCant.text, id, clienteId)

	

	Subs.actualizaProducto(Subs.traeAlmacen, precio, laCant.text, Subs.traeProdNombre(id), id, clienteId, Subs.traeFecha, Subs.traeUsuarioDeBD, rutaUsuario, 0, B4XPages.MainPage.tipo_venta)
	cuentaProds
'	Log($"Total Prods: ${totalProds}, Total Compra: $$1.2{totalCompra}"$)
	If 1 = 1 Then	
		Private cs As CSBuilder
		cs.Initialize
		Private o As Cursor = Starter.skmt.ExecQuery($"select CAT_GP_ALMACEN from ${Starter.tabla} where CAT_GP_ID = '${id}'"$)
		Private invActualizado As String = "0"
		If o.RowCount > 0 Then
			o.Position = 0
			invActualizado = o.GetString("CAT_GP_ALMACEN")
		End If
		If 2 = 2 Then lProdX.Text = cs.Color(Colors.red).append(nombreX).pop.Append(CRLF).Append("Existencias: " & invActualizado).Color(0xFF017F01).Append($"   $${NumberFormat2(precio, 1, 2, 2, False)}"$).Popall
'		Log(lProdX.Text)
	End If
	invTotal = laCant.Text + Subs.traeinventario(id)
'	LogColor("InvTotal PRODMAS: " & invTotal, Colors.Red)
End Sub

Private Sub et_pCant_FocusChanged (HasFocus As Boolean)
	LogColor($"focus changed=${HasFocus}"$, Colors.Magenta)
	If et_pCant.Text = "" Then et_pCant.Text = "0"
	Dim index As Int = clv_prods_ll.GetItemFromView(Sender)
	Dim pnl0 As B4XView = clv_prods_ll.GetPanel(index)
	Dim pnl As B4XView = pnl0.GetView(0)
	Dim laCant As B4XView = pnl.GetView(2).GetView(2)
	Private id As String=clv_prods_ll.GetValue(index).As(Map).Get("id")
	If laCant.Text = "" Then laCant.Text = "0"
	etCantHasFocus = HasFocus
	
	invTotal = laCant.Text + Subs.traeinventario(id)
'	LogColor("InvTotal PRODMAS: " & invTotal, Colors.Red)
	
	cuentaProds
End Sub

Private Sub et_pCant_TextChanged (Old As String, New As String)
	Log(etCantHasFocus)
'	Log("InvTotal: " & invTotal)
	If etCantHasFocus = True Then
		LogColor($"txt changed: ${Old}|${New}, hasfocus=${etCantHasFocus}"$,Colors.Magenta)
		Dim index As Int = clv_prods_ll.GetItemFromView(Sender)
		Dim pnl0 As B4XView = clv_prods_ll.GetPanel(index)
		Dim pnl As B4XView = pnl0.GetView(0)
		Dim laCant As B4XView = pnl.GetView(2).GetView(2)
		Dim lProdX As B4XView = pnl.GetView(1)
		Private id As String=clv_prods_ll.GetValue(index).As(Map).Get("id")
		Private precio As String=clv_prods_ll.GetValue(index).As(Map).Get("precio")
		Private inv As String=clv_prods_ll.GetValue(index).As(Map).Get("almacen")
		Private inv As String=Subs.traeinventario(id)
		Private nombreX As String = Subs.traeProdNombre(id)
		
		
		
		If(New = "" Or New = Null Or New = "-") Then New = 0
'		If New < 0 Then New = 0
		If(New > invTotal) Then
			Sender.As(EditText).text = invTotal
		End If
		'	Log($"inventario=${inv}"$)
		
		If New = "" Then New = 0
		If laCant.Text = "" Then laCant.Text = 0
		If Not(Old = "0" And New = "") And laCant.Text <> Null And laCant.Text <> "" And etCantHasFocus Then
			Log("actualizamos producto")
			Subs.actualizaProducto(Subs.traeAlmacen, precio, laCant.text, Subs.traeProdNombre(id), id, clienteId, Subs.traeFecha, Subs.traeUsuarioDeBD, rutaUsuario, 0, B4XPages.MainPage.tipo_venta)
			cuentaProds
		End If
		
'		If New <> "" And New.SubString2(0,0) = "0" Then
'			New.SubString(1)
'		End If
'		If New <> "" And New.SubString(1) <> "" Then
'			Log(New.SubString(1))
'			New = New.SubString(1)
'			laCant.Text = New.SubString(1)
'			Log(laCant.Text)
'		End If
		
		If 1 = 1 Then
			Private cs As CSBuilder
			cs.Initialize
			Private o As Cursor = Starter.skmt.ExecQuery($"select CAT_GP_ALMACEN from ${Starter.tabla} where CAT_GP_ID = '${id}'"$)
			Private invActualizado As String = "0"
'			If o.RowCount > 0 Then
				o.Position = 0
				invActualizado = Subs.traeinventario(id)
				Log(Subs.traeinventario(id))
'			End If
		
			If New = "" Then New = 0
			lProdX.Text = cs.Color(Colors.red).append(nombreX).pop.Append(CRLF).Append("Existencias: " & (Subs.traeinventario(id))).Color(0xFF017F01).Append($"   $${NumberFormat2(precio, 1, 2, 2, False)}"$).Popall
		End If
	End If
End Sub

Sub cuentaProds
'	LogColor($"Productos de la orden: ${c_prods.GetString("cantProds")}, Total: ${c_prodsX.GetString("costoTotal")}"$, Colors.red)
	Log("===========================")
	Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery($"select sum(PE_COSTO_TOT) as total, sum(PE_CANT) as cant from PEDIDO where PE_CLIENTE = '${clienteId}'"$)
'	LogColor("TIEMPO cuentaProds =" & ((DateTime.Now-inicioContador)/1000), Colors.Red)
'	LogColor(prodsMap, Colors.Magenta)
	p_botonesVenta.Visible = True
	p_botonesVenta.BringToFront
	c.Position=0
	Log($"Total Prods: ${c.GetString("cant")}, Total Compra: $$1.2{c.GetString("total")}"$)
	c.Close
'	Log($"HAY PEDIDO: ${hayPedido}"$)
End Sub

Sub b_terminar1_Click
'	Log("b_terminar1_Click")
'	ya_entro = "0" : Log("ya_entro=1")
	B4XPages.MainPage.skmt.ExecNonQuery2("delete from PEDIDO WHERE PE_PRONOMBRE = ? ", Array As Object("N/A") )
	
	lv_promos.Visible = False
	clv_prods_ll.AsView.Visible = False
	lv_catalogos.Visible = True
	lv_prodsPedido.Clear
	lv_prodsPedido.TwoLinesLayout.Label.Height = 35dip
	lv_prodsPedido.TwoLinesLayout.SecondLabel.Height = 25dip
	Private c_prods As Cursor=B4XPages.MainPage.skmt.ExecQuery("select PE_PRONOMBRE,PE_COSTO_TOT, PE_CANT, PE_FOLIO, PE_CEDIS FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) order by PE_CEDIS, PE_PRONOMBRE")
	If c_prods.RowCount > 0 Then
		Private cs As CSBuilder
		
		vamoaver.Initialize
		For i=0 To c_prods.RowCount -1
			cs.Initialize
			c_prods.Position=i
			Dim label1 As Label
			label1 = lv_prodsPedido.TwoLinesLayout.Label
			label1.TextSize = 15
			label1.TextColor = Colors.Black
			label1.color = Colors.White
			Private textColor As Int = Colors.black
			
			If c_prods.GetString("PE_FOLIO") = "VENTA" Then
				textColor = Colors.RGB(48,3,195)
			Else If c_prods.GetString("PE_FOLIO") = "PREVENTA" Or c_prods.GetString("PE_FOLIO") = "ABORDO" Then
				textColor = Colors.RGB(166,0,0)
			End If
			If Not(IsNumber(c_prods.GetString("PE_CEDIS"))) And c_prods.GetString("PE_FOLIO") = "VENTA" Then
				textColor = Colors.RGB(154,131,231) 'Si es promo, cambiamos el color del texto.
			Else If Not(IsNumber(c_prods.GetString("PE_CEDIS"))) And c_prods.GetString("PE_FOLIO") = "PREVENTA" Then
				textColor = Colors.RGB(255,111,111) 'Si es promo, cambiamos el color del texto.
			End If
			Dim label2 As Label
			label2 = lv_prodsPedido.TwoLinesLayout.SecondLabel
			label2.TextSize = 10
			label2.TextColor = Colors.Blue
			
			lv_prodsPedido.AddTwoLines(cs.Color(textColor).append(c_prods.GetString("PE_PRONOMBRE")).pop,"Cantidad #"& c_prods.GetString("PE_CANT")& " SubTotal $"& c_prods.GetString("PE_COSTO_TOT")& " Folio "& c_prods.GetString("PE_FOLIO"))
			vamoaver.Add(c_prods.GetString("PE_FOLIO"))
			folio = c_prods.GetString("PE_FOLIO")
		Next
'		c=B4XPages.MainPage.skmt.ExecQuery("select pc_noart, pc_monto from pedido_cliente where pc_cliente in (Select CUENTA from cuentaa)")
'		c = B4XPages.MainPage.skmt.ExecQuery("SELECT SUM (PE_CANT) AS CANTIDAD FROM PEDIDO WHERE PE_PROID not like 'PRO%' and PE_CLIENTE IN  (Select CUENTA from cuentaa)")
		c = B4XPages.MainPage.skmt.ExecQuery("select sum(PE_CANT) as PC_NOART, sum (PE_COSTO_TOT) as PC_MONTO from PEDIDO where PE_CLIENTE in (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP )")
'		r = B4XPages.MainPage.skmt.ExecQuery("SELECT SUM (PE_COSTO_TOT) AS MONTO FROM PEDIDO WHERE PE_CLIENTE IN  (Select CUENTA from cuentaa)")
		c.Position=0
'		r.Position = 0
		l_cant.Text = c.GetString("PC_NOART")
		l_total2.Text = c.GetString("PC_MONTO")
		c.Close
'		r.Close
	End If
	c_prods.Close
	p_vistaPreviaTrans.Width = Root.Width
	p_vistaPreviaTrans.Height = Root.Height
	Subs.centraPanel(p_vistaPrevia, Root.Width)
	If Subs.pedidoGuardado Then b_rechazar.Enabled = False Else b_rechazar.Enabled = True
	p_vistaPrevia.Visible=True
	p_vistaPreviaTrans.Visible=True
End Sub

Private Sub b_continuar_Click
	Log("b_continuar_Click")
	cuentaProds
	Private p1 As Map
	Log($"prodsMap=${prodsMap}"$)
	For Each p As String In prodsMap.Keys
		p1 = prodsMap.Get(p)
		Log(p & "|" & p1)
		Private pn As String = Subs.traeProdNombre(p)
		Subs.guardaProductoSinGestion(Subs.traeAlmacen, p1.Get("precio"), p1.Get("cant"), pn, p, clienteId, Subs.traeFecha, Subs.traeUsuarioDeBD, rutaUsuario, 0, B4XPages.MainPage.tipo_venta)
	Next
	Log("promos-inv, prods-inv, cat-vis")
	lv_promos.Visible = False
	clv_prods_ll.AsView.Visible = False
	lv_subtipo.Visible = False
	lv_tipo.Visible = False
	lv_catalogos.Visible = True
	Log("Continuar")
	Dim m As Map = Subs.traeTotalesClienteActual
	prodsPedidoActual = m.Get("productos")
	montoPedidoActual = m.Get("monto")
End Sub

Private Sub l_prodX_LongClick
	Log("longclic = "&Sender.as(Label).tag)
	l_info.Text = Sender.as(Label).tag
	l_info.Visible = True
End Sub

Private Sub l_info_Click
	l_info.Visible = False
End Sub

Private Sub lv_promos_ItemLongClick (Position As Int, Value As Object)
	Log("Promo longclic = "&Value)
	Private id As String = ""
	Dim c As Cursor = B4XPages.MainPage.skmt.ExecQuery($"select CAT_GP_ID from ${Starter.tabla} where CAT_GP_TIPO = 'PROMOS' and CAT_GP_NOMBRE = '${Value}'"$)
	If c.RowCount > 0 Then
		c.Position = 0
		id = c.GetString("CAT_GP_ID")
	End If
	l_info.Text = $"ID: ${id}${CRLF}${Value}"$
	l_info.Visible = True
End Sub

Private Sub b_buscar_Click
	forzarBusqueda = True
	Busca_TextChanged("",BUSCA.Text)
End Sub

Private Sub lv_tipo_ItemClick (Position As Int, Value As Object)
'	lfila.text = "SUB TIPO"
'	lv_tipo.Visible = False
'	lv_subtipo.Height = Root.Height * 0.7
'	lv_subtipo.Visible = True
'	Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select distinct CAT_GP_SUBTIPO from cat_gunaprod where CAT_GP_TIPO = ? order by CAT_GP_SUBTIPO", Array As String(Value))
'	If c.RowCount > 0 Then
'		Dim label1 As Label
'		label1 = lv_subtipo.SingleLineLayout.Label
'		label1.TextSize = 17
'		label1.TextColor = Colors.Black
'		lv_subtipo.Clear
'		For i=0 To c.RowCount-1
'			c.Position=i
'			lv_subtipo.AddSingleLine(c.GetString("CAT_GP_SUBTIPO"))
'		Next
'	End If
'	c.Close
End Sub

Private Sub lv_subtipo_ItemClick (Position As Int, Value As Object)
'	lfila.text = "SUB TIPO"
'	LogColor("Catalogo", Colors.red)
'	lv_catalogos.Visible = False
'	lv_subtipo.Visible = False
'	lv_promos.Visible = False
'	lfila.text = "CATALOGO"
'	ProgressDialogShow("Cargando catalogo ...")
'	Sleep(100)
'	Private inicioContador As String = DateTime.Now
'	llenaCatalogo(Value)
'	clv_prods_ll.AsView.Visible = True
'	LogColor("TIEMPO DE PROCESO DEL CATALOGO: " & ((DateTime.Now-inicioContador)/1000), Colors.Red)
'	ProgressDialogHide
End Sub

Private Sub p_vistaPreviaTrans_Click

End Sub

Private Sub b_rechazar_Click
'	If folio <> "" Then
		result =  Msgbox2($"Seguro que desea borrar el pedido completo?${CRLF}Haciendo clic largo sobre un producto se pueden borrar articulos independientes."$,"Rechazar Pedido", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'ignore
		If result = DialogResponse.POSITIVE Then
			Subs.borraPedidoClienteActual
			prodsMap.Initialize
			B4XPages.MainPage.promos.promosMap.Initialize
'			Log("Llamamos LlenaProdsLL")
'			LlenaProdsLL(Null)
			clv_prods_ll.Clear
			Log("Positivo")
			B4XPages.ShowPage("Cliente")
		Else
			Log("NO Positivo")
			p_vistaPreviaTrans.Visible = False
		End If
'	Else
'		Msgbox("CLIENTE YA SE TRANSMITIO, FAVOR DE LLAMAR A SOPORTE PARA ASISTENCIA","AVISO") 'ignore
'	End If
	p_vistaPreviaTrans.Visible=False
	B4XPages.ShowPage("Cliente")
End Sub

Private Sub b_aceptar_Click
	p_vistaPreviaTrans.Visible=False
	B4XPages.ShowPage("Cliente")
End Sub

Private Sub lv_prodsPedido_ItemLongClick (Position As Int, Value As Object)
	Private sDate,sTime, clie_id, usuario As String
	If Not(Subs.pedidoGuardado) Then
		result =  Msgbox2("Seguro que desea borrar este articulo?","Borrar Articulo", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'ignore
		If result = DialogResponse.POSITIVE Then
			c=B4XPages.MainPage.skmt.ExecQuery2("select PE_PROID,PE_CANT, PE_FOLIO FROM PEDIDO where pe_pronombre = ? and pe_cliente in (Select CUENTA from cuentaa) ", Array As String(Value))
			c.Position=0
			Log(vamoaver.Get(Position))
			If vamoaver.Get(Position) = "VENTA" Then
				Log("CAT_GUNAPROD2")
				Log(Position)
				Log(Value)
				Starter.tabla = "CAT_GUNAPROD2"
			Else
				Log("CAT_GUNAPROD")
				Log(Position)
				Log(Value)
				Starter.tabla = "CAT_GUNAPROD"
			End If
'			B4XPages.MainPage.skmt.ExecNonQuery2($"update ${Starter.tabla} set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_id = ?"$, Array As Object(c.GetString("PE_CANT"),c.GetString("PE_PROID")))
'			Log(c.GetString("PE_CANT"))
			B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO  INVENT_X_ENVIAR (ALMACEN , PROID , CANTIDAD ) VALUES(?,?,?) ", Array As Object (Subs.traeAlmacen,c.GetString("PE_PROID"),c.GetString("PE_CANT")* -1))
			c2=B4XPages.MainPage.skmt.ExecQuery2($"select count(*) AS CUANTOS from ${Starter.tabla} where  CAT_GP_ID in (select pe_cedis from pedido where pe_pronombre = ? and pe_cliente in (Select CUENTA from cuentaa)) and CAT_GP_CLASIF = 'PROMOS' AND CAT_GP_TIPO = 'PROMOS' AND CAT_GP_SUBTIPO = 'PROMOS'"$, Array As String(Value))
			c2.Position=0
			If c2.GetString("CUANTOS") > 0 Then
				j3 = B4XPages.MainPage.skmt.ExecQuery2("SELECT PE_CEDIS, PE_CANT,PE_PROID, PE_PRONOMBRE FROM PEDIDO WHERE PE_CEDIS IN (SELECT PE_CEDIS FROM PEDIDO WHERE PE_PRONOMBRE = ?)",Array As String(Value))
				Log(j3.RowCount)
				If j3.RowCount > 0 Then
					Log("estoy aqui")
					For i = 0 To j3.RowCount -1
						Log("aqui tronare?")
						j3.Position = i
						B4XPages.MainPage.skmt.ExecNonQuery($"update ${Starter.tabla} set cat_gp_almacen = cat_gp_almacen + ${j3.GetString("PE_CANT")} where cat_gp_id = '${j3.Getstring("PE_PROID")}'"$)
						B4XPages.MainPage.skmt.ExecNonQuery2("delete from pedido where  pe_cedis in (select pe_cedis from pedido where pe_pronombre = ?) and pe_cliente in (Select CUENTA from cuentaa) AND PE_FOLIO = ?", Array As Object(j3.GetString("PE_PRONOMBRE"), c.GetString("PE_FOLIO")))
					Next
				End If
				j3.Close
			Else
				B4XPages.MainPage.skmt.ExecNonQuery($"update ${Starter.tabla} set cat_gp_almacen = cat_gp_almacen + ${c.GetString("PE_CANT")} where cat_gp_id = '${c.Getstring("PE_PROID")}'"$)
				B4XPages.MainPage.skmt.ExecNonQuery2("delete from pedido where  pe_pronombre = ?  and pe_cliente in (Select CUENTA from cuentaa) AND PE_FOLIO = ?", Array As Object(Value, c.GetString("PE_FOLIO")))
			End If
			c.Close
			c2.Close
			DateTime.DateFormat = "MM/dd/yyyy"
			sDate=DateTime.Date(DateTime.Now)
			sTime=DateTime.Time(DateTime.Now)
			c=B4XPages.MainPage.skmt.ExecQuery("Select CUENTA from cuentaa")
			c.Position=0
			clie_id = c.GetString("CUENTA")
			c=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
			c.Position=0
			usuario = c.GetString("USUARIO")
			c=B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, count(*) as CUANTOS FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
			c.Position=0
			If c.GetString("CUANTOS") > 0 Then
				Log("aqui5")
				B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
				B4XPages.MainPage.skmt.ExecNonQuery2("insert into pedido_cliente(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT) VALUES (?,?,?,?,?,?,?)", Array As Object(clie_id, sDate & sTime, usuario, c.GetString("CANT_CLIE"),c.GetString("TOTAL_CLIE"), B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps))
				B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
				B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 0  where CAT_CL_CODIGO In (select cuenta from cuentaa)")
				Private h As Cursor = B4XPages.MainPage.skmt.ExecQuery("select sum(PE_CANT) as PC_NOART, sum (PE_COSTO_TOT) as PC_MONTO from PEDIDO where PE_CLIENTE in (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP )")
				h.Position=0
				l_cant.Text = h.GetString("PC_NOART")
				l_total2.Text = h.GetString("PC_MONTO")
				h.Close
			Else
				Log("aqui6")
				B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
				B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 0  where CAT_CL_CODIGO In (select cuenta from cuentaa)")
				Private h As Cursor = B4XPages.MainPage.skmt.ExecQuery("select sum(PE_CANT) as PC_NOART, sum (PE_COSTO_TOT) as PC_MONTO from PEDIDO where PE_CLIENTE in (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP )")
				h.Position=0
				l_cant.Text = 0
				l_total2.Text = 0
				h.Close
			End If
			b_terminar1_Click
		End If
	Else
		ToastMessageShow("Esta venta ya esta guardada, no se puede editar ni borrar.", False)
	End If
End Sub

Private Sub clv_prods_ll_ItemClick (Index As Int, Value As Object)
	
End Sub

Sub l_prodx_click
	Dim index As Int = clv_prods_ll.GetItemFromView(Sender)
	Private p0 As B4XView = clv_prods_ll.GetPanel(index)
	Private p As B4XView = p0.GetView(0)
	Private cant1 As B4XView = p.GetView(2).GetView(2)
	Dim index As Int = clv_prods_ll.GetItemFromView(Sender)
'	Log(clv_prods_ll.GetValue(index))
	Log(cant1.Text)
End Sub

Private Sub clv_prods_ll_VisibleRangeChanged (FirstIndex As Int, LastIndex As Int)
'	Private inicioContador As String = DateTime.Now
'	Log($"clv_prods_ll_VisibleRangeChanged : ${FirstIndex}, ${LastIndex} "$)
	Dim ExtraSize As Int = 15 'List size
	For i = Max(0, FirstIndex - ExtraSize) To Min(LastIndex + ExtraSize, clv_prods_ll.Size - 1)
		Dim Pnl As B4XView = clv_prods_ll.GetPanel(i)
		If i > FirstIndex - ExtraSize And i < LastIndex + ExtraSize Then
'				Log(listaRenglones)
			If Pnl.NumberOfViews = 0 Then 'Add each item/layout to the list/main layout
				Pnl.LoadLayout("proditem")
				p_prods.Width = Root.Width * 0.92
				p_botMasMen.Left = p_prods.Width - (p_botMasMen.Width + 5)
				p_prods.Height = 62dip
				b_prodMenos.Height = 50dip
				b_prodMas.Height = 50dip
				et_pCant.Height = 51dip
				l_pCant.Height = 44dip
				l_pCant.Top = l_pCant.Top + 8
				Pnl.Height = p_prods.Height
				Private cs As CSBuilder
				cs.Initialize
				l_prodX.SetTextSizeAnimated(0, 13)
				If clv_prods_ll.GetValue(i).As(Map).Get("cant") <> Null And clv_prods_ll.GetValue(i).As(Map).Get("cant") > 0 Then
					p_prods.Color=0xFFE2EEFF
					et_pCant.TextColor=Colors.Red
					If Subs.pedidoGuardado Then
						Log("YA SE GUARDO")
						et_pCant.Enabled = False
'						b_prodMas.Enabled = False
						b_prodMenos.Enabled = False
					End If
				End If
				
				Private precio As String=NumberFormat2(clv_prods_ll.GetValue(i).As(Map).Get("precio").As(Double),1,2,2,False)
				If clv_prods_ll.GetValue(i).As(Map).Get("cant") <> Null Then et_pCant.Text = clv_prods_ll.GetValue(i).As(Map).Get("cant")
				l_prodX.Text = cs.Color(Colors.red).append(clv_prods_ll.GetValue(i).As(Map).Get("prod")).pop.append(CRLF).Append("Existencias: " & clv_prods_ll.GetValue(i).As(Map).Get("almacen")).Color(0xFF017F01).Append($"   $${precio}"$).Popall
			End If
'				Log($"${i}, ${FirstIndex}, ${LastIndex}, ${Pnl.NumberOfViews}. ${clv_prods_ll.Size}"$)
		Else 'Not visible
			'			If Pnl.NumberOfViews > 0 Then
			'				Pnl.RemoveAllViews 'Remove none visable item/layouts from the list/main layout
			'			End If
		End If
		PCLV.B4XSeekBar1.Value = clv_prods_ll.Size - FirstIndex
'		Log($"Bar value: ${PCLV.B4XSeekBar1.Value}"$)
	Next
End Sub

Sub Busca_TextChanged (Old As String, New As String)
'	Private inicioContador As String = DateTime.Now
	If Not(clv_prods_ll.AsView.Visible) Then clv_prods_ll.AsView.Visible = True
	If (New.Length = 1 Or New.Length = 2) And Not(forzarBusqueda) Then Return
	forzarBusqueda = False
	clv_prods_ll.Clear
	listaProds.Initialize
	listaHints.Initialize
	Sleep(0)
	Dim p As ResultSet = B4XPages.MainPage.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPOPROD from ${Starter.tabla} where CAT_GP_NOMBRE like '%${New}%' and CAT_GP_PRECIO > 0 AND CAT_GP_ALMACEN > 0 and CAT_GP_CLASIF <> 'PROMOS' order by CAT_GP_NOMBRE"$)
	Log("Llamamos LlenaProdsLL")
	LlenaProdsLL(p)
'	Do While p.NextRow
'		Dim tempMap As Map = CreateMap("prod":p.GetString("CAT_GP_NOMBRE"), "precio":p.GetString("CAT_GP_PRECIO"), "almacen":p.GetString("CAT_GP_ALMACEN"), "id":p.GetString("CAT_GP_ID"))
'		listaProds.Add(tempMap)
'		listaHints.Add(p.GetString("CAT_GP_NOMBRE"))
'		Dim Pnl As B4XView = xui.CreatePanel("")
'		Pnl.SetLayoutAnimated(0, 0, 0, clv_prods_ll.AsView.Width, 50dip) 'Panel height + 4 for drop shadow
'		clv_prods_ll.Add(Pnl, tempMap)
'	Loop
'	LogColor(clv_prods_ll.Size, Colors.red)
''	Log(listaProds)
'	p.Close
'	PCLV.B4XSeekBar1.MaxValue = clv_prods_ll.Size
'	PCLV.B4XSeekBar1.MinValue = 0
'	PCLV.B4XSeekBar1.Interval = clv_prods_ll.Size/10
'	PCLV.B4XSeekBar1.Value = clv_prods_ll.Size
'	PCLV.B4XSeekBar1.Update
'	Log($"Min:0, max:${clv_prods_ll.Size}, Interval:${clv_prods_ll.Size/10}"$)
'	LogColor("TIEMPO DE PROCESO DEL TEXTCHANGED: " & ((DateTime.Now-inicioContador)/1000), Colors.Red)
End Sub

Sub LlenaProdsLL(p As ResultSet)
	Log("Iniciamos LlenaProdsLL")
	listaProds.Initialize
	If hayPedido Then 'Si hay pedido obtenemos las cantidades de los productos para agregarlos al CLV.
		Dim cantsMap As Map
		cantsMap.Initialize
		Dim pe As ResultSet = B4XPages.MainPage.skmt.ExecQuery($"select PE_PROID, PE_CANT from PEDIDO where PE_CLIENTE = '${clienteId}' and PE_CEDIS = '${Subs.traeAlmacen}' and PE_FOLIO = '${B4XPages.MainPage.tipo_venta}'"$)
'		LogColor("Ponemos productos de pedido anterior: "&pe.RowCount, Colors.red)
		Do While pe.NextRow
			Private cant As Int = 0
			cantsMap.put(pe.GetString("PE_PROID"), pe.GetString("PE_CANT"))
		Loop
		pe.Close
	End If
'	Log(p.IsInitialized)
	If p.IsInitialized Then
'		Log("YA HAY RESULSET")
	Else
'		Log("NO HAY RESULSET")
LogColor(Starter.tabla,Colors.blue)
'		Dim p As ResultSet = B4XPages.MainPage.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPOPROD from ${Starter.tabla} where CAT_GP_PRECIO > 0 And CAT_GP_ALMACEN > 0 And CAT_GP_CLASIF <> 'PROMOS' order by CAT_GP_NOMBRE"$)
		Dim p As ResultSet = B4XPages.MainPage.skmt.ExecQuery($"select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPOPROD from ${Starter.tabla} where CAT_GP_PRECIO > 0 And CAT_GP_ALMACEN > 0 And CAT_GP_CLASIF <> 'PROMOS' union all select CAT_GP_ID, CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO, CAT_GP_TIPOPROD from ${Starter.tabla} where CAT_GP_PRECIO > 0 And CAT_GP_ALMACEN = 0 And CAT_GP_CLASIF <> 'PROMOS' and cat_gp_id in (select pe_proid from pedido where pe_cliente in (select cuenta from cuentaa)) order by 2"$)
	End If
	
	Do While p.NextRow
		Private cant As Int = 0
		If hayPedido And cantsMap.ContainsKey(p.GetString("CAT_GP_ID")) Then cant = cantsMap.Get(p.GetString("CAT_GP_ID"))
		Dim tempMap As Map = CreateMap("prod":p.GetString("CAT_GP_NOMBRE"), "precio":p.GetString("CAT_GP_PRECIO"), "almacen":p.GetString("CAT_GP_ALMACEN"), "id":p.GetString("CAT_GP_ID"), "cant":cant)
		listaProds.Add(tempMap)
	Loop
	p.Close
'	Log(listaProds)
	PCLV.Commit
	clv_prods_ll.Clear
	Private listaProdsConCant, listaProdsConCantIndex As List
	listaProdsConCant.Initialize
	listaProdsConCantIndex.Initialize
	listaHints.Initialize
	For q=0 To listaProds.Size-1' Sacamos los productos con cantidad previa.
		If listaProds.Get(q).As(Map).Get("cant").As(Int) <> 0 Then
'			Log(listaProds.Get(q).As(Map).Get("cant"))
			listaProdsConCant.Add(listaProds.Get(q))
			listaProdsConCantIndex.Add(q)
		End If
	Next
'	Log(listaProdsConCantIndex)
	Private cont As Int = 0
	For pr0=0 To listaProdsConCant.Size - 1 'Agregamos los productos con cantidad previa.
		Private Pnl As B4XView = xui.CreatePanel("")
		Pnl.SetLayoutAnimated(0, 0, 0, clv_prods_ll.AsView.Width, 63dip)
		clv_prods_ll.Add(Pnl, listaProdsConCant.Get(pr0))
		listaHints.Add(listaProdsConCant.get(pr0).As(Map).Get("prod"))
		cont = cont + 1
	Next
'	LogColor(clv_prods_ll.Size, Colors.red)
'	Log(listaProds.Size)
	For pr=0 To listaProds.Size-1
		If listaProdsConCantIndex.IndexOf(pr) = -1 Then
			Private Pnl As B4XView = xui.CreatePanel("")
			Pnl.SetLayoutAnimated(0, 0, 0, clv_prods_ll.AsView.Width, 63dip)
			clv_prods_ll.Add(Pnl, listaProds.Get(pr))
			listaHints.Add(listaProds.get(pr).As(Map).Get("prod"))
			cont = cont + 1
		End If
	Next
'	LogColor(clv_prods_ll.Size, Colors.red)
'	PCLV.Commit
'	Log("CONT=" & cont)
'	Log("CLV_PRODSLL="&clv_prods_ll.Size)
	PCLV.B4XSeekBar1.MaxValue = clv_prods_ll.Size
	PCLV.B4XSeekBar1.MinValue = 0
	PCLV.B4XSeekBar1.Interval = clv_prods_ll.Size/20
	PCLV.B4XSeekBar1.Value = clv_prods_ll.Size
	PCLV.B4XSeekBar1.Update
'	Log($"Min:0, max:${clv_prods_ll.Size}, Interval:${clv_prods_ll.Size/20}"$)
	reiniciarlistaProds = False
End Sub

'Return the hint that will be displayed when the user fast scrolls the list. It can be a string or CSBuilder.
Sub PCLV_HintRequested(Index As Int) As Object
	Dim word As String = listaHints.get(Index)
	Return word
End Sub