@page "/Invoice"
@page "/Invoice/{input}"
@using Front.Services
@using Shared
@using Shared.DTOs
@using Front.CUSComponent
@using Shared.DTOs.Serch
@inject HttpClientController hc;
@inject Fixedvalues fv;
<PageTitle>صورتحساب</PageTitle>
<Modal Size="ModalSize.ExtraLarge" @ref="modal" />

<Preload LoadingText="در حال بارگذاری..." />
@* search *@
<div class="row">
    <h4 class="fw-bold py-3 mb-4">
        <span class="text-muted fw-light">سرویس ها /</span> صورتحساب
    </h4>
    <div class="col-md-12">
        <div class="card mb-2">
            <div class="row">
                <div class="col-md-12">
                    <ul class="list-group fa-padding" style="border: 2px solid #0d6efd">
                        <li class="list-group-item" data-toggle="modal" data-target="#issue">
                            <div class="row g-3">
                                <div class="col-md-2">
                                    <input @bind-value="itemsearch.InvoiceID" placeholder="شناسه / سریال" style="text-align:center;" class="form-control" type="text">
                                </div>
                                <div class="col-md-2">
                                    <input @bind-value="itemsearch.refInvoiceID" placeholder="شناسه مرجع" style="text-align:center;" class="form-control" type="text">
                                </div>
                                <div class="col-md-2">
                                    <select @bind="ItemSearchInvoicetype" class="form-control" aria-label="Default select example">
                                        <option value="100" style="color: #b5b5b5" selected>نوع صورتحساب...</option>
                                        @foreach (InvoiceType i in Enum.GetValues(typeof(InvoiceType)))
                                        {

                                            <option value="@Convert.ToInt32(i)">@i.GetEnumDisplayName()</option>


                                        }

                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <input @bind-value="itemsearch.Title" placeholder="عنوان" style="text-align:center;" class="form-control" type="text">
                                </div>
                                <div class="col-md-2">
                                    <AutoComplete @bind-Value="customerName"
                                                  TItem="ForCustomerSearch"
                                                  DataProvider="CustomersDataProvider"
                                                  PropertyName="CustomerName"
                                                  Placeholder="مشتری"
                                                  OnChanged="(ForCustomerSearch customer) => OnAutoCompleteChanged(customer)" />
                                </div>
                                <div class="col-auto">
                                    <button @onclick="() => LoadInvoice(1)" type="submit" class="btn btn-primary">جستجو</button>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

@* action *@
<div class="row">
    <div class="col-md-12">
        <div class="mb-2">
            <div class="row">
                <div class="col-md-12">
                    <div class="col-auto">
                        <button type="submit" @onclick="()=>InvoiceItem(0)" class="btn btn-primary">جدید</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@* alert *@
<div class="row">
    <Alert hidden="@Hidealert" Color="@alertColor" Dismissable="false">
        <Icon Name="@alertIconName" class="me-2"></Icon>
        @alertMessage
    </Alert>

</div>

@* data *@
@if (request != null)
{
    <LTable ModelinComponent="request?.list" OnMultipleOfThree="EventCallback.Factory.Create<int>(this,InvoiceItem)" />
    @* pagination *@
    <p style="color:red">@request?.RowCount آیتم یافت شد</p>
    <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center">
            @for (int page = 1; page <= request?.PageCount; page++)
            {
                if (page == PageIndex)
                {
                    <li class="page-item active">
                        <a class="page-link" href="@hc._nav.GetUriWithQueryParameter("PageIndex",page)">@(page)</a>
                    </li>
                }
                else
                {
                    <li class="page-item">
                        <a class="page-link" href="@hc._nav.GetUriWithQueryParameter("PageIndex",page)">@(page)</a>
                    </li>
                }
            }


        </ul>
    </nav>
}

