@using Front.Services
@using Shared.DTOs
@inject HttpClientController hc;
@inject Fixedvalues fv;
<ConfirmDialog @ref="dialog" />
<Toasts AutoHide="true" Delay="6000" class="p-3" Messages="messages" Placement="ToastsPlacement.TopRight" />

<form>
    @* 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="form-group col-md-5">
            <label class="col-sm-4 col-form-label" style="color:red" for="inputcod">کالا</label>
            <select @bind="itemDTO.CODID" @bind:after="async () =>
            {
           await  AfterAsync();
                itemDTO.vra=await GetVra(itemDTO.CODID);
            }" class="form-control" aria-label="Default select example" id="inputcod">
                @if (itemDTO.CODID > 0)
                {
                    <option value="0" style="color: #b5b5b5">انتخاب کنید...</option>


                }
                else
                {
                    <option value="0" style="color: #b5b5b5" selected>انتخاب کنید...</option>

                }

                @if (cods != null)
                {
                    foreach (var item in cods)
                    {
                        if (itemDTO.CODID == item.ID)
                        {
                            <option value="@item.ID" selected>@item.Title</option>
                        }
                        else
                        {
                            <option value="@item.ID">@item.Title</option>
                        }
                    }
                }
            </select>
        </div>
        <div class="form-group col-md-3">
            <label class="col-sm-6 col-form-label">نرخ مالیات</label>
            <InputNumber @bind-Value="itemDTO.vra" type="text" class="form-control" id="inputvra" placeholder="نرخ مالیات" />
        </div>
        <div class="form-group col-md-4">
            <label class="col-sm-4 col-form-label" style="color:red" for="inputFullName">تعداد</label>
            <InputNumber @bind-Value="itemDTO.am" @bind-Value:after="AfterAsync" type="text" class="form-control" id="inputam" placeholder="تعداد" />
        </div>

    </div>

    <div class="row g-3">
        <div class="form-group col-md-6">
            <label style="color:red" class="col-sm-6 col-form-label">مبلغ واحد</label>
            <CurrencyInput TValue="decimal" @bind-Value="@itemDTO.fee" @bind-Value:after="AfterAsync" Locale="fa-Ir" Placeholder="مبلغ واحد" />
            @*   <InputNumber @bind-Value="itemDTO.fee" @bind-Value:after="AfterAsync" type="text" class="form-control" id="inputfee" placeholder="مبلغ واحد" /> *@
        </div>
        <div class="form-group col-md-6">
            <label class="col-sm-6 col-form-label">مبلغ کل</label>
            <CurrencyInput TValue="decimal?" @bind-Value="itemDTO.prdis" Locale="fa-Ir" Placeholder="مبلغ کل" readonly />
        </div>

    </div>
    <div class="row g-3">
        <div class="col-md-6">
            <label class="col-sm-6 col-form-label">مبلغ تخفیف</label>
            <CurrencyInput TValue="decimal?" @bind-Value="itemDTO.dis" Locale="fa-Ir" @bind-Value:after="AfterAsync" Placeholder="مبلغ تخفیف" />
        </div>
        <div class="col-md-6">
            <label class="col-sm-8 col-form-label">مبلغ بعد تخفیف</label>
            <CurrencyInput TValue="decimal?" @bind-Value="itemDTO.adis" Locale="fa-Ir" Placeholder="مبلغ بعد تخفیف" readonly />
        </div>
    </div>
    <div class="row g-3">

        <div class="form-group col-md-6">
            <label class="col-sm-6 col-form-label">مبلغ مالیات</label>
            <CurrencyInput TValue="decimal?" @bind-Value="itemDTO.vam" Locale="fa-Ir" Placeholder="مبلغ مالیات" readonly />
        </div>
        <div class="form-group col-md-6">
            <label class="col-sm-6 col-form-label">مبلغ نهایی</label>
            <CurrencyInput TValue="decimal?" @bind-Value="itemDTO.tsstam" Locale="fa-Ir" Placeholder="مبلغ نهایی" readonly />
        </div>
    </div>
</form>

