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
	Private l_promoDesc As Label
	Private lv_prodsFijos As ListView
	Private clv_prodsVariabes As CustomListView
	Private l_prodsFijos As Label
	Private l_prodsVariables As Label
	Private i_prod As ImageView
	Private l_prodX As Label
	Private b_prodMenos As Button
	Private et_pCant As EditText
	Private b_prodMas As Button
	Private l_pCant As Label
	Dim totalProds As Int = 0
	Dim prodsVarReq As Int = 0
	Dim prodsVarReq2 As Int = 0
	Dim totalCompra As Float = 0
	Dim prodsFijosTot As Float = 0
	Dim tpf As Int = 0
	Dim tpf2 As Int = 0
	Dim maxCantPromos As Int = 1
	Private l_totProds As Label
	Private l_total As Label
	Private b_terminar1 As Button
	Private p_promociones As Panel
	Dim prodsIds, prodsCants, prodsPrecios, prodsIds2, prodsCants2, prodsPrecios2 As List
	Dim estaPromo, esteCliente As String
	Private b_promoMas As Button
	Private b_promoMenos As Button
	Private et_promoCant As EditText
	Private l_promosCant As Label
	Private b_continuar As Button
	Private p_prodsVariables As Panel
	Dim laPromo = "", elCliente = "" As String
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("promociones")
	p_promociones.Top=0
	p_promociones.Left=0
	p_promociones.Height=Root.Height
	p_promociones.Width=Root.Width
	b_terminar1.Left = Root.Width - (b_terminar1.Width + 10)
	b_continuar.Left = Root.Width - b_terminar1.Width - (b_continuar.Width + 20)
End Sub

Sub B4XPage_Appear
	prodsIds.Initialize
	prodsCants.Initialize
	prodsPrecios.Initialize
	prodsIds2.Initialize
	prodsCants2.Initialize
	prodsPrecios2.Initialize
	Log($"laPromo=${laPromo}, el cliente=${elCliente}"$)
	If laPromo <> "" Then muestraPromo(laPromo, elCliente)
End Sub
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Sub muestraPromo(promo As String, cliente As String)
	Private thisLog As Boolean = False
	Log(promo)
	estaPromo = promo
	esteCliente = cliente
	Private mp As Map = Subs.traePromo(promo, cliente)
	Private prodsPromo As Map = mp.Get("productos") 'Los productos de la promoción.
	Private invDispPromo As Map = Subs.traemosInventarioDisponibleParaPromo(promo)
'	If thisLog Then Log($"invDispPromo=${invDispPromo}"$)
	Log("Max promos por inv de prods FIJOS: " & Subs.revisaMaxPromosProdsFijosPorInventario(mp))
	Log("Max promos por inv de prods VARIABLES: " & Subs.revisaMaxPromosProdsVariablesPorInventario(mp))
	maxCantPromos = Subs.revisaMaxPromosProdsVariablesPorInventario(mp)
	et_promoCant.Text = 1
	l_promosCant.text = "Max promos: " & maxCantPromos
	Private cs As CSBuilder
	cs.Initialize
	If thisLog Then Log(mp)
	If thisLog Then Log(prodsPromo)
	'Ponemos la promo y descripción.
'	Dim desc As String = $"Promoción: ${promo}${CRLF}${mp.Get("descripcion")}"$
'	Dim desc As String = cs.append("Promocion: ").Color(Colors.RGB(100,149,237)).Append(promo).pop.append(CRLF).Append(mp.Get("descripcion")).Popall
	l_promoDesc.Text = cs.Color(Colors.RGB(100,149,237)).append("Promocion: ").pop.append(CRLF).Append(promo).append(CRLF).Append(mp.Get("descripcion")).Popall
	prodsFijosTot = 0
	'Ponemos el texto en las etiquetas de la cantidad de productos.
'	Dim pf As List = mp.Get("prodsFijos")
	Dim pv As List = mp.Get("prodsVariables")
	If thisLog Then Log(mp)
	tpf = 0
	For Each pfp As Int In mp.Get("prodsFijosPiezas").As(List)
		tpf = tpf + pfp
	Next
	tpf2 = tpf
