using IgniteUI.Blazor.Controls; using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Logging; using Microsoft.JSInterop; using MudBlazor; using OI.Metrology.Shared.DataModels; using OI.Metrology.Shared.Models.Stateless; using System.Net; using System.Net.Http.Json; namespace OI.Metrology.View; public partial class Export { protected TimeSpan? _TimeSpan; protected DateRange? _DateRange; protected ToolTypeNameId? _ToolTypeNameId; protected ToolTypeNameId[]? _ToolTypeNameIdCollection; [Inject] protected HttpClient? HttpClient { get; set; } [Inject] protected IJSRuntime? JSRuntime { get; set; } [Inject] protected Models.AppSettings? AppSettings { get; set; } [Inject] protected ILogger? Logger { get; set; } protected Func _ConvertFunc = toolTypeNameId => string.Concat(toolTypeNameId?.ToolTypeName); protected override Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { if (JSRuntime is null) throw new NullReferenceException(nameof(JSRuntime)); if (AppSettings is null) throw new NullReferenceException(nameof(AppSettings)); return JSRuntime.InvokeVoidAsync("initExport", AppSettings.ApiUrl, DateTime.Now.AddMonths(-1), DateTime.Now).AsTask(); } return Task.CompletedTask; } protected override async Task OnInitializedAsync() { _ToolTypeNameId ??= new(); _TimeSpan ??= new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 00); _DateRange ??= new DateRange(DateTime.Now.AddMonths(-1).Date, DateTime.Now.Date); if (Logger is null) throw new NullReferenceException(nameof(Logger)); if (HttpClient is null) throw new NullReferenceException(nameof(HttpClient)); string controllerName = IToolTypesController.GetRouteName(); try { Result? result = await HttpClient.GetFromJsonAsync>($"api/{controllerName}"); if (result is not null) _ToolTypeNameIdCollection = result.Results; } catch (Exception) { string json = await HttpClient.GetStringAsync($"api/{controllerName}"); Logger.LogInformation(message: json); } } protected async Task DownloadAsync() { if (JSRuntime is null) throw new NullReferenceException(nameof(JSRuntime)); if (HttpClient is null) throw new NullReferenceException(nameof(HttpClient)); if (_TimeSpan is null || _DateRange is null || _ToolTypeNameId is null || _ToolTypeNameIdCollection is null || _ToolTypeNameId.ToolTypeName is null || _DateRange.Start is null || _DateRange.End is null) return; string controllerName = IToolTypesController.GetRouteName(); string endTime = _DateRange.End.Value.AddTicks(_TimeSpan.Value.Ticks).ToString(); string startTime = _DateRange.Start.Value.AddTicks(_TimeSpan.Value.Ticks).ToString(); string fileName = $"Export_{_ToolTypeNameId.ToolTypeName}_{startTime:yyyyMMddHHmm}_to_{endTime:yyyyMMddHHmm}.csv"; string query = $"datebegin={startTime:MM/dd/yyyy hh:mm tt}&dateend={endTime:MM/dd/yyyy hh:mm tt}&filename={WebUtility.UrlEncode(fileName)}"; await JSRuntime.InvokeVoidAsync("triggerFileDownload", fileName, $"{HttpClient.BaseAddress}api/{controllerName}/{_ToolTypeNameId.ID}/csv?{query}"); } }