B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=11.5
@EndOfDesignText@
Sub MODS 'ignore
	'V3.04.10 - Se agregó código para el registro de abonos, en B4XMainPage se genera la tabla y aquí se agregó el panel p_abonos para ralizar el abono, y el codigo en el sub "mandaPendientes" para cambiar la bandera de enviado en el abono.
End Sub

Sub Class_Globals
	Private Root As B4XView 'ignore
	Dim rp As RuntimePermissions
	Private xui As XUI 'ignore
	Private p_cliente As Panel
	Dim reqManager As DBRequestManager
	Dim cmd As DBCommand
	Dim ime As IME
	Dim g As GPS
	Dim ruta As String
	Dim skmt As SQL
	Dim clie_id As String
	Dim sDate,sTime As String
	Dim usuario As String
	Dim total_cliente As String
	Dim m_lat, m_lon As String
'	Dim btAdmin As BluetoothAdmin
	Dim cmp20 As Serial
	Dim printer As TextWriter
	Dim PairedDevices As Map
	Dim L As List
	Dim TAMANO As Int
	Dim ESPACIO As Int
	Dim BLANCO As String
	Dim cuenta As String
	Dim tipo_venta As String = "PREVENTA"
	Dim MAC_IMPRESORA As String
	Dim c As Cursor
	Dim s As Cursor
	Dim DD As Cursor
	Dim c2 As Cursor
	Dim ListView1 As ListView
	Dim la_cuenta As Label
	Dim La_nombre As Label
	Dim la_Calle As Label
	Dim la_numero As Label
	Dim la_nint As Label
	Dim la_edo As Label
	Dim la_pob As Label
	Dim la_col As Label
	Dim la_cp As Label
	Dim la_zona As Label
	Dim gest As Button
	Dim la_saldotot As Label
	Dim la_saldooper As Label
	Dim Tels As Button
	Dim Label10 As Label
	Dim Label11 As Label
	Dim Tar As Button
	Dim la_comm As Label
	Dim la_actdte As Label
	Dim la_usuario As Label
	Dim la_resultado As Label
	Dim l_entre1 As Label
	Dim l_entre2 As Label
	Dim l_atiende As Label
	Dim l_atiende2 As Label
	Dim DATOS As Button
	Dim NUEVO As Button
'	Dim lat_gps, lon_gps As String
	Dim l_total As Label
	Dim c2 As Cursor
	Dim S2 As Cursor
	Private s As Cursor
	Dim res As String
	Private HIST As Button
	Private MONTO_COMPRA As String
	Private META As String
	Private META2 As String
	Private VERIFICA As String
	Private L_QR As Label
	Private BT_QR As Button
	Dim CODIGO As String
	Private b_mapa As Button
	Dim CUANTOS As String
	Private B_IMP As Button
	Dim Toggla As Toggle
	Dim tgl As Toggle
	Private Panel1 As Panel
	Private I_COMPRA As EditText
	Private b_venta As Button
	Dim ALMACEN As String
	Private LA_GPS As Label
	Private B_E_NEXT As Button
	Private E_RES_E As EditText
	Private t_tenc As Label
	Private Panel2 As Panel
	Private CONTADOR_E As String
	Private HR_RES1 As String
	Private HR_RES2 As String
	Private HR_RES3 As String
	Private EXISTE As String
	Private TELEFONO As String
	Private RB1, RB2, RB3, RB4, RB5 As RadioButton
	Private stay_hh, stay_mi, stay_ss As String
	Dim result As Int
	Private LA_RUTA As String
	Private b_like As Button
	Private B_GPS As Button
	Dim CODIGO As String
	Private cb_factura As CheckBox
	Private p_cbFactura As Panel
	Dim venimosDeTicketsDia As Boolean = False
	Private p_abono As Panel
	Private et_abono As EditText
	Private b_abono As Button
	Private b_cancelar As Button
	Private b_abono1 As Button
	Private E_NOMBRE_C As EditText
	Private et_direccion As EditText
	Private E_ENTRE1 As EditText
	Private E_ENTRE_2 As EditText
	Private CH_ACTIVO As CheckBox
	Private CLIENTE_ACTIVO As String
	Private et_cp As EditText
	Private et_colonia As EditText
	Private lv_colonia As ListView
	Private et_estado As EditText
	Private et_municipio As EditText
	Dim desdeBD As Boolean
	Private b_guardaCambios As Button
	Private l_secuencia As Label
	Private l_ruta As Label
	Private et_diaSemana As EditText
'	Private et_giro As EditText
	Private lv_diaSemana As ListView
	Private et_calle As EditText
	Private et_NoExt As EditText
	Private et_NoInt As EditText
	Private l_cp As Label
	Private l_lon As Label
	Private l_lat As Label
	Private b_actCoords As Button
	Private estatus As String
	Private cb_activo As B4XComboBox
	Private et_atiende As EditText
	Private cb_giro As B4XComboBox
	Dim refrescarCliente As Boolean = False
	Dim Timer2 As Timer
	Dim Interval As Int = 300
	Dim turnoColor As Int = 1
	Dim cd As ColorDrawable
	Dim camposModificados As List
	Dim mandarTodo As Boolean = False
	Private sv_clientesDatos As ScrollView
'	Private bAceptarPregunta As Button
'	Dim encuestaIniciada As Boolean = False
	Dim q As C_Cuestionario
	Dim su As StringUtils
	Dim clienteAnt As String = ""
	Private l_cuestionario As Label
	Private b_mapa2 As Button
	Private l_tituloCuestionaro As Label
	Private cb_diaSemana As B4XComboBox
	Dim diasDeLaSemana As List = Array As String("LUNES", "MARTES", "MIERCOLES", "JUEVES", "VIERNES", "SABADO")
	Private et_telefono As EditText
	Private et_email As EditText
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)
	Log("Entramos a clientes create")
	Root = Root1
	'load the layout to Root
