Imports System.Net
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Net.Security
Imports System.Threading.Tasks
Imports Newtonsoft.Json
Imports WebIntranet.Models

Public Class gestDelegados
    Inherits System.Web.UI.Page
    'Shared sessionUsuario As String
    'Shared usuariosSeleccionados As List(Of String)
    'Shared liPer As List(Of Personal)
    Public liDepartamento As New List(Of String)
    Protected Async Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Session("Persona") Is Nothing Then
            Response.Redirect("default.aspx", False)
        Else
            Dim usuario
            Dim clave = Session("pass")

            If Session("LDAP") IsNot Nothing Then
                usuario = Session("LDAP")
            Else
                usuario = Session("usuario")
            End If


            Dim RespIden As Models.ResultadoIdentificacion
            Dim client = HttpClientFactory.Create()
            client.BaseAddress = New Uri(UtilAntifraude.urlSwagger())
            client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", Session("token"))
            Dim loginResponse = Await client.GetAsync("api/ResultadoIdentificacion/nif/" + usuario + "/Origen/WEBINTRANET").ConfigureAwait(False)
            Dim responseContent = Await loginResponse.Content.ReadAsStringAsync().ConfigureAwait(False)
            RespIden =
                Newtonsoft.Json.JsonConvert.DeserializeObject(Of Models.ResultadoIdentificacion)(responseContent)


            'Dim objetoConsulta As New Models.Identificacion
            'objetoConsulta.Nif = usuario
            'objetoConsulta.clave = clave
            'objetoConsulta.origen = "WEBINTRANET"
            'objetoConsulta.resultado = ""

            'Dim jsonConsulta As String = JsonConvert.SerializeObject(objetoConsulta)
            'Dim url As String = ConfigurationManager.AppSettings("RutaRes").ToString + "/api/Identificacion"

            'Dim clienteHTTP As New HttpClient
            'Dim contenidoConsultaHTTP As New StringContent(jsonConsulta, Encoding.UTF8, "application/json")
            'Debug.WriteLine("CargarListadodePicadasAsync:1===" + Now.ToLongTimeString)
            'Dim respuestaHTTP As HttpResponseMessage = Await clienteHTTP.PostAsync(url, contenidoConsultaHTTP).ConfigureAwait(True)
            'Debug.WriteLine("CargarListadodePicadasAsync:2===" + Now.ToLongTimeString)
            'Dim sRespuesta As String = Await respuestaHTTP.Content.ReadAsStringAsync().ConfigureAwait(True)
            'Debug.WriteLine("CargarListadodePicadasAsync:3===" + Now.ToLongTimeString)

            'Dim settings As New Newtonsoft.Json.JsonSerializerSettings()

            'settings.CheckAdditionalContent = True
            'Dim objetoDatos As ResultadoIdentificacion =
            '        Newtonsoft.Json.JsonConvert.DeserializeObject(Of ResultadoIdentificacion)(sRespuesta, settings)


            'ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(Function() True)
            'Dim url1 As String = ConfigurationManager.AppSettings("RutaRes").ToString + "/api/Identificacion?Nif=" & usuario & "&Clave=&Origen=GESTDELE"
            'Dim clienteHTTP1 As New Net.WebClient()
            'clienteHTTP1.Encoding = System.Text.Encoding.UTF8
            'Dim sRespuesta1 As String = clienteHTTP1.DownloadString(url1)
            'Dim datos As Newtonsoft.Json.Linq.JObject =
            '    Newtonsoft.Json.JsonConvert.DeserializeObject(Of Newtonsoft.Json.Linq.JObject)(sRespuesta1)
            ''mensajeError.InnerText = sRespuesta1
            'Dim RespIden As Newtonsoft.Json.Linq.JObject = datos
            'Dim objetoDatos As Models.ResultadoIdentificacion = RespIden.ToObject(Of Models.ResultadoIdentificacion)
            Dim liPer = RespIden.Personas
            Session.Add("liPer", liPer)
            Dim listPersonas = liPer


            Dim listaDepartamentos = New List(Of String)
            Dim liPer2 = liPer.Skip(1).ToList()
            If Session("persona").Personas(0).Roll = "SUPERVISORDETODO" Then
                liPer2 = liPer2.Where(Function(x) x.Departamento = Session("persona").Personas(0).Departamento).ToList
            Else
                liPer2 = liPer2.OrderBy(Function(x) x.Departamento).ThenBy(Function(x) x.Nombre).ToList
            End If
            Dim dep = ""
            For Each item As Models.Personal In liPer2
                If dep <> item.Departamento Then
                    dep = item.Departamento
                    listaDepartamentos.Add(item.Departamento)
                End If
            Next

            If liDepartamento.Count > 1 Then
                For Each depar As String In liDepartamento
                    deparSelect.Items.Add(New ListItem(depar, depar))
                Next
                deparSelect.Style.Remove("display")
            ElseIf Session("persona").Personas(0).Roll = "SUPERVISORDETODO" Then
                For Each depar As String In listaDepartamentos
                    deparSelect.Items.Add(New ListItem("SUPTODO", "SUPTODO"))
                Next
            Else
                deparSelect.Items.Add(New ListItem("0", "0"))
            End If
        End If

    End Sub
    <System.Web.Services.WebMethod()>
    Public Shared Function cargarPersonasDelegados(dep As String)
        If UtilAntifraude.CheckCred() = False Then
            Return "ERROR--1"
            Exit Function
        End If
        Dim htmlPersonas = ""
        Dim htmlDelegados = ""
        Dim liPer As List(Of Personal) = HttpContext.Current.Session("liPer")
        Dim usu As Personal = HttpContext.Current.Session("persona").Personas(0)
        Dim cont = 0
        Dim personas As List(Of Personal)
        If dep = "0" Then
            personas = liPer.Skip(1).OrderBy(Function(x) x.Nombre).ToList
        ElseIf dep = "SUPTODO" Then
            personas = liPer.Skip(1).Where(Function(x) x.Departamento = usu.Departamento).ToList
        Else
            personas = liPer.Skip(0).Where(Function(x) x.Departamento = dep AndAlso x.Dni <> usu.Dni).ToList
        End If
        For Each item As Personal In personas
            If (item.Roll = "DELEGADO" AndAlso (usu.Roll = "SUPERVISOR" Or usu.Roll = "SUPERVISORDETODO")) OrElse (item.Roll = "DELEGADOSUPERVISORDETODO" AndAlso usu.Roll = "SUPERVISORDETODO") Then
                htmlPersonas += "<div id='" + item.Dni + "' class='divUsuarioDel col-md-4' style='display:flex; justify-content:space-between'><p class='pUsuario'>" + item.Nombre.ToLower + "</p><input type='checkbox' value='" + item.Dni + "' class='inpDelegado del" + cont.ToString + "' checked='checked'></div>"
            Else
                htmlPersonas += "<div id='" + item.Dni + "' class='divUsuarioDel col-md-4' style='display:flex; justify-content:space-between'><p class='pUsuario'>" + item.Nombre.ToLower + "</p><input type='checkbox' value='" + item.Dni + "' class='inpDelegado del" + cont.ToString + "'></div>"

            End If
        Next
        Return htmlPersonas

    End Function
    <System.Web.Services.WebMethod(EnableSession:=True)>
    Public Shared Async Function GuardarCambiosDelegado(personas As String) As Task(Of String)
        If UtilAntifraude.CheckCred() = False Then
            Return "ERROR--1"
            Exit Function
        End If
        Dim settings As New Newtonsoft.Json.JsonSerializerSettings()
        Dim sessionUsuario As String = HttpContext.Current.Session("usuario")
        Dim listaPersonas As List(Of Personal) = HttpContext.Current.Session("liPer")
        Dim ses As HttpContext = HttpContext.Current
        settings.CheckAdditionalContent = True
        Dim objetoConsulta As New ListaPersonasDelegadas
        objetoConsulta.nifIdent = sessionUsuario

        Dim listapersonadel As List(Of PersonaDelegada) =
        Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of PersonaDelegada))(personas, settings)
        objetoConsulta.listaPersonasDel = listapersonadel
        Dim jsonConsulta As String = JsonConvert.SerializeObject(objetoConsulta)
        Dim url As String = ConfigurationManager.AppSettings("RutaRes").ToString + "/api/ModificaPersonasDelegadas"

        'Dim clienteHTTP As New HttpClient
        'Dim contenidoConsultaHTTP As New StringContent(jsonConsulta, Encoding.UTF8, "application/json")
        'Debug.WriteLine("CargarListadodePicadasAsync:1===" + Now.ToLongTimeString)
        'Dim respuestaHTTP As HttpResponseMessage = Await clienteHTTP.PostAsync(url, contenidoConsultaHTTP).ConfigureAwait(False)
        'Debug.WriteLine("CargarListadodePicadasAsync:2===" + Now.ToLongTimeString)
        'Dim sRespuesta As String = Await respuestaHTTP.Content.ReadAsStringAsync().ConfigureAwait(False)
        'Debug.WriteLine("CargarListadodePicadasAsync:3===" + Now.ToLongTimeString)

        Dim clienteHTTP As New HttpClient
        Dim contenidoConsultaHTTP As New StringContent(jsonConsulta, Encoding.UTF8, "application/json")
        Debug.WriteLine("CargarListadodePicadasAsync:1===" + Now.ToLongTimeString)
        Dim respuestaHTTP As HttpResponseMessage = Await clienteHTTP.PostAsync(url, contenidoConsultaHTTP).ConfigureAwait(False)
        Debug.WriteLine("CargarListadodePicadasAsync:2===" + Now.ToLongTimeString)
        Dim sRespuesta As String = Await respuestaHTTP.Content.ReadAsStringAsync().ConfigureAwait(False)
        Debug.WriteLine("CargarListadodePicadasAsync:3===" + Now.ToLongTimeString)


        Dim objetoDatos As ResultadoModificaPersonasDelegadas =
        Newtonsoft.Json.JsonConvert.DeserializeObject(Of ResultadoModificaPersonasDelegadas)(sRespuesta, settings)
        Dim listPer As List(Of Personal) = objetoDatos.Personas
        'HttpContext.Current.Session.Remove("liPer")
        HttpContext.Current = ses
        HttpContext.Current.Session.Add("liPer", listPer)
        Return sRespuesta


    End Function

End Class