@page "/ConceptosGenerales"
@using System.Net.Http.Headers
@using System.Linq.Expressions
@using Newtonsoft.Json
@using System.Text
@using Serialize.Linq.Serializers
@using GestionPersonalWeb.Models
@using BlazorBootstrap
@using bdAntifraude.db
@using Microsoft.AspNetCore.Components

@rendermode InteractiveServer
@inject IJSRuntime JS
@inject NavigationManager NavigationManager
@inject IHttpClientFactory HttpClientFactory
@inject IHttpContextAccessor HttpContextAccessor
@inject UserState UserState

<div class="pagina">
    <div class="d-flex">
        <div class="cabecera">
            <h6 style="padding-top: 13px;padding-right: 15px;">
                <b>Conceptos Generales</b>
            </h6>
        </div>
        <a href="/ConceptoGeneral" class="btnOAAFAzul" style="text-decoration:none">Nuevo </a>
    </div>

    @if (lConceptos == null)
    {
        <div id="cargando" class="loadingFrame">
            <div class="loadingImg"></div>
        </div>
    }
    else if (!lConceptos.Any())
    {
        <p>No se encontraron datos para mostrar.</p>
    }
    else
    {
        <div class="botonera col-12 gap-1" style="display:flex;" role="group">
        </div>
        <div style="display:flex; justify-content:start; gap:15px;width:100%"></div>
        <div class="form-group mt-4 mb-4">
            <input class="form-control" type="text" placeholder="Filtrar..."
                   @bind-value="Filter" @bind-value:event="oninput" />
        </div>

        <div style="overflow-x:auto;" class="">
            <Grid TItem="CONCEPTOSGENERALES"
                  Class="table tablaRegPers"
                  Data="@lConceptos"
                  AllowFiltering="false"
                  AllowPaging="false"
                  AllowSorting="true"
                  EmptyText="No se han encontrado datos"
                  Height="80"
                  PageSizeSelectorVisible="false"
                  Responsive="true"
                  PaginationItemsTextFormat="{0} - {1} de {2} elementos">
                <GridColumns>
                    <GridColumn TItem="CONCEPTOSGENERALES" HeaderText="Descripción" PropertyName="DESCRIPCION" FilterButtonCSSClass="hidden" SortKeySelector="item => item.DESCRIPCION">
                        <NavLink class="btn btn-link" href="@HashRed(context.IDCONCEPTOSGENERALES.ToString())">@context.DESCRIPCION</NavLink>
                    </GridColumn>
                   

                </GridColumns>
            </Grid>
        </div>

        <!-- Vista móvil -->
      @*   <div class="tablaMov">
            @foreach (var itm in lPuestos)
            {
                var collapseId = $"collapse{itm.IDTIPOPUESTO}";
                <div class="card collapse-card Aceptada">
                    <div class="card-header mb-1" data-bs-toggle="collapse" data-bs-target="#@collapseId" aria-expanded="false" aria-controls="@collapseId">
                        <h5 class="mb-0">@itm.DESCRIPCION</h5>
                    </div>
                    <div id="@collapseId" class="collapse">
                        <div class="card-body">
                            <dl class="row">
                                <dt class="col-sm-3">Descripción</dt>
                                <dd class="col-sm-9"><a href="@HashRed(itm.IDTIPOPUESTO.ToString())">@itm.DESCRIPCION</a></dd>                            
                            </dl>
                        </div>
                    </div>
                </div>
            }
        </div> *@
    }
</div>

@code {
    private List<CONCEPTOSGENERALES> lConceptos = new List<CONCEPTOSGENERALES>();
    private List<CONCEPTOSGENERALES> Conceptos = new List<CONCEPTOSGENERALES>();
    private string _filter = "";
    public string Filter
    {
        get => _filter;
        set
        {
            if (_filter != value)
            {
                _filter = value;
               AplicarFiltros();
            }
        }
    }
    private void AplicarFiltros()
    {
        lConceptos = Conceptos.Where(per =>
            string.IsNullOrEmpty(Filter) ||
            Utilidades.RemoveDiacritics(per.DESCRIPCION).Contains(Utilidades.RemoveDiacritics(Filter), StringComparison.OrdinalIgnoreCase)
            ).ToList();
        UserState.CurrentPage = 1;
    }
   
    private string HashRed(string id)
    {
        string link = "/ConceptoGeneral?cl=" + tsUtilidades.crypt.FEncS(
            id,
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.:/-*",
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.:/-*",
            875421649);
        return link;
    }
    // Bandera que indica si se está en modo "Ver Todos"
    private bool verTodosActive = false;

    private async Task ToggleVerTodos()
    {
        if (!verTodosActive)
        {
            verTodosActive = true;
            var token = UserState.Token;
            var client = HttpClientFactory.CreateClient();
            client.BaseAddress = new Uri(Utilidades.urlSwagger());
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var resultPersonas = await client.GetAsync("/CONCEPTOSGENERALES");
            var resultContent = await resultPersonas.Content.ReadAsStringAsync();
            Conceptos = JsonConvert.DeserializeObject<List<CONCEPTOSGENERALES>>(resultContent)
                       ?? new List<CONCEPTOSGENERALES>();
        }
        else
        {
            verTodosActive = false;
            var token = UserState.Token;
            var client = HttpClientFactory.CreateClient();
            client.BaseAddress = new Uri(Utilidades.urlSwagger());
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var resultPersonas = await client.GetAsync("/api/CONCEPTOSGENERALES");
            var resultContent = await resultPersonas.Content.ReadAsStringAsync();
            Conceptos = JsonConvert.DeserializeObject<List<CONCEPTOSGENERALES>>(resultContent)
                       ?? new List<CONCEPTOSGENERALES>();
        }

        Conceptos = Conceptos
            .OrderBy(x => x.DESCRIPCION)
            .ToList();

        lConceptos = Conceptos;
        UserState.CurrentPage = 1;
        Filter = "";
    }

    protected override async Task OnInitializedAsync()
    {
        verTodosActive = false;
        var token = UserState.Token;
        var client = HttpClientFactory.CreateClient();
        client.BaseAddress = new Uri(Utilidades.urlSwagger());
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var resultPersonas = await client.GetAsync("/api/CONCEPTOSGENERALES");
        var resultContent = await resultPersonas.Content.ReadAsStringAsync();
        Conceptos = JsonConvert.DeserializeObject<List<CONCEPTOSGENERALES>>(resultContent)
                   ?? new List<CONCEPTOSGENERALES>();

        Conceptos = Conceptos
            .OrderBy(x => x.DESCRIPCION)
            .ToList();

        lConceptos = Conceptos;
    }

}