'	tpf = tpf * maxCantPromos
	l_prodsFijos.Text = $"Productos fijos (${tpf})"$
	prodsVarReq = mp.Get("prodsVariablesRequeridos")
	prodsVarReq2 = prodsVarReq
	l_prodsVariables.Text = $"Productos variables requeridos: ${prodsVarReq}"$
	If prodsVarReq = 0 Then
		p_prodsVariables.Visible = False
	Else
		p_prodsVariables.Visible = True
	End If
	'Llenamos el listview con los productos fijos.
	Dim label1 As Label
	label1 = lv_prodsFijos.SingleLineLayout.Label
	label1.TextSize = 13
	label1.TextColor = Colors.black
	lv_prodsFijos.SingleLineLayout.ItemHeight = 30dip
	lv_prodsFijos.Clear
'	If pf.Size < 1 Then pf.Add("Sin productos fijos.")
	lv_prodsFijos.Clear
	agregaFijosALista(mp, True)
	If thisLog Then Log("Total prods fijos = " & prodsFijosTot)
'	If thisLog Then Log("======="&prodsMap)
	l_totProds.text = $"Productos: ${tpf}"$
	l_total.Text = $"Total: $$1.2{prodsFijosTot}"$
'	Dim ins As InputStream
'	Dim bmp As Bitmap
'	Dim jpeg() As Byte

	'Llenamos el listview con los productos variables.
	If thisLog Then Log(pv)
	If thisLog Then Log("invDisp=" & invDispPromo)
	clv_prodsVariabes.Clear
	For Each p As String In pv
		If invDispPromo.ContainsKey(p) Then 'Si no esta en la lista de productos con inventario no lo mostramos.
'		c2.Position=i
'		jpeg = c2.GetBlob("CAT_GP_IMG")
'		ins.InitializeFromBytesArray(jpeg, 0, jpeg.Length)
'		bmp.Initialize2(ins)
			Private thisProd As Map = prodsPromo.Get(p)
			If thisLog Then Log(thisProd)
			clv_prodsVariabes.Add(CreateListItem(Subs.traeProdNombre(p)&CRLF&"Hay " & invDispPromo.Get(p) & " $" & thisProd.Get("precio"), thisProd.Get("precio"), invDispPromo.Get(p), clv_prodsVariabes.AsView.Width, 50dip, Null, p), p)
		End If
	Next
	b_terminar1.Visible = False
	b_continuar.Visible = False
	cuentaProds
End Sub

'Agregamos los productos fijos a una lista para despues meterlos en el pedido.
Sub agregaFijosALista(mp As Map, addListItem As Boolean)
	Private thisLog As Boolean = False
	Private cont As Int = 0
	prodsFijosTot = 0
	Dim pf As List = mp.Get("prodsFijos")
	If pf.Size < 1 Then pf.Add("Sin productos fijos.")
'	Private m As Map
'	prodsMap.Put(estaPromo, CreateMap("cant":1, "precio":0))
'	prodsIds.Add(estaPromo)
	prodsIds.clear
	prodsCants.clear
	prodsPrecios.clear
	prodsIds.Add(estaPromo)
	prodsCants.Add(et_promoCant.text.As(Int))
	prodsPrecios.Add(0)
	For Each p As String In pf
		Log($"cont=${cont}, mp=${mp}"$)
		If mp.Get("prodsFijosPiezas").As(List).Size > 0 Then
			Private tpi As String = mp.Get("prodsFijosPiezas").As(List).Get(cont)
		Else
			Private tpi As String = 0
		End If
		If mp.Get("prodsFijosPrecios").As(List).Size > 0 Then
			Private tpr As String = mp.Get("prodsFijosPrecios").As(List).Get(cont)
		Else
			Private tpr As String = 0
		End If
		prodsFijosTot = prodsFijosTot + (tpi * tpr)
		If thisLog Then Log("|"&tpi&"|"&p)
		Private ntpi As Int = tpi * et_promoCant.text
		If addListItem And tpi > 0 Then lv_prodsFijos.AddSingleLine(ntpi & " " & Subs.traeProdNombre(p) & " - $" & tpr)
		cont = cont+1