@layout PanelLayout
@code {
    private string? customerName;
    public IEnumerable<ForCustomerSearch>? customers;
    public List<IdName<int>> Patterns { get; set; }
    private async Task<AutoCompleteDataProviderResult<ForCustomerSearch>> CustomersDataProvider(AutoCompleteDataProviderRequest<ForCustomerSearch> request)
    {
        if (customers is null) // pull customers only one time for client-side autocomplete
            customers = await GetCustomers(); // call a service or an API to pull the customers

        return await Task.FromResult(request.ApplyTo(customers.OrderBy(customer => customer.CustomerName)));
    }
    //-----------
    [Parameter] public string? input { get; set; }
    [Inject] protected PreloadService PreloadService { get; set; } = default!;
    public int? ItemSearchInvoicetype { get; set; }
    ItemSerchGetInvoices itemsearch = new ItemSerchGetInvoices();
    [Parameter, SupplyParameterFromQuery]
    public int? PageIndex { get; set; }
    public Shared.DTOs.PagingDto<InvoiceGridDTO>? request { get; set; }
    private Modal modal = default!;
    // alert
    AlertColor alertColor = AlertColor.Primary;
    IconName alertIconName = IconName.CheckCircleFill;
    bool Hidealert = true;
    string alertMessage = "";

    protected override async Task OnParametersSetAsync()
    {
        if (PageIndex == null) PageIndex = 1;
        if (!string.IsNullOrEmpty(input))
        {
            if (input.StartsWith("cus"))
                itemsearch.CustomerID = Convert.ToInt32(input.Split(':')[1]);

             else if (input.StartsWith("cod"))
             itemsearch.CodID =Convert.ToInt32(input.Split(':')[1]);
            
        }
        await LoadInvoice(PageIndex.Value);
        await base.OnParametersSetAsync();
    }
}
@functions {
    private void ShowSuccessAlert(string msg)
    {
        Hidealert = false;
        alertColor = AlertColor.Success;
        alertIconName = IconName.CheckCircleFill;
        alertMessage = msg;
    }
    private void ShowDangerAlert(string msg)
    {
        Hidealert = false;
        alertColor = AlertColor.Danger;
        alertIconName = IconName.ExclamationTriangleFill;
        alertMessage = msg;
    }
    public async Task LoadInvoice(int pi)
    {
        if (ItemSearchInvoicetype == 100 || ItemSearchInvoicetype == null)
            itemsearch.invoiceType = null;
        else
            itemsearch.invoiceType = (InvoiceType)ItemSearchInvoicetype;

        itemsearch.PageSize = 10;
        itemsearch.PageIndex = pi;
        PreloadService.Show(SpinnerColor.Dark);
        var rsp = await hc.Post<ItemSerchGetInvoices>("Invoice/GetAll", itemsearch);
        if (rsp.IsSuccessStatusCode)
        {
            request = await rsp.Content.ReadFromJsonAsync<PagingDto<InvoiceGridDTO>>();
        }
        else if (rsp.StatusCode == System.Net.HttpStatusCode.Forbidden)
        {
            ShowDangerAlert("شما دسترسی به خواندن اطلاعات صورتحساب را نداربد");
        }
        else
        {
            ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
        }
        PreloadService.Hide();
    }
    public async Task CallBackInvoiceItem(ActionInResultComponent result)
    {

        if (result.Action == ComponentAction.add)
        {
            if (result.Status == ComponentStatus.success)
                ShowSuccessAlert("صورتحساب جدید با موفقیت اضافه شد");

        }
        else if (result.Action == ComponentAction.update)
        {
            if (result.Status == ComponentStatus.success)
                ShowSuccessAlert("اطلاعات صورتحساب با موفقیت ویرایش شد");
        }
        else if (result.Action == ComponentAction.delete)
        {
            if (result.Status == ComponentStatus.success)
                ShowSuccessAlert("صورتحساب با موفقیت حذف شد");
        }

        if (result.Status == ComponentStatus.success)
            await LoadInvoice(1);

        await modal.HideAsync();
    }
    public async Task InvoiceItem(int ID)
    {
        // if (customers is null)
        //     customers = await GetCustomers();
        // if (Patterns == null || Patterns.Count < 0)
        // {
        //     Patterns =await fv.GetPatterns();
        // }
        // var parameters = new Dictionary<string, object>();

        // if (ID == 0) parameters.Add("Invoice", new InvoiceDTO()
        //     {
        //         ID = 0,
        //         InvoiceDate = DateTime.Now.ConvertMiladiToShamsiinFront().ShamciToFormatShamciinFront(),
        //         InvoicIssueDate = DateTime.Now.ConvertMiladiToShamsiinFront().ShamciToFormatShamciinFront(),
        //         Udate = DateTime.Now.ConvertMiladiToShamsiinFront().ShamciToFormatShamciinFront()
        //     });
        // else parameters.Add("invoice", request.list.Where(w => w.ID == ID).First().Clone());
        // parameters.Add("Patterns", Patterns);
        // parameters.Add("Cus", customers);
        // parameters.Add("OnMultipleOfThree", EventCallback.Factory.Create<ActionInResultComponent>(this, CallBackInvoiceItem));

        //await modal.ShowAsync<InvoiceItem>(title: ID == 0 ? "صورتحساب جدید" : "ویرایش اطلاعات", parameters: parameters);
        if (ID==0)
        {
            hc._nav.NavigateTo($"InvoiceDetails");
        }
        else
        hc._nav.NavigateTo($"InvoiceDetails/{ID}");

    }
    //------------------------
    private async Task<List<ForCustomerSearch>> GetCustomers()
    {
        return await fv.GetCustomers();
        // var rsp = await hc.Get("Customer/GetAllForidName");
        // if (rsp.IsSuccessStatusCode)
        // {
        //     return await rsp.Content.ReadFromJsonAsync<List<ForCustomerSearch>>();
        // }
        // return new List<ForCustomerSearch>();

    }
    private void OnAutoCompleteChanged(ForCustomerSearch customer)
    {
        itemsearch.CustomerID = customer?.ID;
    }
}