<PageTitle>دریافت صورتحساب</PageTitle>
@inject IJSRuntime JS
@inject HttpClientController hc;
<Preload LoadingText="در حال بارگذاری..." />
<Toasts class="p-3" Messages="messages" Placement="ToastsPlacement.MiddleCenter" />
@layout EmptyLayout
@page "/InvoiceReport/{InvoiceID:int}"
@using Front.Services

@code {
    [Inject] protected PreloadService PreloadService { get; set; } = default!;
    List<ToastMessage> messages = new List<ToastMessage>();
    [Parameter] public int? InvoiceID { get; set; }
    protected async override Task OnParametersSetAsync()
    {
         await ShowReport();
        await base.OnParametersSetAsync();
    }


}
@functions {
    private void ShowMessage(ToastType toastType, string msg) => messages.Add(CreateToastMessage(toastType, msg));

    private ToastMessage CreateToastMessage(ToastType toastType, string msg)
    => new ToastMessage
        {
            Type = toastType,
            Message = msg,
        };
    private async Task ShowReport()
    {
        if (InvoiceID != null && InvoiceID > 0)
        {

            PreloadService.Show(SpinnerColor.Dark);
            var rsp = await hc.Get($"Invoice/GetReport/{InvoiceID}");
            if (rsp.IsSuccessStatusCode)
            {
                var str = await rsp.Content.ReadAsStringAsync();
                if (string.IsNullOrEmpty(str))
                    ShowMessage(ToastType.Warning, "مشکلی در ساخت فایل رخ داده لطفا مجدد تلاش کنید");
                else
                    await DownloadFileFromStream(str, $"{InvoiceID}.pdf");

            }
            else if (rsp.StatusCode == System.Net.HttpStatusCode.NotFound)
                ShowMessage(ToastType.Warning, "فاکتوری یافت نشد");

            else ShowMessage(ToastType.Warning, "خطایی در چاپ فاکتور");

            PreloadService.Hide();

        }
        else hc._nav.NavigateTo("Invoice");

 
    }
    //for download
    private Stream GetFileStream(byte[] bytes)
    {
        var fileStream = new MemoryStream(bytes);

        return fileStream;
    }
    private async Task DownloadFileFromStream(string Base64, string FileName)
    {
        byte[] bytes = System.Convert.FromBase64String(Base64);

        var fileStream = GetFileStream(bytes);
        // var fileName = "log.bin";

        using var streamRef = new DotNetStreamReference(stream: fileStream);

        await JS.InvokeVoidAsync("downloadFileFromStream", FileName, streamRef);
    }

}
<script>
    window.downloadFileFromStream = async (fileName, contentStreamReference) => {
        const arrayBuffer = await contentStreamReference.arrayBuffer();
        const blob = new Blob([arrayBuffer]);
        const url = URL.createObjectURL(blob);
        const anchorElement = document.createElement('a');
        anchorElement.href = url;
        anchorElement.download = fileName ?? '';
        anchorElement.click();
        anchorElement.remove();
        URL.revokeObjectURL(url);
    }
</script>