'		m=CreateMap("cant":tpi, "precio":tpr)
'		prodsMap.Put(p, m)
		prodsIds.Add(p)
		prodsCants.Add(tpi.As(Int)*et_promoCant.text.As(Int))
		prodsPrecios.Add(tpr) '*et_promoCant.text.As(Int)
	Next
End Sub

Sub CreateListItem(Text As String, precioU As String, inv As Int, Width As Int, Height As Int, img As Bitmap, prodId As String) As Panel 'ignore
	Dim p As B4XView = xui.CreatePanel("")
	p.SetLayoutAnimated(0, 0, 0, Width, Height)
	p.LoadLayout("prodItem")
	l_prodX.TextSize = 12
	l_prodX.Text = Text
'	l_pCant.Text = 0
	l_pCant.Tag = precioU&"|"&inv&"|"&prodId
	et_pCant.Tag = precioU&"|"&inv&"|"&prodId
	et_pCant.BringToFront
'	i_prod.Bitmap = img
	Return p
End Sub

Sub b_prodMenos_Click
	Dim index As Int = clv_prodsVariabes.GetItemFromView(Sender)
	Dim pnl0 As B4XView = clv_prodsVariabes.GetPanel(index)
	Dim pnl As B4XView = pnl0.GetView(0)
'	Dim laCant  As B4XView = pnl.GetView(5)
	Dim laCant As B4XView = pnl.GetView(2).GetView(3)
'	Log($"precio|stock:${laCant.tag}"$)
	laCant.Text = $"$1.0{laCant.Text-1}"$
	If laCant.Text < 0 Then laCant.Text = 0
'	Dim chk As B4XView = pnl.GetView(2)
	cuentaProds
'	l_total.Text = $"Total Compra: $$1.2{totalCompra}"$
'	l_totProds.text = $"Total Productos: ${totalProds}"$
End Sub

Sub b_prodMas_Click
	If totalProds < prodsVarReq + tpf Then
		Dim index As Int = clv_prodsVariabes.GetItemFromView(Sender)
		Dim pnl0 As B4XView = clv_prodsVariabes.GetPanel(index)
		Dim pnl As B4XView = pnl0.GetView(0)
'		Dim laCant  As B4XView = pnl.GetView(5)
		Dim laCant As B4XView = pnl.GetView(2).GetView(3)
'		Log($"precio|stock:${laCant.tag}"$)
'		Log($"Indice: ${index}, cant:${laCant.Text+1}, precioU: ${laCant.tag}"$)
		Dim esteTag As List = Regex.Split("\|", laCant.Tag)
'		Log(esteTag)
		If laCant.Text + 1 <= esteTag.get(1) Then
			laCant.Text = $"$1.0{laCant.Text+1}"$
			cuentaProds
		End If
	End If
'	Log($"Total Prods: ${totalProds}, Total Compra: $$1.2{totalCompra}"$)
'	l_total.Text = $"Total Compra: $$1.2{totalCompra}"$
'	l_totProds.text = $"Total Productos: ${totalProds}"$
End Sub

Private Sub et_pCant_TextChanged (Old As String, New As String)
'	LogColor("txt changed",Colors.Magenta)
	cuentaProds
End Sub

Sub cuentaProds
	Log("=====================================================")
	Log("Inicia cuentaProds")
	Private thisLog As Boolean = False
	If thisLog Then LogColor($"ProdsFijos=${tpf}, totalProds=${totalProds}, totalCompra=${totalCompra}"$, Colors.Red)
	prodsIds2.Clear
	prodsCants2.Clear
	prodsPrecios2.Clear
	lv_prodsFijos.Clear
	agregaFijosALista(Subs.traePromo(estaPromo, esteCliente), True)