<div class="row g-3">
    <div class="col-md-10">
        @if (itemDTO.ID == null)
        {
            <Button Disabled="SpinnerVisible" class="mt-3" Color="ButtonColor.Success" @onclick="OnClickAdd" Type="ButtonType.Button">
                جدید
            </Button>
        }
        else
        {
            <Button Disabled="SpinnerVisible" class="mt-3" Color="ButtonColor.Success" @onclick="OnClickUpdate" Type="ButtonType.Button">
                ثبت تغییرات
            </Button>
            <Button Disabled="SpinnerVisible" class="mt-3" Color="ButtonColor.Danger" @onclick="ShowConfirmationDeleteAsync" Type="ButtonType.Button">
                حذف
            </Button>
        }
    </div>
    <div class="col-md-2">
        <Spinner Visible="SpinnerVisible" Color="SpinnerColor.Primary" />
    </div>
</div>

@code {
    public bool SpinnerVisible { get; set; } = false;
    List<ToastMessage> messages = new List<ToastMessage>();
    private ConfirmDialog dialog = default!;
    // alert
    AlertColor alertColor = AlertColor.Primary;
    IconName alertIconName = IconName.CheckCircleFill;
    bool Hidealert = true;
    string alertMessage = "";
    public int Tax { get; set; } = 0;
    [Parameter] public int InvoiceID { get; set; }
    [Parameter] public InvoiceItemDTO itemDTO { get; set; }
    [Parameter] public EventCallback<ActionInResultComponent> OnMultipleOfThree { get; set; }
    public List<CODIdName<int>> cods { get; set; } = new();
    public ActionInResultComponent result { get; set; }
    protected override async Task OnInitializedAsync()
    {
        SpinnerVisible = true;
        cods = await fv.GetCODs();
        SpinnerVisible = false;
        await base.OnInitializedAsync();
    }
    protected override async Task OnParametersSetAsync()
    {
        SpinnerVisible = false;
        if (!itemDTO.ID.HasValue)
            itemDTO.vra = 0;
        result = new ActionInResultComponent()
            {
                Status = ComponentStatus.fild
            };
        Hidealert = true;
        alertMessage = "";
        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 void ShowSuccessAlert(string msg)
    {
        Hidealert = false;
        alertColor = AlertColor.Success;
        alertIconName = IconName.CheckCircleFill;
        alertMessage = msg;
    }
    private async Task<decimal> GetVra(int CODID)
    {
        var rsp = await hc.Get($"COD/GetVra/{CODID}");
        if (rsp.IsSuccessStatusCode)
        {
            return await rsp.Content.ReadFromJsonAsync<decimal>();
        }

        return 0;
    }
    private void ShowDangerAlert(string msg)
    {
        Hidealert = false;
        alertColor = AlertColor.Danger;
        alertIconName = IconName.ExclamationTriangleFill;
        alertMessage = msg;
    }
    //-----------------------
    private async Task prdisAsync()
    {
        //   if (itemDTO.ID == null)
        itemDTO.prdis = itemDTO.fee * itemDTO.am;
    }
    private async Task adisAsync()
    {
        //  if (itemDTO.ID == null)
        itemDTO.adis = itemDTO.prdis - itemDTO.dis;

        //  await AftervamAsync();
    }
    private async Task vamAsync()
    {
        //  if (itemDTO.ID == null)
        itemDTO.vam = itemDTO.vra * itemDTO.adis / 100;
    }
    private async Task tsstamAsync()
    {
        //  if (itemDTO.ID == null)
        itemDTO.tsstam = itemDTO.vam + itemDTO.adis;
    }
    private async Task AfterAsync()
    {
        await prdisAsync();
        await adisAsync();
        await vamAsync();
        await tsstamAsync();
    }
    //-----------------------
    public async Task OnClickDelete()
    {
        SpinnerVisible = true;
        var rsp = await hc.Delete($"InvoiceItem/DeleteItem/{itemDTO.ID}");
        if (rsp.IsSuccessStatusCode)
        {
            var request = await rsp.Content.ReadFromJsonAsync<bool>();
            if (request)
            {
                result.Status = ComponentStatus.success;
                result.Action = ComponentAction.delete;
                await OnMultipleOfThree.InvokeAsync(result);
            }
            else ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
        }

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



    }
    public async Task OnClickUpdate()
    {
        SpinnerVisible = true;
        if (itemDTO.CODID == null || itemDTO.CODID <= 0)
        {
            ShowDangerAlert("کالا انتخاب نشده");
            SpinnerVisible = false;
            return;
        }

        if (itemDTO.am == null || itemDTO.am <= 0)
        {
            ShowDangerAlert("تعداد وارد نشده");
            SpinnerVisible = false;
            return;
        }

        if (itemDTO.fee == null || itemDTO.fee < 0)
        {
            ShowDangerAlert("مبلغ واحد وارد نشده"); SpinnerVisible = false;
            return;
        }

        if (itemDTO.dis == null || itemDTO.dis < 0)
        {
            ShowDangerAlert("مبلغ تخفیف درست نیست"); SpinnerVisible = false;
            return;
        }
        var rsp = await hc.Put<InvoiceItemAction<InvoiceItemDTO>>($"InvoiceItem/UpdateItem"
        , new InvoiceItemAction<InvoiceItemDTO>
            {
                invoiceID = InvoiceID,
                item = itemDTO
            });
        if (rsp.IsSuccessStatusCode)
        {
            var request = await rsp.Content.ReadFromJsonAsync<bool>();
            if (request)
            {
                result.Status = ComponentStatus.success;
                result.Action = ComponentAction.update;
                await OnMultipleOfThree.InvokeAsync(result);
            }
            else ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
        }
        else
        {
            var request = await rsp.Content.ReadFromJsonAsync<List<string>>();
            ShowDangerAlert(request[0]);
        }
        SpinnerVisible = false;
    }
    public async Task OnClickAdd()
    {
        SpinnerVisible = true;
        if (itemDTO.CODID == null || itemDTO.CODID <= 0)
        {
            ShowDangerAlert("کالا انتخاب نشده"); SpinnerVisible = false;
            return;
        }

        if (itemDTO.am == null || itemDTO.am <= 0)
        {
            ShowDangerAlert("تعداد وارد نشده"); SpinnerVisible = false;
            return;
        }

        if (itemDTO.fee == null || itemDTO.fee < 0)
        {
            ShowDangerAlert("مبلغ واحد وارد نشده"); SpinnerVisible = false;
            return;
        }

        if (itemDTO.dis == null || itemDTO.dis < 0)
        {
            ShowDangerAlert("مبلغ تخفیف درست نیست"); SpinnerVisible = false;
            return;
        }

        var rsp = await hc.Post<InvoiceItemAction<InvoiceItemDTO>>($"InvoiceItem/AddItem", new InvoiceItemAction<InvoiceItemDTO>
            {
                invoiceID = InvoiceID,
                item = itemDTO
            });
        if (rsp.IsSuccessStatusCode)
        {
            var request = await rsp.Content.ReadFromJsonAsync<bool>();

            if (request)
            {
                result.Status = ComponentStatus.success;
                result.Action = ComponentAction.add;
                await OnMultipleOfThree.InvokeAsync(result);
            }
            else ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
        }
        else
        {
            var request = await rsp.Content.ReadFromJsonAsync<List<string>>();
            ShowDangerAlert(request[0]);
        }
        SpinnerVisible = false;
    }
    private async Task ShowConfirmationDeleteAsync()
    {
        if (itemDTO.ID != null && itemDTO.ID > 0 && InvoiceID != null && InvoiceID > 0)
        {
            var confirmation = await dialog.ShowAsync(
                title: "عملیات حذف آیتم صورتحساب",
                message1: $"از حذف کالای {itemDTO.sstt} از صورتحساب {InvoiceID}",
                message2: "اطمینان دارید?");

            if (confirmation)
            {
                await OnClickDelete();
            }
            else
            {
                ShowMessage(ToastType.Secondary, "عملیات حذف متوقف شد");
            }

        }

    }
}