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 g As GPS
	Dim ruta As String
	Dim c As Cursor
	Dim reqManager As DBRequestManager
	Dim CANCELA As Button
	Dim GUARDA As Button
	Dim cuenta As String
	Dim usuario As String
	Dim sDate,sTime As String
	Dim sDate2,sTime2 As String
	Dim no_cliente As String
	Dim no_ruta As String
	Dim desdeBD As Boolean
	Dim r_4 As RadioButton
	Dim E_NOMBRE As EditText
	Dim tgl As Toggle
	Private l_sinUbicacion As Label
	Private p_nuevoCliente As Panel
	Private Label1 As Label
	Private p_botones As Panel
	Private p_cam As Panel
	Private p_camara As Panel
	Private b_foto_inci As Button
	Private camEx2 As CameraExClass2
	Dim frontCamera As Boolean = False
	Dim fototomada As String = "0"
	Dim ALMACEN As String
	Private et_direccion As EditText
	Private Label2 As Label
	Dim lat As Double = 0
	Dim lon As Double = 0
	Private b_ubicacion As Label
	Private Label3 As Label
	Private et_colonia As EditText
	Private Label4 As Label
	Private et_cp As EditText
	Private lv_colonia As ListView
	Dim banderasepo 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
	Root.LoadLayout("nuevocliente")
	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)
'	p_camara.Height = Root.Height
'	p_camara.Width = Root.Width
	reqManager.Initialize(Me, B4XPages.MainPage.SERVER)
End Sub

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

Sub B4XPage_Appear
	E_NOMBRE.Text =  ""
	et_colonia.Text = ""
	et_cp.Text = ""
	et_direccion.Text = ""
	lv_colonia.Visible = False
	lv_colonia.Clear
	If Not(Starter.gps.GPSEnabled) Then
		ToastMessageShow("Es necesario tener el GPS encendido", True)
		StartActivity(Starter.gps.LocationSettingsIntent)
	End If
	GUARDA.Visible = False
	Subs.panelVisible(p_nuevoCliente, 0, 0)
	p_nuevoCliente.Height = Root.Height
	p_nuevoCliente.Width = Root.Width
	Subs.centraEtiqueta(Label1, Root.Width)
	Subs.centraEtiqueta(Label2, Root.Width)
	Subs.centraEtiqueta(Label3, Root.Width)
	Subs.centraEtiqueta(Label4, Root.Width)
	Subs.centraEtiqueta(l_sinUbicacion, Root.Width)
	Subs.centraEtiqueta(b_ubicacion, Root.Width)
	Subs.centraPanel(p_botones, Root.Width)
	E_NOMBRE.Left = Round(Root.Width/2)-(E_NOMBRE.Width/2)
	et_direccion.Left = Round(Root.Width/2)-(E_NOMBRE.Width/2)
	et_colonia.Left = Round(Root.Width/2)-(E_NOMBRE.Width/2)
	et_cp.Left = Round(Root.Width/2)-(E_NOMBRE.Width/2)
	If B4XPages.MainPage.lat_gps <> "0.0" Then
		GUARDA.Visible = True 'Si hay ubicaccion, mostramos el boton de guardar.
		l_sinUbicacion.Visible = False
	End If
	
	If Not(Starter.GPS.GPSEnabled) Then
		ToastMessageShow("Debe Activar el GPS del Equipo.", True)
		StartActivity(Starter.GPS.LocationSettingsIntent)
	Else
		Starter.GPS.Start(0, 0)
'		If Starter.ubicacionActual.Latitude <> 0 Then GPS_LocationChanged(Starter.ubicacionActual)
	End If
	CallSubDelayed(Tracker, "StartFLPSmall")
	desdeBD = False
End Sub

Sub GPS_LocationChanged (Location1 As Location)
	If B4XPages.MainPage.lat_gps <> "0.0" Then
		GUARDA.Visible = True 'Si hay ubicaccion, mostramos el boton de guardar.
		l_sinUbicacion.Visible = True
		lat = Location1.Latitude
		lon = Location1.Longitude
		l_sinUbicacion.Text = ("Latitud: " & lat & ", Longotud: "& lon)
	End If
	
	b_ubicacion.TextSize = 13
	b_ubicacion.Text = $"Precisión GPS $1.0{Location1.Accuracy} m"$
	If Location1.Accuracy > 200 Then
		b_ubicacion.TextColor = Colors.Red
		b_ubicacion.TextSize = 16
		b_ubicacion.Text = $"Mala señal $1.0{Location1.Accuracy} m"$
	End If
End Sub

Sub CANCELA_Click
	B4XPages.ShowPage("Principal")
	CallSubDelayed(Tracker, "StartFLP")
	lv_colonia.Clear
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_cp_TextChanged (Old As String, New As String)
	If Not(desdeBD) And New.Length = 5 Then
		Private cc As Cursor = B4XPages.MainPage.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
			Next
		End If
	else if New.Length < 5 Then
		lv_colonia.Visible = False
	End If
	desdeBD = False
