Option Strict On Option Explicit On Imports System.Data Imports System.IO Imports System.Net Imports Extensiones Imports Microsoft.Reporting.WebForms Imports Newtonsoft.Json.Linq Imports System.Linq Imports System.Net.Http Imports System.Net.Http.Headers Imports Newtonsoft.Json Partial Class GPS_TrayectoDetalle Inherits ClsPaginas #Region "P R O P I E D A D E S" Private Property DtGeocercas As DataTable Get Return CType(ViewState("DtGeocercas"), DataTable) End Get Set(value As DataTable) ViewState("DtGeocercas") = value End Set End Property Private Property DtPosiciones As DataTable Get Return CType(ViewState("DtPosiciones"), DataTable) End Get Set(value As DataTable) ViewState("DtPosiciones") = value End Set End Property Private Property CveTrayecto As Integer Get Return CType(ViewState("CveTrayecto"), Integer) End Get Set(value As Integer) ViewState("CveTrayecto") = value End Set End Property Private Property CveEstatusActual As Integer Get Return CType(ViewState("CveEstatusActual"), Integer) End Get Set(value As Integer) ViewState("CveEstatusActual") = value End Set End Property Private Property OrdenActual As Integer Get Return CType(ViewState("OrdenActual"), Integer) End Get Set(value As Integer) ViewState("OrdenActual") = value End Set End Property #End Region Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Page.IsPostBack Then DirectCast(Master.FindControl("TSM"), ScriptManager).EnablePageMethods = True CveTrayecto = Request("CveTrayecto").ToString().ToEntero() If CveTrayecto > 0 Then CargaTrayectoHistorial(CveTrayecto) CargaReporte() End If End If End Sub Private Sub CargaTrayectoHistorial(CveTrayecto As Integer) If CveTrayecto > 0 Then Dim CveDispositivo As Integer = -1 Dim ObjGPS As New ClsGPS Dim DtEstatusHistorial As DataTable = Nothing Dim DtPuntosInteres As DataTable = Nothing Dim DsDatos As DataSet = Nothing Dim FechaInicio As DateTime = MinFecha Dim FechaFin As DateTime = MaxFecha Try If ObjGPS.GetTrayectosDatos(CveTrayecto) Then DsDatos = ObjGPS.DtSetResultados.Copy If DsDatos IsNot Nothing AndAlso DsDatos.Tables.Count > 0 Then CveDispositivo = DsDatos.Tables(0).Rows(0)("CveDispositivo").ToString().ToEntero If Not String.IsNullOrEmpty(DsDatos.Tables(0).Rows(0)("FechaInicio").ToString()) Then FechaInicio = DsDatos.Tables(0).Rows(0)("FechaInicio").ToString().ToDateTime End If If Not String.IsNullOrEmpty(DsDatos.Tables(0).Rows(0)("FechaFin").ToString()) Then FechaFin = DsDatos.Tables(0).Rows(0)("FechaFin").ToString().ToDateTime End If End If End If If ObjGPS.GetTrayectosGeoReferencias(CveTrayecto) Then DtGeocercas = ObjGPS.DtResultados.Copy End If 'If ObjGPS.GetTrayectosHistorial(CveTrayecto, UsuarioActual.CveCliente) Then ' DtPosiciones = ObjGPS.DtResultados.Copy() 'End If If CveDispositivo > 0 Then If ObjGPS.UltimaPosicionEquipoGet(CveDispositivo.ToString(), UsuarioActual.CveCliente) Then DtPosiciones = ObjGPS.DtResultados.Copy() End If End If If ObjGPS.GetTrayectosEstatusHistorial(CveTrayecto) Then DtEstatusHistorial = ObjGPS.DtResultados.Copy End If If FechaInicio > MinFecha Then If FechaFin <= MinFecha Then FechaFin = MaxFecha End If If ObjGPS.RepPuntosGet(-1, CveDispositivo.ToString(), FechaInicio, FechaFin, UsuarioActual.CveCliente) Then DtPuntosInteres = ObjGPS.DtResultados.Copy End If End If Catch ex As Exception OnError("Ocurrió un error al consultar el trayecto.", ex) End Try ObjGPS.Dispose() Try RegistraScript("initMap();") If DtEstatusHistorial IsNot Nothing AndAlso DtEstatusHistorial.Rows.Count > 0 Then Dim Direcciones = ConsultarDirecciones(DtEstatusHistorial) For Each Dir As JObject In Direcciones DtEstatusHistorial.Rows(Dir("Indice").ToEntero())("Direccion") = Dir("Direccion").ToString() Next GvEstatus.DataSource = DtEstatusHistorial GvEstatus.DataBind() End If If DsDatos IsNot Nothing AndAlso DsDatos.Tables.Count > 0 Then Dim RowEstatus As DataRow = DsDatos.Tables(0).Rows(0) LblTitulo.Text = $"Trayecto: {RowEstatus("Trayecto")}" LtlEstatusActual.Text = RowEstatus("Estatus").ToString() CveEstatusActual = RowEstatus("CveEstatusActual").ToString().ToEntero() OrdenActual = RowEstatus("OrdenActual").ToString().ToEntero() If CBool(RowEstatus("EsFin")) Then BtnTerminarTrayeto.Visible = False LnkActualizarEstatus.Visible = False BtnRecalcular.Visible = False LblETA.Text = "TERMINADO" End If LtlDispositivo.Text = RowEstatus("Vehiculo").ToString() LtlFechaI.Text = If(String.IsNullOrEmpty(RowEstatus("FechaInicio").ToString()), "No ha ingresado a la geocerca de inicio", String.Format("{0:dd/MM/yyyy HH:mm tt}", RowEstatus("FechaInicio").ToString().ToDateTime())) LtlFechaF.Text = If(String.IsNullOrEmpty(RowEstatus("FechaFin").ToString()), "No ha terminado", String.Format("{0:dd/MM/yyyy HH:mm tt}", RowEstatus("FechaFin").ToString().ToDateTime())) LtlVMedia.Text = String.Format("{0:N2} KM/H", RowEstatus("VMedia")) LtlVMax.Text = String.Format("{0:N2} KM/H", RowEstatus("VMax")) LtlTiempo.Text = String.Format("{0}", RowEstatus("TiempoOperativo")) LtlKM.Text = String.Format("{0:N2} KM", RowEstatus("Dist")) LtlExcesosVelo.Text = String.Format("{0}", RowEstatus("ExcesosVelocidad")) LtlCombustibleI.Text = If(String.IsNullOrEmpty(RowEstatus("CombustibleInicial").ToString()), "No Disponible", String.Format("{0:N2}", RowEstatus("CombustibleInicial"))) LtlCombustibleF.Text = If(String.IsNullOrEmpty(RowEstatus("CombustibleFinal").ToString()), "No Disponible", String.Format("{0:N2}", RowEstatus("CombustibleFinal"))) LtlCargas.Text = String.Format("{0:N0}", RowEstatus("Cargas")) LtlDescargas.Text = String.Format("{0:N0}", RowEstatus("Descargas")) LtlCombustibleConsumido.Text = String.Format("{0:N2} L", RowEstatus("CombustibleConsumido")) LtlRendimiento.Text = String.Format("{0:N2} KM/L", RowEstatus("Rendimiento")) GvIgnicion.DataSource = DsDatos.Tables(1) GvIgnicion.DataBind() Dim DtExcesos As DataTable = DsDatos.Tables(2) Dim Direcciones = ConsultarDirecciones(DtExcesos) If Direcciones IsNot Nothing Then For Each Dir As JObject In Direcciones DtExcesos.Rows(Dir("Indice").ToEntero())("Direccion") = Dir("Direccion").ToString() Next End If GvExcesos.DataSource = DtExcesos GvExcesos.DataBind() GvRalenti.DataSource = DsDatos.Tables(3) GvRalenti.DataBind() GvCombustible.DataSource = DsDatos.Tables(4) GvCombustible.DataBind() GvGastos.DataSource = DsDatos.Tables(5) GvGastos.DataBind() End If Dim count = 0 If DtPosiciones IsNot Nothing AndAlso DtPosiciones.Rows.Count > 0 Then Dim Fecha, Vehiculo, Icono, CoordDis, Info As String For Each Row As DataRow In DtPosiciones.Rows count += 1 CoordDis = Row("Posicion").ToString.SQLToGmaps("POINT") Fecha = Row("FechaTrama").ToString Vehiculo = Row("NombreVehiculo").ToString Info = InfoWindow($"{Vehiculo}", "-1", Row("CveDispositivo").ToString.ToEntero, Row, PermisoComandos:=False) If Row("Velocidad").ToString.ToDouble > 1 Then Icono = $"/Imagenes/{Row("Icono")}green.png" Else Icono = $"/Imagenes/{Row("Icono")}.png" End If RegistraScript($"CreaMarcador({CoordDis},'{Vehiculo}', '{Info}', '{Icono}');", count.ToString()) Next End If If DtGeocercas IsNot Nothing AndAlso DtGeocercas.Rows.Count > 0 Then Dim Coord As String = "" Dim CoordAnterior As String = "" Dim CveEstatus As Integer = -1 Dim CveEstatusAnterior As Integer = -1 Dim GeoreferenciaASeguir As String = "" Dim EstatusSiguiente As String = "" Dim OrdenEstatus As Integer = 0 'GEOCERCAS For Each Row As DataRow In DtGeocercas.Rows count += 1 Coord = SQLToGmaps(Row("Geom").ToString, "POLYGON") CveEstatus = Row("CveEstatusTrayecto").ToString.ToEntero CveEstatusAnterior = Row("CveEstatusAnterior").ToString.ToEntero OrdenEstatus = Row("OrdenEstatus").ToString.ToEntero Dim EsInicio As Boolean = CBool(IfNull(Row("EsInicio"), 0)) Dim EsFin As Boolean = CBool(IfNull(Row("EsFin"), 0)) Dim InicioFin As Integer = If(EsInicio, 1, If(EsFin, 2, 0)) Dim Cruzo As String = IfNull(Row("Cruzo"), "0").ToString() 'MARCA PARA QUE NO CALCULE EL TIEMPO DE LAS GEOCERCAS RESTANTES If Not String.IsNullOrEmpty(GeoreferenciaASeguir) Then Cruzo = "1" End If 'VERIFICA SI SE ACTUALIZO MANUALMENTE If Cruzo = "0" Then If OrdenEstatus <= OrdenActual Then Cruzo = "1" End If End If If Cruzo = "0" Then GeoreferenciaASeguir = Row("GeoReferencia").ToString() EstatusSiguiente = Row("EstatusTrayecto").ToString() End If RegistraScript($"creaPoligono({Coord}, '{Row("Color").ToString}', '{Row("GeoReferencia")}', '{Row("EstatusTrayecto")}',{InicioFin},{CveEstatus},{CveEstatusAnterior},{Cruzo},'{GeoreferenciaASeguir}','{EstatusSiguiente}')", count.ToString()) Next End If If DtPuntosInteres IsNot Nothing Then Dim SBBody As New StringBuilder Dim CoordsPoligono = "" Dim Coords = "" Dim Titulo = "" Dim Info = "" Dim GeoCercas = "" Dim Color = "" For Each RowPI As DataRow In DtPuntosInteres.Rows count += 1 Coords = SQLToGmaps(RowPI("Punto").ToString, "POINT") SBBody.Append($"
") SBBody.Append($"
Punto: {RowPI("PuntoDeInteres")}
") Color = "#26C281" SBBody.Append($"
") SBBody.Append($"") SBBody.Append($"") SBBody.Append($"
{RowPI("Vehiculo")}: {RowPI("Visitas")} visitas
Última Visita: {RowPI("UltimaVisita")}
") SBBody.Append($"
") RegistraScript($"CreaCirculo({Coords},'{Color}');CreaMarcadorPI({Coords},'{RowPI("PuntoDeInteres")}','{SBBody.ToString}');", count.ToString()) Next count += 1 RegistraScript("CalcularETA();", count.ToString()) End If Catch ex As Exception OnError("Ocurrió un error al cargar los datos del trayecto", ex) End Try End If UpIgniciones.Update() UpEventos.Update() End Sub Public Sub CargaReporte() Dim ObjGPS As New ClsGPS If ObjGPS.GetTrayectosDetalle(CveTrayecto) Then Dim Direcciones = ConsultarDirecciones(ObjGPS.DtResultados) If Direcciones IsNot Nothing Then For Each Dir As JObject In Direcciones ObjGPS.DtResultados.Rows(Dir("Indice").ToEntero())("Direccion") = Dir("Direccion").ToString() Next End If GvEventos.DataSource = ObjGPS.DtResultados End If ObjGPS.Dispose() GvEventos.DataBind() UpEventos.Update() 'RegistraScript("$('#ShowDiv3').click();") End Sub Public Function ConsultarDirecciones(Dt As DataTable) As JArray Dim retorno As JArray = Nothing Dim posicionesArray = New JArray(From Row As DataRow In Dt Let index = Dt.Rows().IndexOf(Row) Select New JObject( New JProperty("indice", index), New JProperty("cveTrama", -1), New JProperty("lat", Row("Lat").ToString.ToDouble), New JProperty("lon", Row("Lng").ToString.ToDouble) )) Dim Base64array = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(posicionesArray.ToString())) Using wc As New HttpClient() Try Dim Url = New Uri(String.Format("{0}nominatim/reverseMultiple.php", ClsPaginas.UrlDirecciones)) Dim FormStuff = String.Format("formato=json&posiciones={0}", Base64array) Dim content = New StringContent(FormStuff, Encoding.UTF8, "application/x-www-form-urlencoded") Dim response = wc.PostAsync(Url, content).Result Dim result = response.Content.ReadAsStringAsync().Result retorno = JArray.Parse(result) response.Dispose() content = Nothing Url = Nothing FormStuff = Nothing Catch ex As Exception OnError("Ocurrió un error al obtener las direcciones", ex) End Try End Using Return retorno End Function Protected Sub BtnTerminarTrayeto_Click(sender As Object, e As EventArgs) Dim DtEstatus As DataTable = Nothing Dim ObjGPS As New ClsGPS Try Dim CveEstatusFinal As Integer = -1 If ObjGPS.GetTrayectosGeoReferencias(CveTrayecto) Then 'TOMA LA GEOCERCA FINAL Dim Row As DataRow = ObjGPS.DtResultados.FiltroPrimero($"EsFin = True") If Row IsNot Nothing Then CveEstatusFinal = Row("CveEstatusTrayecto").ToString().ToEntero() End If End If If CveEstatusFinal > 0 Then If ObjGPS.UpdateTrayectoEstatus(CveTrayecto, CveEstatusFinal) Then Alert("El trayecto se finalizo correctamente", JSBtnAceptar:="RefrescarPagina();", ShowCloseButton:=False) End If Else Alert("No se pudo obtener el estatus final", TipoMensaje.MsgError) End If 'If ObjGPS.GetEstatusTrayectos(-1, UsuarioActual.CveCliente) Then ' DtEstatus = ObjGPS.DtResultados.Copy() 'End If 'Dim CveEstatusFinal As Integer = DtEstatus.FiltroPrimeroValor("CveEstatusTrayecto", "EsFin = True").ToEntero() 'If CveEstatusFinal > 0 Then ' If ObjGPS.UpdateTrayectoEstatus(CveTrayecto, CveEstatusFinal) Then ' Alert("El trayecto se finalizo correctamente", JSBtnAceptar:="RefrescarPagina();", ShowCloseButton:=False) ' End If 'Else ' Alert("No se pudo obtener el estatus final", TipoMensaje.MsgError) 'End If Catch ex As Exception OnError("Ocurrió un error al actualizar el trayecto", ex) End Try ObjGPS.Dispose() End Sub Protected Sub GvGastos_RowDataBound(sender As Object, e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then If String.IsNullOrEmpty(e.Row.DBCampo("CveGPSGasto")) Then e.Row.CssClass = "Totales" End If End If End Sub Protected Sub LimpiaModal() TxtCantidad.Text = "" TxtPrecio.Text = "" TxtDescripcion.Text = "" TxtObs.Text = "" TxtFecha.Text = "" End Sub Protected Sub LnkAgregar_Click(sender As Object, e As EventArgs) LimpiaModal() 'Modalidad = "A" BtnGuardar.Text = "Agregar" ltlMotititulo.Text = "Agregar Gasto" UpModal.Update() RegistraScript("$('#DModal').modal()") End Sub Protected Sub BtnGuardar_Click(sender As Object, e As EventArgs) Dim ObjPS As New ClsGPS 'If Modalidad = "A" Then 'ElseIf Modalidad = "U" Then ' If ObjPS.UpdateGasto(CveGPSGasto, TxtCantidad.Text.ToDecimal(), TxtPrecio.Text.Trim().ToDecimal(), TxtDescripcion.Text.Trim(), TxtObs.Text.Trim(), TxtFecha.Text.ToDateTime(), UsuarioActual.CveUsuario) Then ' RegistraScript("$('#DModal').modal('hide')") ' Alert("El Gasto se agregó correctamente.", TipoMensaje.MsgInformacion) ' End If 'End If If ObjPS.AddGasto(TxtCantidad.Text.ToDecimal(), TxtPrecio.Text.Trim().ToDecimal(), TxtDescripcion.Text.Trim(), TxtObs.Text.Trim(), TxtFecha.Text.ToDateTime(), 2, UsuarioActual.CveUsuario, UsuarioActual.CveCliente, CveTrayecto:=Me.CveTrayecto) Then RegistraScript("$('#DModal').modal('hide')") Alert("El Gasto se agregó correctamente.", TipoMensaje.MsgInformacion) End If ObjPS.Dispose() 'CargaDatos() End Sub Protected Sub BtnRecalcular_Click(sender As Object, e As EventArgs) If CveTrayecto > 0 Then CargaTrayectoHistorial(CveTrayecto) CargaReporte() End If End Sub Protected Sub LnkActualizarEstatus_Click(sender As Object, e As EventArgs) Dim CveEstatusSiguiente As Integer = -1 Dim Estatus As String = "" Using ObjGPS As New ClsGPS If ObjGPS.GetTrayectosGeoReferencias(CveTrayecto) Then If CveEstatusActual = 1 Then 'TOMA LA GEOCERCA DE INICIO Dim Row As DataRow = ObjGPS.DtResultados.FiltroPrimero($"EsInicio = True") If Row IsNot Nothing Then CveEstatusSiguiente = Row("CveEstatusTrayecto").ToString().ToEntero() End If Else Dim Row As DataRow = ObjGPS.DtResultados.FiltroPrimero($"CveEstatusTrayecto = {CveEstatusActual}") If Row IsNot Nothing Then CveEstatusSiguiente = Row("CveEstatusSiguiente").ToString().ToEntero() End If End If End If If CveEstatusSiguiente > 0 Then If ObjGPS.GetEstatusTrayectos(CveEstatusSiguiente, UsuarioActual.CveCliente) Then Estatus = ObjGPS.DtResultados.FiltroPrimeroValor("Estatus") End If If Not String.IsNullOrEmpty(Estatus) Then If ObjGPS.UpdateTrayectoEstatus(CveTrayecto, CveEstatusSiguiente) Then Alert($"El trayecto se cambió al estatus {Estatus}.", JSBtnAceptar:="RefrescarPagina();", ShowCloseButton:=False) End If Else Alert("No se pudo cambiar al estatus siguiente.", TipoMensaje.MsgError) End If Else Alert("No se pudo cambiar al estatus siguiente.", TipoMensaje.MsgError) End If End Using End Sub Private Sub BtnRefrescarPagina_Click(sender As Object, e As EventArgs) Handles BtnRefrescarPagina.Click Response.Redirect($"~/GPS/TrayectoDetalle.aspx?CveTrayecto={Me.CveTrayecto}") End Sub End Class