'	Activity.RemoveAllViews
	Root.LoadLayout("cliente")
	ruta = File.DirInternal
	If File.Exists(ruta, "kmt.db") = False Then
		File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
	End If
	skmt.Initialize(ruta,"kmt.db", True)
'	btAdmin.Initialize("BlueTeeth")
'	cmp20.Initialize("Printer")
	m_lat = 0
	m_lon = 0

	reqManager.Initialize(Me, Starter.server)
	sv_clientesDatos.Width = Root.Width
	sv_clientesDatos.Height = Root.Height
	sv_clientesDatos.Panel.LoadLayout("clienteDatos")
	Subs.centraBoton(b_guardaCambios, p_cliente.Width)
	If l_cuestionario.Visible Then
		b_guardaCambios.Top = l_cuestionario.Top + l_cuestionario.Height + 20dip
	Else
		b_guardaCambios.Top = l_cuestionario.Top + 20dip
	End If
	Log("terminamos create")
	camposModificados.Initialize
	q.Initialize(Me, "q", Root, skmt)
End Sub

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

Sub B4XPage_Appear
	rp.CheckAndRequest(Starter.rp.PERMISSION_CAMERA)
	Wait For B4XPage_PermissionResult (Permission As String, resultC As Boolean)
	sv_clientesDatos.Panel.Height = p_cliente.Height
	l_cuestionario.Visible = False
	l_tituloCuestionaro.Visible = False
	reqManager.Initialize(Me, Starter.server)
	lv_colonia.Visible = False
	Timer2.Initialize("Timer2", Interval * 1)
	Timer2.Enabled = True
	b_guardaCambios.Enabled = False
	b_guardaCambios.Text = "Buscando Ubicación"
	If Not(Starter.gps.GPSEnabled) Then
		ToastMessageShow("Es necesario tener el GPS encendido", True)
		StartActivity(Starter.gps.LocationSettingsIntent)
	End If
	CallSubDelayed(Tracker, "StartFLPSmall")
	If refrescarCliente Then
		LogColor("Cargamos cliente de BD", Colors.Magenta)
		skmt.Initialize(ruta,"kmt.db", True)
		c = B4XPages.MainPage.skmt.ExecQuery("select * from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
		If c.RowCount > 0 Then
			c.Position=0
			la_cuenta.Text = c.GetString("CAT_CL_CODIGO")
			l_ruta.Text = c.GetString("CAT_CL_RUTA")
'			et_giro.Text = c.GetString("CAT_CL_GIRO")
			et_diaSemana.Text = c.GetString("CAT_CL_DIASEMANA")
			l_secuencia.text = c.GetString("CAT_CL_SECUENCIA")
			la_cuenta.Text = c.GetString("CAT_CL_CODIGO")
			E_NOMBRE_C.TEXT = c.GetString("CAT_CL_NOMBRE")
			et_direccion.Text = c.GetString("CAT_CL_CALLE1")
			et_colonia.Text = ""
			et_colonia.Text = c.GetString("CAT_CL_COLONIA")
			et_telefono.Text = c.GetString("CAT_CL_TELEFONO")
			et_email.Text = c.GetString("CAT_CL_EMAIL")
			et_estado.Text = c.GetString("CAT_CL_EDO")
			desdeBD = True
			et_cp.Text = c.GetString("CAT_CL_CP")
			et_calle.Text = c.GetString("CAT_CL_CALLE")
			et_NoExt.Text = c.GetString("CAT_CL_NOEXT")
			et_NoInt.Text = c.GetString("CAT_CL_NOINT")
			estatus = c.GetString("CAT_CL_ESTATUS")
			If estatus = Null Then estatus = ""
			cb_activo.Tag = estatus
			E_ENTRE1.Text = ""
			E_ENTRE_2.Text = ""
			et_atiende.Text = ""
			If c.GetString("CAT_CL_CRUCE1") <> Null Then E_ENTRE1.Text = c.GetString("CAT_CL_CRUCE1")
			If c.GetString("CAT_CL_CALLE2") <> Null Then E_ENTRE_2.Text = c.GetString("CAT_CL_CALLE2")
			If c.GetString("CAT_CL_ATIENDE1") <> Null Then et_atiende.Text = c.GetString("CAT_CL_ATIENDE1")
			m_lat = "0"
			If c.GetString("CAT_CL_LAT") <> "" Then m_lat = c.GetString("CAT_CL_LAT")
			If m_lat.Length < 5 Then m_lat = "0"
			m_lon = "0"
			If c.GetString("CAT_CL_LONG") <> "" Then m_lon = c.GetString("CAT_CL_LONG")
			If m_lon.Length < 5 Then m_lon = "0"
			l_lat.Text = m_lat
			l_lon.Text = m_lon
		End If
		Private cuest As Cursor = skmt.ExecQuery($"select * from cuestionario where Q_IDCLIENTE = '${Subs.traeCliente}'"$)
		If cuest.RowCount > 0 Then
			Private cs As CSBuilder
			cs.Initialize
			For i = 0 To cuest.RowCount - 1
				cuest.Position = i
				cs.color(Colors.black).Append(cuest.GetString("Q_PREGUNTA")).popall.Append(CRLF).Append(" " & cuest.GetString("Q_RESPUESTA")).Append(CRLF).popall
			Next
			l_cuestionario.Text = cs
			l_cuestionario.Visible = True
			l_tituloCuestionaro.Visible = True
		End If
		l_cuestionario.Height = su.MeasureMultilineTextHeight(l_cuestionario, l_cuestionario.Text)
		ajustaTamano
'		Tracker.FLP.Connect
		If Tracker.FLP.IsInitialized And Tracker.FLP.GetLastKnownLocation.IsInitialized Then 'Si tenemos "UltimaUbicaccionConocida" la usamos.
			B4XPages.MainPage.lat_gps = Tracker.FLP.GetLastKnownLocation.Latitude
			B4XPages.MainPage.lon_gps = Tracker.FLP.GetLastKnownLocation.Longitude
'		Log($"Tenemos UUC: ${Tracker.FLP.GetLastKnownLocation.Latitude},${Tracker.FLP.GetLastKnownLocation.Longitude}"$)
'		GPS_LocationChanged(Tracker.FLP.GetLastKnownLocation)
		End If
		desdeBD = False
		Dim itemsAct As List
		itemsAct.Initialize
		itemsAct.Add("Activo")
		itemsAct.Add("No Activo")
'		itemsAct.Add("Cerrado Permanente")
		cb_activo.SetItems(itemsAct)
'	Log(estatus)
		If estatus = "Activo" Then
			cb_activo.SelectedIndex = 0
			CLIENTE_ACTIVO = "Activo"
		Else If estatus = "Inactivo" Then
			cb_activo.SelectedIndex = 1
			CLIENTE_ACTIVO = "Inactivo"
		Else
			cb_activo.SelectedIndex = 1 'Antes 2 para "Cerrado Permanente"
			CLIENTE_ACTIVO = "Inactivo" 'Antes "Cerrado Permanente"
		End If
		Dim losGiros As List = Subs.traeGirosLista
		cb_giro.SetItems(losGiros)
		cb_giro.SelectedIndex = losGiros.IndexOf(c.GetString("CAT_CL_GIRO").As(String).ToUpperCase)
		cb_giro.mBase.Width = et_diaSemana.Width
		cb_diaSemana.SetItems(diasDeLaSemana)
		cb_diaSemana.SelectedIndex = diasDeLaSemana.IndexOf(c.GetString("CAT_CL_DIASEMANA"))
'		Log("|"&c.GetString("CAT_CL_GIRO")&"|")
		c.Close
		camposModificados.Clear
	End If
	refrescarCliente = False
	'Revisamos si el cliente actual es diferente del anterior y si es diferente ponemos encuestaIniciada en VERDADERO.
	If clienteAnt <> Subs.traeCliente Then q.encuestaIniciada = False
	clienteAnt = Subs.traeCliente
'	Log("CON ENCUESTA: " & q.clienteConCuestionario(Subs.traeCliente))
'	Log("INICIADA: " & q.encuestaIniciada)
	l_cuestionario.Height = su.MeasureMultilineTextHeight(l_cuestionario, l_cuestionario.Text)
	ajustaTamano

	If Not(q.encuestaIniciada) And Not(q.clienteConCuestionario(Subs.traeCliente)) Then q.agregaPregunta("1", "¿Se puede acceder al negocio o está enrejado?", Array As String("No, está enrejado o no se tiene acceso", "Si se pude acceder"))
End Sub

Private Sub Timer2_Tick
'	Log(turnoColor)
	If turnoColor = 1 Then
		cd.Initialize(Colors.RGB(125, 125, 125), 5dip) '210, 132, 79   '210, 105, 30   '125, 125, 125
		b_guardaCambios.Background = cd
		turnoColor = 0
	Else
		cd.Initialize(Colors.RGB(87, 87, 87), 5dip) '210, 132, 79   '210, 105, 30   '125, 125, 125
		b_guardaCambios.Background = cd
		turnoColor = 1
	End If
End Sub

Sub GPS_LocationChanged (Location1 As Location)
	LogColor($"Entrando a Cliente.GPS_LocationChanged"$, Colors.red)
'	Log($"${Tracker.FLP.GetLastKnownLocation.Latitude}, ${Tracker.FLP.GetLastKnownLocation.Longitude}"$)
	If Tracker.FLP.GetLastKnownLocation.IsInitialized And Tracker.FLP.GetLastKnownLocation.Latitude <> 0 Then
		B4XPages.MainPage.lat_gps = Tracker.FLP.GetLastKnownLocation.Latitude
		B4XPages.MainPage.lon_gps = Tracker.FLP.GetLastKnownLocation.Longitude
'		Log("Coords set to: " & B4XPages.MainPage.lat_gps & " and " & B4XPages.MainPage.lon_gps)
	End If
	Dim l1, l2 As Location
	l1.Initialize2(B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps)
'	Log($"Coordenadas de la tienda - lat:${m_lat}, lon:${m_lon}"$)
	l2.Initialize2(m_lat, m_lon)
'	Log($"${Location1.Latitude}, ${Location1.Longitude} - ${Tracker.FLP.GetLastKnownLocation.Latitude}, ${Tracker.FLP.GetLastKnownLocation.Longitude}"$)
	'now we need the distance between our location and the target location
'	Dim distance As Long
'	distance = l1.DistanceTo(l2)  'the result is in meter
	B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_GPS")
	B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO  HIST_GPS (HGDATE, HGLAT, HGLON) VALUES(?,?,?) ", Array As Object (sDate & " " & sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
	CallSubDelayed(Tracker, "CreateLocationRequest")
	b_guardaCambios.Text = "Guardar"
	b_guardaCambios.Enabled = True
	Timer2.Enabled = False
	b_guardaCambios.Color = Colors.RGB(210, 105, 30) '210, 132, 79   '210, 105, 30
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
'	BACK key pressed
	q.encuestaIniciada = False
	q.ocultPanelPregunta
'	Return True To close, False To cancel
	CallSubDelayed(Tracker, "StartFLP")
	Return True
'	Return False
End Sub

Private Sub b_guardaCambios_Click
'	dd/mm/yyyy hh24:mi:ss
	DateTime.DateFormat = "dd/MM/yyyy HH:mm:ss"
	sDate=DateTime.Date(DateTime.Now)
	camposModificados = Subs.RemoveDuplicates(camposModificados)
	Log(camposModificados)
	If CLIENTE_ACTIVO = "Inactivo" Or CLIENTE_ACTIVO = "Cerrado Permanente" Then l_secuencia.Text = "0"
	If CLIENTE_ACTIVO = "Cerrado Permanente" Then CLIENTE_ACTIVO = "Cerrado permanente confirmado"
	B4XPages.MainPage.skmt.ExecNonQuery($"UPDATE kmt_info set CAT_CL_CODIGO = '${la_cuenta.text}', CAT_CL_CEDIS = '${Subs.traeAlmacen}', CAT_CL_LAT = '${l_lat.text}', CAT_CL_LONG = '${l_lon.text}', CAT_CL_SECUENCIA = '${l_secuencia.text}', CAT_CL_RUTA = '${l_ruta.text}', CAT_CL_DIASEMANA = '${cb_diaSemana.SelectedItem}', CAT_CL_GIRO = '${cb_giro.SelectedItem}', CAT_CL_NOMBRE = '${Subs.escapeSQLString(E_NOMBRE_C.text)}', CAT_CL_ATIENDE1 = '${et_atiende.text}', CAT_CL_CALLE = '${Subs.escapeSQLString(et_calle.text)}', CAT_CL_NOINT = '${et_NoInt.text}', CAT_CL_NOEXT = '${et_NoExt.text}', CAT_CL_CALLE1 = '${Subs.escapeSQLString(et_direccion.text)}', CAT_CL_CRUCE1 = '${E_ENTRE1.text}', CAT_CL_CALLE2 = '${E_ENTRE_2.text}', CAT_CL_CP = '${et_cp.text}', CAT_CL_COLONIA = '${et_colonia.text}', CAT_CL_MUNI = '${et_municipio.text}', CAT_CL_EDO = '${et_estado.text}', CAT_CL_ESTATUS = '${CLIENTE_ACTIVO}', gestion = 11, CAT_CL_FECHA_CAPTURA = '${sDate & " " & sTime}', CAT_CL_ENVIO_PENDIENTE = 1, LAT_CENSADOR = '${B4XPages.MainPage.lat_gps}', LON_CENSADOR = '${B4XPages.MainPage.lon_gps}', ESTATUS_ORIGINAL = '${cb_activo.tag}', CAT_CL_TELEFONO = '${et_telefono.Text}', CAT_CL_EMAIL = '${et_email.Text}', CAT_CL_EMAIL = '${et_email.Text}', CAMPOS_MODIFICADOS = '${Subs.list2string(camposModificados)}' where CAT_CL_CODIGO In (select cuenta from cuentaa)"$)
	Log($"CAT_CL_CODIGO = '${la_cuenta.text}', CAT_CL_CEDIS = '${Subs.traeAlmacen}', CAT_CL_LAT = '${l_lat.text}', CAT_CL_LONG = '${l_lon.text}', CAT_CL_SECUENCIA = '${l_secuencia.text}', CAT_CL_RUTA = '${l_ruta.text}', CAT_CL_DIASEMANA = '${cb_diaSemana.SelectedItem}', CAT_CL_GIRO = '${cb_giro.SelectedItem}', CAT_CL_NOMBRE = '${E_NOMBRE_C.text}', CAT_CL_ATIENDE1 = '${et_atiende.text}', CAT_CL_CALLE = '${et_calle.text}', CAT_CL_NOINT = '${et_NoInt.text}', CAT_CL_NOEXT = '${et_NoExt.text}', CAT_CL_CALLE1 = '${et_direccion.text}', CAT_CL_CRUCE1 = '${E_ENTRE1.text}', CAT_CL_CALLE2 = '${E_ENTRE_2.text}', CAT_CL_CP = '${et_cp.text}', CAT_CL_COLONIA = '${et_colonia.text}', CAT_CL_MUNI = '${et_municipio.text}', CAT_CL_EDO = '${et_estado.text}', CAT_CL_ESTATUS = '${CLIENTE_ACTIVO}', gestion = 11"$)
'	B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO NOVENTA (NV_CLIENTE, NV_FECHA, NV_USER, NV_MOTIVO, NV_COMM, NV_LAT, NV_LON) VALUES(?,?,?,?,?,?,?) ", Array As Object (clie_id, sDate & sTime, usuario, "CENSOS", CLIENTE_ACTIVO, l_lat.text, l_lon.text))
	mandaPendientes
	B4XPages.ShowPage("Clientes")
End Sub

Sub NUEVO_Click
	B4XPages.ShowPage("NuevoCliente")
End Sub

Private Sub p_cliente_Click
	'Nada aqui, solo esta para que los clics no se pasen hacia atras.
End Sub

Sub mandaPendientes
	'Enviamos Pendientes
	c = B4XPages.MainPage.skmt.ExecQuery("SELECT * from kmt_info where CAT_CL_ENVIO_PENDIENTE = '1'")
	If mandarTodo Then c = B4XPages.MainPage.skmt.ExecQuery("SELECT * from kmt_info")
	Log($">>>>>>  Cliente PENDIENTE: ${c.RowCount}"$)
	If c.RowCount > 0 Then
		For i = 0 To c.RowCount - 1
			c.Position = i
'			Dim fechaCaptura As String = c.GetString("CAT_CL_FECHA_CAPTURA").As(String).SubString2(0,10)
			Dim fechaCaptura As String = c.GetString("CAT_CL_FECHA_CAPTURA")
			Log(fechaCaptura)
			Dim cmd As DBCommand
			Dim motivo As String = "VERIFICACION DE DATOS"
			Dim comentario As String = c.GetString("ESTATUS_ORIGINAL")
			If c.GetString("CAT_CL_CODIGO").As(String).SubString2(0,1) = "N" Then motivo = "VERIFICACION CLIENTE NUEVO PREVENTA"
			If c.GetString("CAT_CL_CODIGO").As(String).SubString2(0,2) = "NC" Then motivo = "CLIENTE NUEVO CENSOS"
			If c.GetString("CAT_CL_CODIGO").As(String).SubString2(0,1) = "N" Then comentario = ""
			If c.GetString("CAT_CL_CODIGO").As(String).SubString2(0,2) = "NC" Then comentario = c.GetString("CAT_CL_CALLE1")
			
			Private cuestionarioTexto As String = ""
			Private cuest As Cursor = B4XPages.MainPage.skmt.ExecQuery($"select * from cuestionario where Q_IDCLIENTE = '${c.GetString("CAT_CL_CODIGO")}'"$)
			If cuest.RowCount > 0 Then
				cuest.Position = 0
				cuestionarioTexto = cuest.GetString("Q_FECHA")
				For cu = 0 To cuest.RowCount - 1
					cuestionarioTexto = $"${cuestionarioTexto}|${cuest.GetString("Q_IDPREGUNTA")}|${cuest.GetString("Q_PREGUNTA")}|${cuest.GetString("Q_IDRESPUESTA")}|${cuest.GetString("Q_RESPUESTA")}"$
				Next
			End If

			cmd.Initialize
			cmd.Name = "guardaClienteGeocerca_MARDS"
			cmd.Parameters = Array As Object(c.GetString("CAT_CL_CODIGO"), fechaCaptura, Subs.traeUsuarioDeBD, c.GetString("CAT_CL_LAT"), c.GetString("CAT_CL_LONG"), l_ruta.text, Subs.traeAlmacen, c.GetString("LAT_CENSADOR"), c.GetString("LON_CENSADOR"), motivo, comentario)
			reqManager.ExecuteCommand(cmd, "guaradClienteGeocerca")

			cmd.Initialize
			cmd.Name = "sp_confirmaCliente2"
			Log("*******  LARGO - " & cuestionarioTexto.Length)
			cmd.Parameters = Array As Object(c.GetString("CAT_CL_CODIGO"), Subs.traeAlmacen, c.GetString("CAT_CL_LAT"), c.GetString("CAT_CL_LONG"), c.GetString("CAT_CL_SECUENCIA"), c.GetString("CAT_CL_RUTA"), c.GetString("CAT_CL_DIASEMANA"), c.GetString("CAT_CL_GIRO"), Subs.escapeSQLString(c.GetString("CAT_CL_NOMBRE")), c.GetString("CAT_CL_ATIENDE1"), c.GetString("CAT_CL_CALLE"), c.GetString("CAT_CL_NOINT"), c.GetString("CAT_CL_NOEXT"), Subs.escapeSQLString(c.GetString("CAT_CL_CALLE1")), c.GetString("CAT_CL_CRUCE1"), c.GetString("CAT_CL_CALLE2"), c.GetString("CAT_CL_CP"), c.GetString("CAT_CL_COLONIA"), c.GetString("CAT_CL_MUNI"), c.GetString("CAT_CL_EDO"), c.GetString("CAT_CL_ESTATUS"), c.GetString("CAT_CL_FECHA_CAPTURA"), sDate, Subs.traeUsuarioDeBD, c.GetString("CAT_CL_TELEFONO"), c.GetString("CAT_CL_EMAIL"), cuestionarioTexto)
			Log($"${c.GetString("CAT_CL_CODIGO")}, ${Subs.traeAlmacen}, ${c.GetString("CAT_CL_LAT")}, ${c.GetString("CAT_CL_LONG")}, ${c.GetString("CAT_CL_SECUENCIA")}, ${c.GetString("CAT_CL_RUTA")}, ${c.GetString("CAT_CL_DIASEMANA")}, ${c.GetString("CAT_CL_GIRO")}, ${Subs.escapeSQLString(c.GetString("CAT_CL_NOMBRE"))}, ${c.GetString("CAT_CL_ATIENDE1")}, ${c.GetString("CAT_CL_CALLE")}, ${c.GetString("CAT_CL_NOINT")}, ${c.GetString("CAT_CL_NOEXT")}, ${c.GetString("CAT_CL_CALLE1")}, ${c.GetString("CAT_CL_CRUCE1")}, ${c.GetString("CAT_CL_CALLE2")}, ${c.GetString("CAT_CL_CP")}, ${c.GetString("CAT_CL_COLONIA")}, ${c.GetString("CAT_CL_MUNI")}, ${c.GetString("CAT_CL_EDO")}, ${c.GetString("CAT_CL_ESTATUS")}, ${c.GetString("CAT_CL_FECHA_CAPTURA")}, ${sDate}, ${Subs.traeUsuarioDeBD}, ${c.GetString("CAT_CL_TELEFONO")}, ${c.GetString("CAT_CL_EMAIL")}, ${cuestionarioTexto}"$)
			reqManager.ExecuteCommand(cmd , $"confirmaCliente_${c.GetString("CAT_CL_CODIGO")}"$)

			cmd.Initialize
			cmd.Name = "guardaClientesNuevosMods_MARDS"
			cmd.Parameters = Array As Object(Subs.traeUsuarioDeBD, Subs.traeAlmacen, Subs.traeAlmacen, c.GetString("CAT_CL_RUTA"), Subs.traeCliente, c.GetString("CAMPOS_MODIFICADOS"))
			Log($"${Subs.traeUsuarioDeBD}, ${Subs.traeAlmacen}, ${Subs.traeAlmacen}, ${c.GetString("CAT_CL_RUTA")}, ${Subs.traeCliente}, ${c.GetString("CAMPOS_MODIFICADOS")}"$)
			reqManager.ExecuteCommand(cmd , $"guardaClientesNuevosMods_${c.GetString("CAT_CL_CODIGO")}"$)
		Next
	End If
End Sub

Sub JobDone(Job As HttpJob)
	Log(Job.Success)
	If Job.Success = False Then
'		ToastMessageShow("Error: " & Job.ErrorMessage, True)
		LogColor("Error: " & Job.ErrorMessage, Colors.red)
	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 = "confirmaCliente" Then
				Subs.logJobDoneResultados(resultado)
			End If
			'Modificamos la bandera de pendiente en kmt_info
			If resultado.Tag.As(String).IndexOf("confirmaCliente_") > -1 Then
				Private cliente As String= resultado.Tag
				cliente = cliente.SubString(cliente.IndexOf("_")+1)
'				Log($"Cliente: ${cliente}"$)
				B4XPages.MainPage.skmt.ExecNonQuery($"update kmt_info set CAT_CL_ENVIO_PENDIENTE = 0 where CAT_CL_CODIGO = '${cliente}'"$)
				Subs.logJobDoneResultados(resultado)
			End If
			If resultado.Tag = "guaradClienteGeocerca" Then
				Subs.logJobDoneResultados(resultado)
			End If
		End If
		Job.Release
	End If
	
End Sub

Private Sub b_cancelar_Click
	et_abono.Text = ""
	p_abono.Visible = False
	ime.HideKeyboard
End Sub

Private Sub et_cp_TextChanged (Old As String, New As String)
'	Log(desdeBD)
	camposModificados.Add("CAT_CL_CP")
	If Not(desdeBD) And New.Length = 5 Then
		Private cc As Cursor = skmt.ExecQuery($"select estado, municipio, colonia from sepomex where codigo = '${et_cp.text}'"$)
'		LogColor(cc.RowCount, Colors.Green)
		If cc.RowCount > 0 Then
			For x = 0 To cc.RowCount - 1
				cc.Position = x
				et_estado.Text = cc.GetString("ESTADO")
				et_municipio.Text = cc.GetString("MUNICIPIO")
			Next
		End If
	End If
	desdeBD = False
End Sub

Private Sub et_cp_FocusChanged (HasFocus As Boolean)
	et_cp_click
End Sub

Sub et_cp_click
	lv_colonia.Visible = False
End Sub

Private Sub et_colonia_Click
	Sender.As(EditText).InputType = 524288
	If lv_colonia.Visible = False Then
		lv_colonia.Visible = True
	Else
		lv_colonia.Visible = False
	End If
End Sub

Private Sub et_colonia_FocusChanged (HasFocus As Boolean)
	If HasFocus Then
		Private cc As Cursor = skmt.ExecQuery($"select colonia from sepomex where codigo = '${et_cp.text}'"$)
		lv_colonia.Clear
		lv_colonia.BringToFront
		Private label1 As Label
		label1 = lv_colonia.SingleLineLayout.Label
		label1.TextColor = Colors.White
		label1.TextSize = 14
'		Log(cc.RowCount)
		If cc.RowCount > 0 Then
			For i = 0 To cc.RowCount - 1
				cc.Position = i
				lv_colonia.AddSingleLine(cc.GetString("COLONIA"))
'				Log(cc.GetString("COLONIA"))
			Next
		Else
			lv_colonia.AddSingleLine("Código no encontrado.")
			lv_colonia.AddSingleLine("Ingrese colonia manualmente.")
		End If
		lv_colonia.Visible = True
	End If
End Sub

Private Sub lv_colonia_ItemClick (Position As Int, Value As Object)
	lv_colonia.Visible = False
	If Value <> "Código no encontrado." And Value <> "Ingrese colonia manualmente." Then
		et_colonia.Text = Value
	End If
End Sub

Sub et_diaSemana_Click
	LogColor("Clic diasemana", Colors.Red)
	Sender.As(EditText).InputType = 524288
	If Not(lv_diaSemana.Visible) Then
		lv_diaSemana.Visible = True
	Else
		Log("Si visible")
		lv_diaSemana.Visible = False
	End If
End Sub

Private Sub et_diaSemana_FocusChanged (HasFocus As Boolean)
	If HasFocus And lv_diaSemana.Visible = False Then
'		lv_diaSemana.Visible = True
		lv_diaSemana.BringToFront
		lv_diaSemana.Clear
		Private label1 As Label
		label1 = lv_diaSemana.SingleLineLayout.Label
		label1.TextColor = Colors.White
		label1.TextSize = 14
		lv_diaSemana.AddSingleLine("LUNES")
		lv_diaSemana.AddSingleLine("MARTES")
		lv_diaSemana.AddSingleLine("MIERCOLES")
		lv_diaSemana.AddSingleLine("JUEVES")
		lv_diaSemana.AddSingleLine("VIERNES")
		lv_diaSemana.AddSingleLine("SABADO")
		lv_diaSemana.Visible = True
	End If
	If Not(HasFocus) And lv_diaSemana.Visible Then
		lv_diaSemana.Visible = False
	End If
End Sub

Private Sub lv_diaSemana_ItemClick (Position As Int, Value As Object)
	lv_diaSemana.Visible = False
	et_diaSemana.Text = Value
End Sub

Sub et_giro_Click
'	If lv_giro.Visible Then
'		lv_giro.Visible = False
'	Else
'		lv_giro.Visible = True
'	End If
End Sub

Sub et_giro_FocusChanged (HasFocus As Boolean)
'	If HasFocus Then
'		Sender.As(EditText).InputType = 524288
'		Private cc As Cursor = skmt.ExecQuery($"select * from cat_giros"$)
'		lv_giro.Clear
'		lv_giro.BringToFront
'		Private label1 As Label
''		label1 = lv_giro.SingleLineLayout.Label
'		label1.TextColor = Colors.White
'		label1.TextSize = 14
'		Log(cc.RowCount)
'		If cc.RowCount > 0 Then
'			For i = 0 To cc.RowCount - 1
'				cc.Position = i
'				label1.Tag = cc.GetString("id")
'				lv_giro.AddSingleLine(cc.GetString("descripcion"))
'				Log(cc.GetString("descripcion"))
'			Next
'		End If
'		lv_giro.Visible = True
'	Else
'		lv_giro.Visible = False
'	End If
End Sub

Private Sub lv_giro_ItemClick (Position As Int, Value As Object)
'	lv_giro.Visible = False
'	et_giro.Text = Value
End Sub

Private Sub l_cp_LongClick
	et_cp_TextChanged(et_cp.Text, et_cp.Text)
End Sub

Private Sub b_mapa2_Click
	B4XPages.MainPage.mapa.Latitud = l_lat.text
	B4XPages.MainPage.mapa.Longitud = l_lon.text
	B4XPages.MainPage.mapa.NOMBRE_TIENDA = E_NOMBRE_C.text
'	B4XPages.MainPage.mapa.gmap.Clear
	B4XPages.ShowPage("mapa")
End Sub

Private Sub b_actCoords_Click
	l_lat.Text = B4XPages.MainPage.lat_gps
	l_lon.Text = B4XPages.MainPage.lon_gps
	camposModificados.Add("CAT_CL_LAT")
	camposModificados.Add("CAT_CL_LONG")
	ToastMessageShow("¡Coordenadas actualizadas!", False)
End Sub

Private Sub cb_activo_SelectedIndexChanged (Index As Int)
	If Index = 0 Then
		CLIENTE_ACTIVO = "Activo"
	else if Index = 1 Then
		CLIENTE_ACTIVO = "Inactivo"
	Else
		CLIENTE_ACTIVO = "Cerrado Permanente"
	End If
	Log(CLIENTE_ACTIVO)
	camposModificados.Add("CAT_CL_ESTATUS")
End Sub

Private Sub cb_giro_SelectedIndexChanged (Index As Int)
	camposModificados.Add("CAT_CL_GIRO")
End Sub

Private Sub et_atiende_TextChanged (Old As String, New As String)
	camposModificados.Add("CAT_CL_ATIENDE1")
End Sub

Private Sub E_ENTRE_2_TextChanged (Old As String, New As String)
	camposModificados.Add("CAT_CL_CALLE2")
End Sub

Private Sub E_ENTRE1_TextChanged (Old As String, New As String)
	camposModificados.Add("CAT_CL_CRUCE1")
End Sub

Private Sub et_NoInt_TextChanged (Old As String, New As String)
	camposModificados.Add("CAT_CL_NOINT")
End Sub

Private Sub et_NoExt_TextChanged (Old As String, New As String)
	camposModificados.Add("CAT_CL_NOEXT")
End Sub

Private Sub et_calle_TextChanged (Old As String, New As String)
	camposModificados.Add("CAT_CL_CALLE")
End Sub

Private Sub et_direccion_TextChanged (Old As String, New As String)
	camposModificados.Add("CAT_CL_CALLE1")
End Sub

Private Sub et_colonia_TextChanged (Old As String, New As String)
	camposModificados.Add("CAT_CL_COLONIA")
End Sub

Private Sub et_municipio_TextChanged (Old As String, New As String)
	camposModificados.Add("CAT_CL_MUNI")
End Sub

Private Sub et_estado_TextChanged (Old As String, New As String)
	camposModificados.Add("CAT_CL_EDO")
End Sub

Private Sub E_NOMBRE_C_TextChanged (Old As String, New As String)
	camposModificados.Add("CAT_CL_NOMBRE")
End Sub

Private Sub et_diaSemana_TextChanged (Old As String, New As String)
	camposModificados.Add("CAT_CL_DIAS_VISITA")
End Sub

Private Sub cb_diaSemana_SelectedIndexChanged (Index As Int)
	camposModificados.Add("CAT_CL_DIAS_VISITA")
End Sub

Sub q_preguntaContestada(m As Map)
'	Recibimos el id de la pregunta, el id de la respuesta, el texto de la respuesta y el objeto del panelSombra para poder ocultarlo.
	Log(m)
'	If q.IsInitialized Then Log($"${q.encuestaIniciada}|${q.preguntaActual}"$)
'	m.Get("panel").As(Panel).Visible = False 'Ocultamos el panel de la pregunta.
	m.Get("panel").As(Panel).RemoveView 'Quitamos le panel de la pregunta
	DateTime.DateFormat = "yyyyMMdd"
	skmt.ExecNonQuery($"delete from CUESTIONARIO where Q_IDCLIENTE = '${Subs.traeCliente}' and Q_IDPREGUNTA = '${m.Get("idPregunta")}'"$)
	skmt.ExecNonQuery($"insert into CUESTIONARIO (Q_IDCLIENTE, Q_IDPREGUNTA, Q_PREGUNTA, Q_IDRESPUESTA, Q_RESPUESTA, Q_FECHA) values ('${Subs.traeCliente}', '${m.Get("idPregunta")}', '${m.Get("pregunta")}', '${m.Get("idRespuesta")}', '${m.Get("respuesta")}', '${DateTime.Date(DateTime.now)}')"$)
	Select Case m.Get("idPregunta")
		Case "1"
			If m.Get("respuesta") = "No, está enrejado o no se tiene acceso" Then
				Log("Tiendajon / Ventana / Kiosko")
				ToastMessageShow("Tiendajon / Ventana / Kiosko", False)
				q.agregaPregunta("6", "¿Cuenta con caja de salida para cobro con sistema de computo?", Array As String("Si, tiene sistema de computo para cobro", "No"))
			Else if m.Get("respuesta") = "Si se pude acceder" Then
				q.agregaPregunta("2", "¿Tiene al menos 2 pasillos con acceso directo a la mercancía?", Array As String("Si tiene al menos 2 pasillos con acceso directo a la mercancía", "No tiene pasillos o solo uno central"))
			End If
		Case "2"
			If m.Get("respuesta") = "Si tiene al menos 2 pasillos con acceso directo a la mercancía" Then
				Log("Mini-Super")
				ToastMessageShow("Mini-Super", False)
				q.agregaPregunta("6", "¿Cuenta con caja de salida para cobro con sistema de computo?", Array As String("Si, tiene sistema de computo para cobro", "No"))
			else If m.Get("respuesta") = "No tiene pasillos o solo uno central" Then
				q.agregaPregunta("3", "¿Cuenta con enfriador horizontal para venta de perecederos como queso, jamon, crema, etc.?", Array As String("Si", "No tiene enfriador horizontal."))
			End If
		Case "3"
			Log("|"&m.Get("respuesta")&"|")
			If m.Get("respuesta") = "Si" Then
				Log("Miscelanea")
				ToastMessageShow("Miscelanea", False)
				q.agregaPregunta("6", "¿Cuenta con caja de salida para cobro con sistema de computo?", Array As String("Si, tiene sistema de computo para cobro", "No"))
			else If m.Get("respuesta") = "No tiene enfriador horizontal." Then
				q.agregaPregunta("4", "¿El local esta enfocado a venta especializada?", Array As String("No", "Si"))
			End If
		Case "4"
			If m.Get("respuesta") = "No" Then
				Log("Abarrotera")
				ToastMessageShow("Abarrotera", False)
				q.agregaPregunta("6", "¿Cuenta con caja de salida para cobro con sistema de computo?", Array As String("Si, tiene sistema de computo para cobro", "No"))
			else If m.Get("respuesta") = "Si" Then
				q.agregaPregunta("5", "¿Cual venta especializada?", Array As String("Carnicería / Pollería", "Cremería", "Depósito / Vinateria", "Dulcería", "Farmacia", "Fonda / Restaurante / Cafetería", "Verdulería"))
			End If
		Case "5"
			Log(m.Get("respuesta"))
			ToastMessageShow(m.Get("respuesta"), False)
'			If m.Get("respuesta") = "No" Then
'				Log("Abarrotera")
'				q.agregaPregunta("5", "¿Cuenta con caja de salida para cobro con sistema de computo?", Array As String("Si, tiene sistema de computo para cobro", "No"))
'			else If m.Get("respuesta") = "Si" Then
			q.agregaPregunta("6", "¿Cuenta con caja de salida para cobro con sistema de computo?", Array As String("Si, tiene sistema de computo para cobro", "No"))
'			End If
		Case "6"
			Log(m.Get("respuesta"))
			ToastMessageShow(m.Get("respuesta"), False)
			Log(">>>>>>>>>>  " & q.encuestaIniciada)
			q.encuestaIniciada = False
			Log(">>>>>>>>>>  " & q.encuestaIniciada)
			refrescarCliente = True
'			Log($"####  REFRESCAR CLIENTE -> ${refrescarCliente}"$)
			B4XPage_Appear
'		Case 6
	End Select
End Sub

'Ajusta el tamaño del panel de scroll.
Sub ajustaTamano
'	Log("xx: " & sv_clientesDatos.Panel.Height)
'	Log($"${b_guardaCambios.Top} + 350"$)
	If l_cuestionario.Visible Then
		Log("visible")
		b_guardaCambios.Top = l_cuestionario.Top + l_cuestionario.Height + 20
	Else
		Log("INVisible")
		b_guardaCambios.Top = b_mapa2.Top + b_mapa2.Height + 20
	End If
	
	
	p_cliente.Height = b_guardaCambios.Top + 350
	sv_clientesDatos.Panel.Height = p_cliente.Height
'	Log("xx: " & sv_clientesDatos.Panel.Height)
End Sub

'Private Sub Label9_LongClick
''	Log(b_guardaCambios.Top)
'	If l_cuestionario.Visible Then
'		l_cuestionario.Visible = False
'		l_tituloCuestionaro.Visible = False
''		b_guardaCambios.Top = b_mapa2.Top + b_mapa2.Height + 20
''		Log($"${b_mapa2.Top} + ${b_mapa2.Height} + 20dip"$)
'	Else
'		l_cuestionario.Visible = True
'		l_tituloCuestionaro.Visible = True
''		b_guardaCambios.Top = l_cuestionario.Top + l_cuestionario.Height + 20
''		Log($"${l_cuestionario.Top} + ${l_cuestionario.Height} + 20"$)
'	End If
''	Log(b_guardaCambios.Top)
'	ajustaTamano
'End Sub


Private Sub l_cuestionario_LongClick
	Log("BORRAMOS CUESTIONARIO")
	res = Msgbox2("Seguro que desea borrar el cuestionario para este cliente?", "ATENCIÓN", "Borrar", "Cancelar", "", Null)
	If res = DialogResponse.POSITIVE Then
		skmt.ExecNonQuery($"delete from CUESTIONARIO where Q_IDCLIENTE = '${Subs.traeCliente}'"$)
		B4XPage_Appear
	End If
End Sub