@page "/dashboarddetail/{Group}"
@page "/dashboarddetail"
@using Domain.Entities
@inject IJSRuntime js;
@inject IToastService toastService
@inject HttpClient _httpClient
@inject TicketsService ticketService
@inject NavigationManager Navigation
@inject AuthenticationStateProvider authenticationStateProvider

<div class="card " style="zoom:90%">
    <div class="card-header">
        <h3 class="card-title">Tickets detalle: @Group?.ToUpper().ToString()</h3> @* wtf? *@
    </div>
    <div class="card-body">
        <PhTable Columns="columnas" Data="datos" SelectionField="#" RenderSelect="false" RenderButtons="false" RowsPerPage="5" SorteableCols="columnas"></PhTable>
    </div>
    <div class="card-footer">
        <div class="row">
            <div class="col">
                <button type="button" class="btn btn-success" @onclick="XSLXExportar">
                    <i class="fas fa-file-excel"></i> Exportar a Excel
                </button>
                <button type="button" class="btn btn-secondary" @onclick="Cancel">Volver</button>
            </div>
        </div>
    </div>
</div>
@code {
    [Parameter]
    public string? Group { get; set; } = string.Empty;

    private IEnumerable<ETicket_Dashboard>? detailResult;
    List<string> columnas = new List<string> 
    {
        "#",
        "Titulo",
        "Prioridad",
        "Estado",
        "Creador",
        "Fecha",
        "Asignado",
        "Categoria",
        "Departamento",
        "Impacto",
        "Urgencia"
    };
    List<Dictionary<string, object>> datos = new List<Dictionary<string, object>>();

    protected override async Task OnInitializedAsync()
    {
        if (!string.IsNullOrEmpty(Group))
        {
            detailResult = await ticketService.GetDashboardDetail(Group, "ASC");
            if (detailResult is not null)
            {
                datos = ObtenerDatos(detailResult);
            }
        }
    }
    private async Task XSLXExportar()
    {
        string endpoint = "/api/Ticket/ExportDashboardDetail";
        var response = await _httpClient.PostAsJsonAsync(endpoint, new { Param1 = Group, Param2 = "ASC" });
        response.EnsureSuccessStatusCode();
        var fileBytes = await response.Content.ReadAsByteArrayAsync();
        var currentDate = DateTime.Now.ToString("ddMMyyyyhhmmss");
        var filename = $"Tickets_{Group}_{currentDate}.xlsx";
        await js.InvokeAsync<object>("saveAsFile", filename, Convert.ToBase64String(fileBytes));
    }

    List<Dictionary<string, object>> ObtenerDatos(IEnumerable<ETicket_Dashboard> summary)
    {
        var datos = new List<Dictionary<string, object>>();
        foreach (var item in summary)
        {
            var fila = new Dictionary<string, object>();
            fila.Add(columnas[0], item.TicketId);
            fila.Add(columnas[1], item.Titulo?.ToString() ?? string.Empty);
            fila.Add(columnas[2], item.Prioridad?.ToString() ?? string.Empty);
            fila.Add(columnas[3], item.Estado?.ToString() ?? string.Empty);
            fila.Add(columnas[4], item.CreadorUsuarioId?.ToString() ?? string.Empty);
            fila.Add(columnas[5], item.FechaCreacion?.ToString() ?? string.Empty);
            fila.Add(columnas[6], item.AsignadoAUsuarioId?.ToString() ?? string.Empty);
            fila.Add(columnas[7], item.Categoria?.ToString() ?? string.Empty);
            fila.Add(columnas[8], item.Departamento?.ToString() ?? string.Empty);
            fila.Add(columnas[9], item.Impacto?.ToString() ?? string.Empty);
            fila.Add(columnas[10], item.Urgencia?.ToString() ?? string.Empty);
            datos.Add(fila);
        }
        return datos;
    }
    public void Cancel()
    {
        Navigation.NavigateTo("/DashboardPanel");
    }
}