'	Log(prodsIds)
	Private tcpf As Float = 0 'Total de compra de productos fijos.
	For pf = 0 To prodsIds.Size - 1
		If thisLog Then Log($"${tcpf} + ${prodsCants.Get(pf)} * ${prodsPrecios.Get(pf)} = ${(prodsPrecios.Get(pf) * prodsCants.Get(pf))}"$)
		tcpf = tcpf + (prodsPrecios.Get(pf) * prodsCants.Get(pf))
	Next
'	Log("Total compra pordsFijos = " & tcpf)
	totalCompra = tcpf
	totalProds = tpf 'Cantidad total de productos fijos.
	For i = 0 To clv_prodsVariabes.GetSize - 1
		Private p0 As B4XView = clv_prodsVariabes.GetPanel(i)
		Private p As B4XView = p0.GetView(0)
		Private cant1 As B4XView = p.GetView(2).GetView(3)
		If cant1.Text = "" Then cant1.Text = 0
		totalProds = totalProds + cant1.Text
		Private esteTag As List = Regex.Split("\|", cant1.Tag)
		If cant1.Text > esteTag.Get(1) Then cant1.Text = esteTag.Get(1)
		If cant1.Text > 0 Then
			Log(esteTag.Get(2) & "|" & cant1.Text)
			totalCompra = totalCompra + (esteTag.get(0) * cant1.text)
			If thisLog Then Log($"Cant: ${cant1.Text}, Suma: ${totalCompra}"$)
			prodsIds2.Add(esteTag.Get(2))
			prodsCants2.Add(cant1.Text)
			prodsPrecios2.Add(esteTag.get(0))
		End If
'		Log(esteTag)
'		Log($"Cant: ${cant1.Text}, Suma: ${totalCompra}"$)
'		totalCompra = totalCompra * et_promoCant.Text
'		totalProds = totalProds * et_promoCant.Text

		l_total.Text = $"Total: $$1.2{totalCompra}"$
		l_totProds.text = $"Productos: ${totalProds}"$
	Next
	If thisLog Then Log($"Total Prods: ${totalProds}, Total: $$1.2{totalCompra}"$)
	l_total.Text = $"Total: $$1.2{totalCompra}"$
	l_totProds.text = $"Productos: ${totalProds}"$
	If totalProds < prodsVarReq + tpf Or totalProds > prodsVarReq + tpf Then
'		Log("INCOMPLETA")
		b_terminar1.Visible = False
		b_continuar.Visible = False
	Else
'		Log("COMPLETA")
		b_terminar1.Visible = True
		b_continuar.Visible = True
	End If
	If thisLog Then LogColor($"${prodsIds}${CRLF}${prodsCants}${CRLF}${prodsPrecios}"$, Colors.blue)
	If thisLog Then LogColor($"${prodsIds2}${CRLF}${prodsCants2}${CRLF}${prodsPrecios2}"$, Colors.Magenta)
	LogColor($"Total Prods: ${totalProds}, Total: $$1.2{totalCompra}"$, Colors.Blue)
End Sub

Private Sub et_pCant_FocusChanged (HasFocus As Boolean)
	LogColor("focus changed", Colors.Magenta)
	cuentaProds
End Sub

Private Sub b_promoMenos_Click
	If et_promoCant.Text > 1 Then
		et_promoCant.Text = et_promoCant.Text.As(Int) - 1
	End If
	l_prodsFijos.Text = $"Productos fijos (${tpf2 * et_promoCant.Text.As(Int)})"$
	l_prodsVariables.Text = $"Productos variables requeridos: ${prodsVarReq2 * et_promoCant.Text.As(Int)}"$
	tpf = tpf2 * et_promoCant.Text.As(Int)
	prodsVarReq = prodsVarReq2 * et_promoCant.Text.As(Int)
	Log($"Max promos=${et_promoCant.Text.As(Int)}, Prods fijos=${tpf},  "$)
	cuentaProds
End Sub