End Sub


Private Sub et_colonia_FocusChanged (HasFocus As Boolean)
	If HasFocus Then
		Private cc As Cursor = B4XPages.MainPage.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
			lv_colonia.AddSingleLine("Ingrese colonia manualmente.")
		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
		banderasepo = 0
	Else
		banderasepo = 1
	End If
End Sub

Sub GUARDA_Click
	If E_NOMBRE.Text =  "" Then
		MsgboxAsync("Por favor captura el nombre de la Tienda","Atención")
	Else
		If et_direccion.Text.Length > 3 Then
			If lat <> 0 Then
				If et_colonia.Text.Length > 3 Then
					If et_cp.Text.Length > 3 Then
				
						DateTime.DateFormat = "MM/dd/yyyy"
						DateTime.Timeformat = "HHmmss"
						sDate=DateTime.Date(DateTime.Now)
						sTime=DateTime.Time(DateTime.Now)
						Log($" ////////////   Date: ${sDate} - Time: ${sTime} ////////////////"$)
						'Aqui creamos manualmete la hora con el separador de los 2 puntos porque en algunas versiones de android no respeta el formato "Timeformat = 'HH:mm:ss'"
						Private hora As String = sTime.SubString2(0,2)
						Private mins As String = sTime.SubString2(2,4)
						Private segs As String = sTime.SubString(4)
						sTime = hora&":"&mins&":"&segs
						Log("////////////// sTime: "&sTime&" ////////////////")
						c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA FROM kmt_info")
						c.Position=0
						no_ruta= c.GetString("CAT_CL_RUTA")
						no_cliente= "N" & sTime & no_ruta
						Log("++ ++ no_cliente = "&no_cliente)
						c.Close
						B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO kmt_info(CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO, gestion) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,0) ",Array As Object (no_cliente,no_ruta, E_NOMBRE.Text,"null","null","null","null","null","null","null","null","null","null","null","null","null",B4XPages.MainPage.lon_gps,B4XPages.MainPage.lat_gps))
						B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_STAY_STORE(HSS_CODIGO,  HSS_IN , HSS_OUT , HSS_TOT) VALUES (?,0,0,0)", Array As Object (no_cliente))
						B4XPages.MainPage.skmt.ExecNonQuery("delete from CUENTAA")
						B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object(no_cliente))
						c=B4XPages.MainPage.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
						If c.RowCount>0 Then
							C.Position=0
							ALMACEN = C.GetString("ID_ALMACEN")
						End If
						c.Close
						c=B4XPages.MainPage.skmt.ExecQuery("select usuario from usuarioa")
						c.Position = 0
						usuario = c.GetString("USUARIO")
						c.Close
'					B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO  NOVENTA (NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_LAT,NV_LON,NV_NOMBRE,NV_DIRECCION) VALUES(?,?,?,?,?,?,?,?) ", Array As Object (no_cliente,sDate & sTime, usuario, "NUEVO CLIENTE", lat, lon, E_NOMBRE.Text,et_direccion.Text))
					
						DateTime.DateFormat = "dd/MM/yyyy"
						DateTime.Timeformat = "HH:mm:ss"
						sDate2=DateTime.Date(DateTime.Now)
						sTime2=DateTime.Time(DateTime.Now)
					
						B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO CLIENTES_NUEVOS(CN_ID, CN_FECHA, CN_USER, CN_LAT, CN_LON, CN_NOMBRE, CN_DIRECCION, COLONIA, CP, CN_ALMACEN, CN_RUTA, CN_ENVIO,CN_BANDERA) VALUES (?,?,?,?,?,?,?,?,?,?,?,0,?)",Array As String(no_cliente,sDate2 &" "&sTime2, usuario, lat, lon, E_NOMBRE.Text,et_direccion.Text,et_colonia.Text, et_cp.Text, ALMACEN, no_ruta,banderasepo))
						fototomada = "0"
						B4XPages.ShowPage("cliente")
						CallSubDelayed(Tracker, "StartFLP")
						
						mandaPendientesclientesnuevos
					Else
						MsgboxAsync("Por favor captura el C.P. del cliente","Atención")
					End If
				Else
					MsgboxAsync("Por favor captura la colonia del cliente","Atención")
				End If		
			Else
				MsgboxAsync("Por favor revisa que tengas señal GPS","Atención")
			End If
		Else
			MsgboxAsync("Por favor captura la dirección del cliente","Atención")
		End If
	End If
End Sub


Sub mandaPendientesclientesnuevos
	c=B4XPages.MainPage.skmt.ExecQuery("SELECT  CN_ID, CN_FECHA , CN_USER, CN_LAT, CN_LON, CN_NOMBRE, CN_DIRECCION, COLONIA, CP, CN_ALMACEN, CN_RUTA, CN_BANDERA FROM CLIENTES_NUEVOS where CN_ENVIO <> 1")
	If c.RowCount>0 Then
		For i = 0 To c.RowCount - 1
			c.Position = i
				
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_clientesnuevos2_MEDI"
			cmd.Parameters = Array As Object(c.GetString("CN_ID"), c.GetString("CN_FECHA"), c.GetString("CN_USER"), c.GetString("CN_LAT"), c.GetString("CN_LON"), c.GetString("CN_NOMBRE"), c.GetString("CN_DIRECCION"),c.GetString("COLONIA"),c.GetString("CP"),c.GetString("CN_ALMACEN"), c.GetString("CN_RUTA"),c.GetString("CN_BANDERA"))
