@using Front.Services
@using Shared.DTOs
@inject HttpClientController hc;
@inject UserAuthenticationDTO userinfo
<Preload LoadingText="در حال بارگذاری..." />
<ConfirmDialog @ref="dialog" />

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

</div>
<div class="row g-3">
    <div class="col-md-2">
        <label class="col-sm-5 col-form-label">وضغیت</label>
        <input style="text-align: center;" value="@order.StatusTitle" type="text" class="form-control" id="StatusTitle" placeholder="وضغیت" readonly />
    </div>
    <div class="col-md-2">
        <label class="col-sm-5 col-form-label">تاریخ ایجاد</label>
        <InputText style="text-align: center;" @bind-Value="order.DateCreate" type="text" class="form-control" id="DateCreate" placeholder="تاریخ ایجاد" readonly />
    </div>
    @if (order.Status != StatusOrder.Create)
    {
        <div class="col-md-2">
            <label class="col-sm-5 col-form-label">@titledateapp</label>
            <InputText style="text-align: center;" @bind-Value="order.ApprovalDate" type="text" class="form-control" id="ApprovalDate" placeholder="@titledateapp" readonly />
        </div>
    }

</div>

<br />
<hr class="hr" />
<div class="row g-3">
    <Grid @ref="grid" TItem="OrderItemDto"
          AllowRowClick="true"
          AllowSorting="true"
          Class="table table-hover"
          DataProvider="DataProvider"
          AllowPaging="true"
          PageSize="10"
          Responsive="true">
        <GridColumn TItem="OrderItemDto" HeaderText="عنوان">
            @context.Title
        </GridColumn>
        <GridColumn TItem="OrderItemDto" HeaderText="تعداد">
            @context.CreditAmount
        </GridColumn>
        <GridColumn TItem="OrderItemDto" HeaderText="قیمت واحد">
            @context.APrice.ToString("N0")
        </GridColumn>
        <GridColumn TItem="OrderItemDto" HeaderText="تخفیف">
            @context.Discount.ToString("N0")
        </GridColumn>
        <GridColumn TItem="OrderItemDto" HeaderText="مالیات">
            @context.Tax.ToString("N0")
        </GridColumn>
        <GridColumn TItem="OrderItemDto" HeaderText="مبلغ کل">
            @context.Total.ToString("N0")
        </GridColumn>
    </Grid>

</div>
<hr class="hr" />
<div class="row g-3">

    <div class="col-md-3">
        <label class="col-sm-5 col-form-label">مبلغ سفارش</label>
        <CurrencyInput style="text-align: center;" TValue="decimal" @bind-Value="order.PreDiscount" Locale="fa-Ir" Placeholder="مبلغ سفارش" readonly />

    </div>

    <div class="col-md-3">
        <label class="col-sm-5 col-form-label">تخفیف سفارش</label>
        <CurrencyInput style="text-align: center;" TValue="decimal" @bind-Value="order.TDiscount" Locale="fa-Ir" Placeholder="تخفیف سفارش" readonly />
    </div>

    <div class="col-md-3">
        <label class="col-sm-5 col-form-label">مالیات</label>
        <CurrencyInput style="text-align: center;" TValue="decimal" @bind-Value="order.TTax" Locale="fa-Ir" Placeholder="مالیات" readonly />
    </div>

    @*     <div class="col-md-4">
    <label class="col-sm-5 col-form-label">بغد از تخفیف</label>
    <CurrencyInput TValue="decimal" @bind-Value="order.lstDiscount" Locale="fa-Ir" Placeholder="بغد از تخفیف" readonly />
    </div> *@
    <div class="col-md-3">
        <label class="col-sm-5 col-form-label">مبلغ نهایی</label>
        <CurrencyInput style="text-align: center;" TValue="decimal" @bind-Value="order.TPrice" Locale="fa-Ir" Placeholder="مبلغ نهایی" readonly />
    </div>
</div>

<div class="form-group col-md-4">
    <br />
    @if (order.Status == StatusOrder.Create)
    {
        <Button Disabled="SpinnerVisible" class="mt-3" Color="ButtonColor.Success" @onclick="OnClickPay" Type="ButtonType.Button">
            پرداخت با کیف پول
        </Button>
        <Button Disabled="SpinnerVisible" class="mt-3" Color="ButtonColor.Danger" @onclick="OnClickCancel" Type="ButtonType.Button">
            ابطال
        </Button>

    }