Private Sub b_promoMas_Click
	If et_promoCant.Text < maxCantPromos Then
		et_promoCant.Text = et_promoCant.Text.As(Int) + 1
		l_prodsFijos.Text = $"Productos fijos (${tpf2 * et_promoCant.Text.As(Int)})"$
		l_prodsVariables.Text = $"Productos variables requeridos: ${prodsVarReq2 * et_promoCant.Text.As(Int)}"$
		tpf = tpf2 * et_promoCant.Text.As(Int)
		prodsVarReq = prodsVarReq2 * et_promoCant.Text.As(Int)
		Log($"Max promos=${et_promoCant.Text.As(Int)}, Prods fijos=${tpf},  "$)
	End If
	If et_promoCant.text > maxCantPromos Then et_promoCant.Text = maxCantPromos
	cuentaProds
End Sub

Private Sub b_terminar1_Click
	cuentaProds
	Log("====================================================================")
'	Log($"${prodsIds}${CRLF}${prodsCants}${CRLF}${prodsPrecios}"$)
	For t = 0 To prodsIds.Size - 1 'Guardamos los productos fijos de la promocion en pedido.
		Private pn As String = Subs.traeProdNombre(prodsIds.Get(t))
		If prodsCants.Get(t) > 0 Then Subs.guardaProducto(estaPromo, prodsPrecios.Get(t), prodsCants.Get(t), pn, prodsIds.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, B4XPages.MainPage.tipo_venta)
	Next
	For t = 0 To prodsIds2.Size - 1 'Guardamos los productos variables de la promocion en pedido.
		Private pn As String = Subs.traeProdNombre(prodsIds2.Get(t))
		Subs.guardaProducto(estaPromo, prodsPrecios2.Get(t), prodsCants2.Get(t), pn, prodsIds2.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, B4XPages.MainPage.tipo_venta)
	Next
	lv_prodsFijos.Clear
	B4XPages.MainPage.bTerminarClicked = True
	B4XPages.ShowPage("Cliente")
End Sub

Private Sub b_continuar_Click
	cuentaProds
	Log("====================================================================")
	Log($"${prodsIds}${CRLF}${prodsCants}${CRLF}${prodsPrecios}"$)
	For t = 0 To prodsIds.Size - 1 'Guardamos los productos fijos de la promocion en pedido.
		Private pn As String = Subs.traeProdNombre(prodsIds.Get(t))
		LogColor(pn,Colors.Red)
		If pn <> "N/A" Then
			Subs.guardaProducto(estaPromo, prodsPrecios.Get(t), prodsCants.Get(t), pn, prodsIds.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, B4XPages.MainPage.tipo_venta)
		End If
	Next
	Log(prodsIds2)
	For t = 0 To prodsIds2.Size - 1 'Guardamos los productos variables de la promocion en pedido.
		Private pn As String = Subs.traeProdNombre(prodsIds2.Get(t))
		LogColor(pn,Colors.Green)
		If pn <> "N/A" Then
			Subs.guardaProducto(estaPromo, prodsPrecios2.Get(t), prodsCants2.Get(t), pn, prodsIds2.Get(t), Subs.traeCliente, Subs.traeFecha, Subs.traeUsuarioDeBD, Subs.traeRuta, 0, B4XPages.MainPage.tipo_venta)
		End If
	Next
	lv_prodsFijos.Clear
'	Activity_KeyPress(KeyCodes.KEYCODE_BACK)
'	CallSubDelayed2(productos, "Activity_KeyPress", KeyCodes.KEYCODE_BACK)
	Private prodspage As C_Productos
	If prodspage.IsInitialized Then
		prodspage.lv_catalogos.Visible = True
		prodspage.lv_promos.Visible = False
		prodspage.clv_productos.AsView.Visible = False
	End If
	B4XPages.MainPage.bTerminarClicked = True
	B4XPages.ShowPage("productos")
End Sub

'Sub Activity_KeyPress (key As Int) As Boolean 'ignore
'	' BACK key pressed
'	Log("Keypress")
'	If key=KeyCodes.KEYCODE_BACK Then
'		Log("BACK")
'		Return False
'	End If
'	Return False
'	' Returning False signals the system to handle the key
'End Sub