'													TMP_ID_CLIENTEN, TMP_FECHA_CAPTURA_MOVIL, 	TMP_USUARIO, 				TMP_LATITUD, 			TMP_LONGITUD, 			TMP_NOMBRE, 				TMP_DOMICILIO, 			TMP_COLONIA, 		TMP_CP, 				TMP_ALMACENID,				TMP_RUTA,
			reqManager.ExecuteCommand(cmd , $"ins_CNUEVOSPendientes_head_${c.GetString("CN_ID")}"$)
		Next
	End If
	c.Close
End Sub


Sub JobDone(Job As HttpJob)
	Log(Job.Success)
	If Job.Success = False Then
'		ToastMessageShow("Error: " & Job.ErrorMessage, True)
	Else
		LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green)  'Mod por CHV - 211027
		If Job.JobName = "DBRequest" Then
			Dim resultado As DBResult = reqManager.HandleJob(Job)
			If resultado.Tag.As(String).IndexOf("ins_CNUEVOSPendientes_head_") > -1 Then
				Private cliente As String= resultado.Tag
				cliente = cliente.SubString(cliente.IndexOf("_")+24)
				Log($"Cliente1:${cliente}"$)
				B4XPages.MainPage.skmt.ExecNonQuery2("update CLIENTES_NUEVOS SET CN_ENVIO = ? WHERE CN_ID = ? AND CN_ENVIO <> 1",Array As String ("1", cliente))
				For Each records() As Object In resultado.Rows
					For Each k As String In resultado.Columns.Keys
						Log(resultado.Tag & ": " & k & ": " & records(resultado.Columns.Get(k)))
					Next
				Next
			End If
		End If
		Job.Release
	End If
End Sub


Private Sub p_nuevoCliente_Click
	
End Sub

Private Sub b_foto_inci_Click
	camEx2.TakePicture
	p_camara.Visible = False
'	StopCamera2
End Sub

Private Sub InitializeCamera2
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_CAMERA)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		camEx2.Initialize(p_cam, frontCamera, Me, "Camera1")
		frontCamera = camEx2.Front
		Log("inicializamos Camara")
	Else
		ToastMessageShow("No permission!!!", True)
	End If
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		Log("conpermisos para escritura")
	Else
		ToastMessageShow("No permission!!!", True)
	End If
	
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_EXTERNAL_STORAGE)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		Log("conpermisos para escritura")
	Else
		ToastMessageShow("No permission!!!", True)
	End If
End Sub

Sub Camera1_Ready (Success As Boolean)
	Log("Camara ready")
	If Success Then
		camEx2.SetJpegQuality(90)
		camEx2.SetContinuousAutoFocus
		camEx2.CommitParameters
		camEx2.StartPreview
		Log(camEx2.GetPreviewSize)
	Else
		ToastMessageShow("Cannot open camera.", True)
		Log("Cannot open camera")
	End If
End Sub

Sub Camera1_PictureTaken (Data()As Byte)
	Log("tome foto")
	Dim filename As String = fototomada
	Dim Dirp As String = File.DirInternal
	Dim Dir As String
	Dim Dir2 As String
	Try
		File.MakeDir(Dirp,"/promotoriakmts")
		Dir = "/promotoriakmts"
		Log("creado en promotoria " & Dirp & Dir)
	Catch
		Dir = ""
		Log("creado en raiz")
	End Try
	
	Try
		File.MakeDir(Dirp & Dir,"/reduccion")
		Dir2 = "/reduccion"
		Log("creado en promotoria " & Dirp & Dir & Dir2)
	Catch
		Dir = ""
		Log("creado en raiz")
	End Try
	
	camEx2.SavePictureToFile(Data, Dirp&Dir, filename)
	camEx2.StartPreview 'restart preview
	ToastMessageShow("Picture saved." & CRLF  & "File size: " & File.Size(Dir, filename) & Dir &"," & filename, True)
	Log("Picture saved." & CRLF  & "File size: " & File.Size(Dir, filename) & Dir &"," & filename)
	p_camara.Visible = False
	StopCamera2
	
End Sub

Private Sub StopCamera2
'	Capturing = False
	If camEx2.IsInitialized Then
		camEx2.Release
	End If
End Sub


Private Sub B_FOTO_Click
	DateTime.DateFormat="ddMMyyyyHHmmss"
	InitializeCamera2
	Subs.panelVisible(p_camara, 0, 0)
	fototomada = DateTime.Now & "_cliente.jpg"
End Sub