</div>
<div class="col-md-2">
    <Spinner Visible="SpinnerVisible" Color="SpinnerColor.Primary" />
</div>
@code {
    public bool SpinnerVisible { get; set; } = false;
    #region Alert
    // alert
    AlertColor alertColor = AlertColor.Primary;
    IconName alertIconName = IconName.CheckCircleFill;
    bool Hidealert = true;
    string alertMessage = "";
    #endregion
    private ConfirmDialog dialog = default!;
    public ActionInResultComponent result { get; set; }
    Grid<OrderItemDto> grid = default!;
    [Inject] protected PreloadService PreloadService { get; set; } = default!;
    [Parameter] public EventCallback<ActionInResultComponent> OnMultipleOfThree { get; set; }
    [Parameter] public OrderDto order { get; set; }
    List<OrderItemDto> OrderItems = new List<OrderItemDto>();
    string titledateapp = "تاریخ";
    protected override async Task OnParametersSetAsync()
    {
        Hidealert = true;
        if (order.Status == StatusOrder.Cancel)
        {
            titledateapp += " ابطال";
        }
        else if (order.Status == StatusOrder.Cancel)
        {
            titledateapp += " پرداخت";
        }
        await base.OnParametersSetAsync();
    }
}
@functions {
    private async Task<GridDataProviderResult<OrderItemDto>> DataProvider(GridDataProviderRequest<OrderItemDto> request)
    {
        OrderItems = await LoadOrderItem(); // call a service or an API to pull the employees

        return await Task.FromResult(request.ApplyTo(OrderItems));
    }
    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;
    }
    private async Task<List<OrderItemDto>> LoadOrderItem()
    {
       
        var rsp = await hc.Get($"Orders/GetOrderDetails/{order.ID}");
        if (rsp.IsSuccessStatusCode)
        {
            return await rsp.Content.ReadFromJsonAsync<List<OrderItemDto>?>();
        }
        else
        {

            ShowDangerAlert("خطایی در بارگیری");
            return new List<OrderItemDto>();
        }

    }
    private async Task OnClickPay()
    {
        SpinnerVisible = true;
        var rsp = await hc.Get($"Orders/SubmitOrderBywallet/{order.ID}");

        if (rsp.IsSuccessStatusCode)
        {
            userinfo.Company.Credit -= order.TPrice;
            result = new ActionInResultComponent();
            result.Status = ComponentStatus.success;
            result.Action = ComponentAction.add;

            await OnMultipleOfThree.InvokeAsync(result);
        }
        else
        {
            var request = await rsp.Content.ReadFromJsonAsync<List<string>>();
            ShowDangerAlert(request[0]);
        }

        SpinnerVisible = false;

    }
    private async Task OnClickCancel()
    {
        var confirmation = await dialog.ShowAsync(
                title: "عملیات ابطال سفارش",
                message1: $"از ابطال سفارش {order.ID}",
                message2: "اطمینان دارید?");

        if (confirmation)
        {
            SpinnerVisible = true;
            PreloadService.Show(SpinnerColor.Dark);
            var rsp = await hc.Delete($"Orders/CancelOrder/{order.ID}");
            PreloadService.Hide();
            if (rsp.IsSuccessStatusCode)
            {
                if (await rsp.Content.ReadFromJsonAsync<bool>())
                {
                    order.Status = StatusOrder.Cancel;
                    result = new ActionInResultComponent();
                    result.Status = ComponentStatus.success;
                    result.Action = ComponentAction.delete;
                    await OnMultipleOfThree.InvokeAsync(result);
                }
                else
                    ShowDangerAlert("خطای سیستمی");

         
            }
            else if (rsp.StatusCode == System.Net.HttpStatusCode.NotFound)
                ShowDangerAlert("سفارش یافت نشد");

            else
            {
                var request = await rsp.Content.ReadFromJsonAsync<List<string>>();
                ShowDangerAlert(request[0]);
            }
            SpinnerVisible = false;
        }

    }
}