@page "/Orders"
@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" />
<Modal Size="ModalSize.Small" @ref="Newordermodal" />
<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-1">
                                    <input @bind-value="itemsearch.ID" placeholder="شناسه" style="text-align:center;" class="form-control" type="text">
                                </div>
                                <div class="col-md-2">
                                    <select @bind="ItemSearchOrdertype" class="form-control" aria-label="Default select example">
                                        <option value="0" style="color: #b5b5b5" selected>وضعیت سفارش ...</option>

                                        @foreach (StatusOrder i in Enum.GetValues(typeof(StatusOrder)))
                                            {

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


                                            }
                                        
                                    </select>
                                </div>

                                <div class="col-auto">
                                    <Button Disabled="SpinnerVisible" @onclick="() => GetOrders(1)" Color="ButtonColor.Primary">جستجو</Button>
                                </div>


                                <div class="col-md-2">
                                    <Spinner Visible="SpinnerVisible" Color="SpinnerColor.Primary" />
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

@* action *@
<div class="row">
    <div class="col-md-12">
        <ul class="list-group fa-padding">
            <li class="list-group-item" data-toggle="modal" data-target="#issue">
                <div class="row g-3">
                    <div class="col-auto">

                        <Button Disabled="SpinnerVisible" Color="ButtonColor.Primary" @onclick="NewOrderItem">جدید</Button>


                    </div>
                   
                </div>

            </li>
        </ul>

    </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,OrderItem)" />
    @* 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 {
    public bool SpinnerVisible { get; set; } = false;
    //private Modal stuffmodal = default!;
    [Inject] protected PreloadService PreloadService { get; set; } = default!;
    ItemSerachOrder itemsearch = new ItemSerachOrder();
    public int? ItemSearchOrdertype { get; set; }
    [Parameter, SupplyParameterFromQuery]
    public int? PageIndex { get; set; }
    public Shared.DTOs.PagingDto<OrderDto>? request { get; set; }
    private Modal modal = default!;
    private Modal Newordermodal = default!;
    // alert
    AlertColor alertColor = AlertColor.Primary;
    IconName alertIconName = IconName.CheckCircleFill;
    bool Hidealert = true;
    string alertMessage = "";

    protected override async Task OnInitializedAsync()
    {
        SpinnerVisible = false;
        await base.OnInitializedAsync();
    }
    protected override async Task OnParametersSetAsync()
    {
        SpinnerVisible = false;
        if (PageIndex == null) PageIndex = 1;
        await GetOrders(PageIndex.Value);
        await base.OnParametersSetAsync();
    }
}
@functions {
    public async Task GetOrders(int pi=1)
    {
        SpinnerVisible = true;
        if (ItemSearchOrdertype == 0 || ItemSearchOrdertype == null)
            itemsearch.Status = null;
        else
            itemsearch.Status = (StatusOrder)ItemSearchOrdertype;

        itemsearch.PageSize = 10;
        itemsearch.PageIndex = pi;
        PreloadService.Show(SpinnerColor.Dark);
        var rsp = await hc.Post<ItemSerachOrder>("Orders/GetAllOrder",itemsearch);
        if (rsp.IsSuccessStatusCode)
            request = await rsp.Content.ReadFromJsonAsync<Shared.DTOs.PagingDto<OrderDto>?>();
        else
            ShowDangerAlert("خطایی در بارگیری سفارشات رخ داده");
        PreloadService.Hide();
        SpinnerVisible = false;
    }
    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 CallBackFromReadItem(ActionInResultComponent result)
    {

        if (result.Action == ComponentAction.add)
        {
            if (result.Status == ComponentStatus.success)
            {
                ShowSuccessAlert("سفارش پرداخت شد");
               await fv.LoadDashBoard(true);
            }


        }
        else if (result.Action == ComponentAction.delete)
        {
            if (result.Status == ComponentStatus.success)
                ShowSuccessAlert("سفارش ابطال شد");
        }
        if (result.Status == ComponentStatus.success)
            await GetOrders(1);

        await modal.HideAsync();
    }
    public async Task OrderItem(int ID)
    {
       await ReadOrderItem(request?.list.Where(w => w.ID == ID).First());
    }
    public async Task ReadOrderItem(OrderDto order)
    {
        var parameters = new Dictionary<string, object>();
        parameters.Add("order", order);
        parameters.Add("OnMultipleOfThree", EventCallback.Factory.Create<ActionInResultComponent>(this, CallBackFromReadItem));
        await modal.ShowAsync<OrderItemRead>(title: $"سفارش {order.ID}", parameters: parameters);
    }
    public async Task CallBackFromNewItem(OrderDto result)
    {
        await Newordermodal.HideAsync();
        await ReadOrderItem(result);
        await GetOrders(1);

    }
    public async Task NewOrderItem()
    {
        var parameters = new Dictionary<string, object>();
        parameters.Add("OnMultipleOfThree", EventCallback.Factory.Create<OrderDto>(this, CallBackFromNewItem));
        await Newordermodal.ShowAsync<OrderItemNew>(title: $"سفارش جدید", parameters: parameters);


    }
}