<PageTitle>انبارداری</PageTitle>
@page "/Warehouse"
@using Front.CUSComponent
@using Front.Services
@using Shared.DTOs
@using Shared.DTOs.Warehouse
@layout PanelLayout
<Modal Size="ModalSize.Regular" @ref="modal" />
@inject Fixedvalues fv;
@inject HttpClientController hc;
<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="date" placeholder="تاریخ" style="text-align:center" dir="ltr" class="form-control" type="number">
                                </div>

                                <div class="col-md-2">
                                    <select style="text-align:center" @bind="CODID" class="form-control" aria-label="Default select example">
                                        <option value="0" style="color: #b5b5b5" selected>کالا ...</option>
                                        @if (CODrequest != null)
                                        {
                                            foreach (var item in CODrequest)
                                            {
                                                <option value="@item.ID">@item.Title</option>
                                            }
                                        }
                                    </select>
                                </div>

                                <div class="col-auto">
                                    <Button Disabled="SpinnerVisible" @onclick="() => Load(1)" Color="ButtonColor.Primary">جستجو</Button>
                                </div>
                                <div class="col-auto">
                                    <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" Type="ButtonType.Submit" Color="ButtonColor.Warning" @onclick="()=>Item(new CirculationDto(){Type=TypeCirculation.Receipt})">رسید جدید</Button>
                    </div>
                    <div class="col-auto" >
                        <Button Disabled="SpinnerVisible" Type="ButtonType.Submit" Color="ButtonColor.Success" @onclick="()=>Item(new CirculationDto(){Type=TypeCirculation.Remittance})">حواله جدید</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" OnMultipleOfThreeGeneric="EventCallback.Factory.Create<CirculationDto>(this,Item)" />
    @* 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>
}
@code {
    public bool SpinnerVisible { get; set; } = false;
    [Inject] protected PreloadService PreloadService { get; set; } = default!;
    [Parameter, SupplyParameterFromQuery]
    public int? PageIndex { get; set; }
    public Shared.DTOs.PagingDto<CirculationDto>? request { get; set; }
    private Modal modal = default!;
    // alert
    AlertColor alertColor = AlertColor.Primary;
    IconName alertIconName = IconName.CheckCircleFill;
    bool Hidealert = true;
    string alertMessage = "";
    //itemSearch
    public string date { get; set; }
    public int CODID { get; set; }
    public List<CODIdName<int>>? CODrequest { get; set; }
}
@functions {
    protected override async Task OnInitializedAsync()
    {
        SpinnerVisible = true;
        CODrequest = await fv.GetCODs();
        SpinnerVisible = false;
        await base.OnInitializedAsync();
    }
    protected override async Task OnParametersSetAsync()
    {
        SpinnerVisible = true;
        if (PageIndex == null) PageIndex = 1;
        await Load(PageIndex.Value);
        SpinnerVisible = false;
        await base.OnParametersSetAsync();
    }
    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 Load(int pi)
    {
        string query = "";

        if (!string.IsNullOrEmpty(date))
        {
            if (date.Replace("/","").Length==10)
                query = $"date={date}&";
            else
            {
                ShowDangerAlert("تاریخ صحیح نمی باشد");
                return;
            }
        }

        if (CODID != null && CODID != 0)
            query += $"CODID={CODID}&";

        SpinnerVisible = true;

        PreloadService.Show(SpinnerColor.Dark);
        var rsp = await hc.Get("Warehouse/Circulation?" + query + $"PageIndex={pi}&PageSize=5");
        if (rsp.IsSuccessStatusCode)
        {
            request = await rsp.Content.ReadFromJsonAsync<PagingDto<CirculationDto>>();
        }
        else if (rsp.StatusCode == System.Net.HttpStatusCode.Forbidden)
        {
            ShowDangerAlert("شما دسترسی به خواندن اطلاعات را نداربد");
        }
        else
        {
            ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
        }
        PreloadService.Hide();
        SpinnerVisible = false;
    }
    public async Task CallBackItem(ActionInResultComponent result)
    {
        if (result.Status == ComponentStatus.success && result.Action==ComponentAction.delete)
            ShowSuccessAlert("حذف با موفقیت انجام شد");
        if (result.Status == ComponentStatus.success && result.Action == ComponentAction.update)
            ShowSuccessAlert("ویرایش با موفقیت انجام شد");
        if (result.Status == ComponentStatus.success && result.Action == ComponentAction.add)
            ShowSuccessAlert("سند جدید اضافه شد");

        if (result.Status==ComponentStatus.success)
        {
            await Load(1);
           await modal.HideAsync();
        }
    }
    public async Task Item(CirculationDto circulationDto)
    {
        string title = "";
        //رسید
        if (circulationDto.Type == TypeCirculation.Receipt)
            title = "رسید";

        //حواله
        if (circulationDto.Type == TypeCirculation.Remittance)
            title = "حواله";


        if (circulationDto.CODID == 0)
            title += " جدید";
        else title = "اطلاعات " + title;
        var parameters = new Dictionary<string, object>();


        parameters.Add("OnMultipleOfThree", EventCallback.Factory.Create<ActionInResultComponent>(this, CallBackItem));
        parameters.Add("model", circulationDto);
        parameters.Add("NewItem", circulationDto.CODID == 0);
        parameters.Add("CODrequest", CODrequest);
        await modal.ShowAsync<WarehouseItem>(title: title, parameters: parameters);


    }
}