Imports System.Net.Http
Imports Newtonsoft.Json

Public Class gestionDepartamentoEmp
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Session("usuario") = "" OrElse Session("modo") <> "PERSONAL" Then
            Response.Redirect("default.aspx")
        End If

        Dim persons As List(Of Models.Personal) = Session("persona").Personas
        Dim listaPersonas As New List(Of Models.Personal)
        Dim listDni = Session("usuariosSeleccionados")
        For Each pers As String In listDni
            Dim per = persons.FirstOrDefault(Function(x) x.Dni = pers)
            listaPersonas.Add(per)
        Next

        Dim htmlSelPer = ""
        htmlSelPer += "<select id='selPer' class='selectIn' style='width:100%' onchange=""setSelDep()"">"
        For Each itm As Models.Personal In listaPersonas.OrderBy(Function(x) x.Nombre)
            htmlSelPer += "<option value='" + itm.idPersona.ToString() + "'>" + itm.Nombre + "</option>"
        Next
        htmlSelPer += "</select>"
        DivSelPer.InnerHtml = htmlSelPer
        'cbPersonas.DataSource = listaPersonas.OrderBy(Function(x) x.Nombre)
        'cbPersonas.DataBind()


        Dim usuario As String = "tecnosis"
        Dim contraseña As String = "patata2022"
        Dim url3 As String = ConfigurationManager.AppSettings("RutaRes").ToString + "/api/ObtenerDepartamentos"

        Dim credenciales3 As New Net.CredentialCache()
        credenciales3.Add(New Uri(url3), "Basic", New Net.NetworkCredential(usuario, contraseña))
        Dim clienteHTTP3 As New Net.WebClient()
        clienteHTTP3.Encoding = System.Text.Encoding.UTF8
        clienteHTTP3.Credentials = credenciales3
        Dim respuesta3 As String = clienteHTTP3.DownloadString(url3)
        Dim deserializador3 As New System.Web.Script.Serialization.JavaScriptSerializer()
        deserializador3.MaxJsonLength = Integer.MaxValue

        Dim liDep As List(Of Models.EnumDepartamento) =
            deserializador3.Deserialize(Of List(Of Models.EnumDepartamento))(respuesta3)

        Dim htmlSelDep = ""
        htmlSelDep += "<select id='selDep' class='selectIn' style='width:100%'>"
        For Each itm As Models.EnumDepartamento In liDep
            htmlSelDep += "<option value='" + itm.idDep.ToString() + "'>" + itm.Descripcion + "</option>"
        Next
        htmlSelDep += "</select>"
        DivSelDep.InnerHtml = htmlSelDep
        'selDep.DataSource = liDep
        'selDep.DataBind()

    End Sub


    <System.Web.Services.WebMethod()>
    Public Shared Function getDep(usu As String) As String
        If UtilAntifraude.CheckCred() = False Then
            Return "ERROR--1"
            Exit Function
        End If
        Dim usuarios As List(Of Models.Personal) = HttpContext.Current.Session("liPer")
        Dim us = usuarios.FirstOrDefault(Function(x) x.idPersona = CInt(usu))

        Dim usuario As String = "tecnosis"
        Dim contraseña As String = "patata2022"
        Dim url3 As String = ConfigurationManager.AppSettings("RutaRes").ToString + "/api/ObtenerDepartamentos"

        Dim credenciales3 As New Net.CredentialCache()
        credenciales3.Add(New Uri(url3), "Basic", New Net.NetworkCredential(usuario, contraseña))
        Dim clienteHTTP3 As New Net.WebClient()
        clienteHTTP3.Encoding = System.Text.Encoding.UTF8
        clienteHTTP3.Credentials = credenciales3
        Dim respuesta3 As String = clienteHTTP3.DownloadString(url3)
        Dim deserializador3 As New System.Web.Script.Serialization.JavaScriptSerializer()
        deserializador3.MaxJsonLength = Integer.MaxValue

        Dim liDep As List(Of Models.EnumDepartamento) =
            deserializador3.Deserialize(Of List(Of Models.EnumDepartamento))(respuesta3)

        Dim idDepSel = liDep.FirstOrDefault(Function(x) x.Descripcion = us.Departamento).idDep

        Return idDepSel


    End Function


    <System.Web.Services.WebMethod()>
    Public Shared Async Function CambiarDep(usu As String, dep As String) As Threading.Tasks.Task(Of String)
        Dim usuario = usu
        Dim departamento = dep
        Dim settings As New Newtonsoft.Json.JsonSerializerSettings()
        Dim ses As HttpContext = HttpContext.Current
        Dim consulta As New CambiarDep
        consulta.usuario = usuario
        consulta.departamento = departamento
        Dim jsonConsulta As String = JsonConvert.SerializeObject(consulta)
        Dim url As String = ConfigurationManager.AppSettings("RutaRes").ToString + "/api/CambiarDepartamento"
        Dim clienteHTTP As New HttpClient
        Dim contenidoConsultaHTTP As New StringContent(jsonConsulta, Encoding.UTF8, "application/json")
        Dim respuestaHTTP As HttpResponseMessage = Await clienteHTTP.PostAsync(url, contenidoConsultaHTTP).ConfigureAwait(False)
        Dim sRespuesta As String = Await respuestaHTTP.Content.ReadAsStringAsync().ConfigureAwait(False)
        Dim objetoDatos As Models.ResultadoModificaPersonasDelegadas =
        Newtonsoft.Json.JsonConvert.DeserializeObject(Of Models.ResultadoModificaPersonasDelegadas)(sRespuesta, settings)
        Dim listPer As List(Of Models.Personal) = objetoDatos.Personas
        'HttpContext.Current.Session.Remove("liPer")
        HttpContext.Current = ses
        HttpContext.Current.Session.Add("liPer", listPer)
        Return sRespuesta
        Return sRespuesta

    End Function

    'Private Sub cbPersonas_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbPersonas.SelectedIndexChanged
    '    Dim personas As List(Of Models.Persona) = Session("persona").Personas
    '    Dim persona = personas.First(Function(x) x.DNI = cbPersonas.Value)
    'End Sub
End Class
Public Class CambiarDep
    Public Property usuario As Integer
    Public Property departamento As Integer
End Class