@using Front.Services
@using Shared
@using Shared.DTOs
@using Shared.DTOs.Warehouse
@using Shared.Enums
@inject HttpClientController hc;
<ConfirmDialog @ref="dialog" />
<form>
    @* alert *@
    <div class="row">
        <Alert hidden="@Hidealert" Color="@alertColor" Dismissable="false">
            <Icon Name="@alertIconName" class="me-2"></Icon>
            @alertMessage
        </Alert>
    </div>

    @if (_UsedFromInvoice)
    {
        <ul>
            <li style="color:red"> این سند از فاکتور صادر شده، ویرایش مستقیم آن ممکن نیست</li>
            <br />
        </ul>
    }

    <div class="row g-3">
        <div class="form-group col-md-6">
            <label class="col-sm-4 col-form-label" style="color:red" for="inputFullName">کالا</label>

            <AutoComplete @bind-Value="model.CODTitle"
                          TItem="CODIdName<int>"
                          DataProvider="CODDataProvider"
                          PropertyName="Title"
                          Placeholder="جستجو در کالا..."
                          Disabled="!NewItem"
                          OnChanged="(CODIdName<int> cod) => OnAutoCompleteChanged(cod)" />
        </div>
        <div class="form-group col-md-3">
            <label class="col-sm-4 col-form-label" style="color:red">مقدار</label>
            <InputNumber @bind-Value="model.Count" style="text-align:center" type="text" class="form-control" placeholder="مقدار" />
        </div>
        <div class="form-group col-md-3">
            <label class="col-sm-5 col-form-label" for="inputInvoicIssueDate">تاریخ</label>
            <InputText style=" text-align: center;" @bind-Value="model.Date" type="text" class="form-control" id="inputInvoicIssueDate" placeholder="تاریخ" />
        </div>
    </div>
    <div class="row g-3">
        <div class="col-md-4">
            <label class="col-sm-4 col-form-label" style="color:red">نوع سند</label>

            <select style="text-align:center" @bind="model.ModelTypeID" class="form-control" aria-label="Default select example">
                <option value="0" style="color: #b5b5b5" selected>نوع سند ...</option>
                @if (model.Type == TypeCirculation.Receipt)
                {
                    <option value="1">خرید</option>
                    <option value="2">امانت</option>
                }
                @if (model.Type == TypeCirculation.Remittance)
                {

                    <option value="3">فروش</option>
                    <option value="4">امانت</option>
                }


            </select>
        </div>
        <div class="form-group col-md-8">
            <label class="col-form-label" for="inputdes">توضیحات</label>
            <InputText @bind-Value="model.info" type="text" class="form-control" id="inputdes" placeholder="توضیحات" />
        </div>

    </div>
    @*     <div class="col-md-2">
    <select style="text-align:center" @bind="Doctype" class="form-control" aria-label="Default select example">
    <option value="0" style="color: #b5b5b5" selected>نوع ...</option>
    <option value="10">رسید</option>
    <option value="20">حواله</option>
    </select>
    </div> *@





    @if (model.Type == TypeCirculation.Receipt)
    {
        <div class="row g-3">
            <div class="form-group col-md-4" style="margin-top:30px">
                <Switch @bind-Value="forsale" Label="اجازه فروش" />
            </div>
        </div>
    }

</form>
<div class="row g-3">
    <div class="col-md-10">
        @if (NewItem)
        {
            <Button class="mt-3" Color="ButtonColor.Success" @onclick="OnClickAddOrUpdate" Type="ButtonType.Button">
                جدید
            </Button>
        }
        else
        {
            @if (!_UsedFromInvoice)
            {
                <Button Disabled="SpinnerVisible" class="mt-3" Color="ButtonColor.Success" @onclick="OnClickAddOrUpdate" 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 {
    [Parameter] public CirculationDto model { get; set; }
    [Parameter] public EventCallback<ActionInResultComponent> OnMultipleOfThree { get; set; }
    [Parameter] public bool NewItem { get; set; }
    [Parameter] public List<CODIdName<int>> CODrequest { get; set; }
    private ConfirmDialog dialog = default!;

    AlertColor alertColor = AlertColor.Primary;
    IconName alertIconName = IconName.CheckCircleFill;
    bool Hidealert = true;
    string alertMessage = "";

    bool _UsedFromInvoice = false;

    public bool SpinnerVisible { get; set; } = false;

    private bool forsale { get; set; } = true;
}
@functions {
    protected override async Task OnParametersSetAsync()
    {
        if (NewItem)
            forsale = true;

        else
            forsale = model.ForSale.HasValue ? model.ForSale.Value : false;
        _UsedFromInvoice = model.invoiceID.HasValue;
        if (NewItem)
            model.Date = DateTime.Now.ConvertMiladiToShamsiinFront().ShamciToFormatShamciinFront();

        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 OnClickDelete()
    {
        if (NewItem)
            return;

        SpinnerVisible = true;
        await Delete();
        SpinnerVisible = false;

    }
    private async Task Delete()
    {
        string route = model.Type == TypeCirculation.Receipt ? "Receipt" : "Remittance";

        var rsp = await hc.Delete($"{route}/{model.ID}");
        if (rsp.IsSuccessStatusCode)
        {
            
                ActionInResultComponent result = new ActionInResultComponent();
                result.Status = ComponentStatus.success;
                result.Action = ComponentAction.delete;
                await OnMultipleOfThree.InvokeAsync(result);
           
        }

        else if (rsp.StatusCode == System.Net.HttpStatusCode.NotFound)
        {
            ShowDangerAlert("سندی یافت نشد");
        }
        else ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
    }
    private async Task Addorupdate()
    {
        if ((model.Type == TypeCirculation.Receipt && !await ValidateReceipt())
        || (model.Type == TypeCirculation.Remittance && !await ValidateRemittance()))
            return;


        string controller = model.Type == TypeCirculation.Receipt ? "Receipt" : "Remittance";
        string route = NewItem ? "ADD" : "Update";
        ActionInResultComponent result = new ActionInResultComponent();
        HttpResponseMessage rsp = new HttpResponseMessage();

        if (NewItem)
        {
            if (model.Type == TypeCirculation.Receipt)
                rsp = await hc.Post($"{controller}/{route}", new ReceiptDto()
                    {
                        CODID = model.CODID,
                        Count = model.Count,
                        Date = model.Date,
                        ForSale = model.ForSale.Value,
                        info = model.info,
                        Type = (TypeReceipt)model.ModelTypeID,
                    });

            if (model.Type == TypeCirculation.Remittance)
                rsp = await hc.Post($"{controller}/{route}", new RemittanceDto()
                    {
                        CODID = model.CODID,
                        Count = model.Count,
                        Date = model.Date,
                        info = model.info,
                        Type = (TypeRemittance)model.ModelTypeID,
                    });
            result.Action = ComponentAction.add;
        }
        else
        {
            if (model.Type == TypeCirculation.Receipt)
                rsp = await hc.Put($"{controller}/{route}", new ReceiptDto()
                    {
                        ID = model.ID,
                        CODID = model.CODID,
                        Count = model.Count,
                        Date = model.Date,
                        ForSale = model.ForSale.Value,
                        info = model.info,
                        Type = (TypeReceipt)model.ModelTypeID,
                    });

            if (model.Type == TypeCirculation.Remittance)
                rsp = await hc.Put($"{controller}/{route}", new RemittanceDto()
                    {
                        ID = model.ID,
                        CODID = model.CODID,
                        Count = model.Count,
                        Date = model.Date,
                        info = model.info,
                        Type = (TypeRemittance)model.ModelTypeID,
                    });

            result.Action = ComponentAction.update;
        }


        if (rsp.IsSuccessStatusCode)
        {
            result.Status = ComponentStatus.success;

            await OnMultipleOfThree.InvokeAsync(result);

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

            }
            catch (Exception)
            {
                ShowDangerAlert("حظای سیستمی");
            }

        }
    }
    public async Task OnClickAddOrUpdate()
    {
        SpinnerVisible = true;
        await Addorupdate();
        SpinnerVisible = false;
    }
    private async Task ShowConfirmationDeleteAsync()
    {
        if (!NewItem)
        {
            var confirmation = await dialog.ShowAsync(
                title: "عملیات حذف سند انبار",
                message1: $"{model.info}",
                message2: "اطمینان دارید?");

            if (confirmation)
                await OnClickDelete();


        }

    }
    private async Task<bool> ValidateRemittance()
    {
        if (model.Type == TypeCirculation.Remittance)
        {
            if (model.ModelTypeID != 3 && model.ModelTypeID != 4)
                ShowDangerAlert("نوع سند صحیح نمی باشد");

            else return await Validate();
        }
        return false;
    }
    private async Task<bool> ValidateReceipt()
    {
        if (model.Type == TypeCirculation.Receipt)
        {
            model.ForSale = forsale;
            if (model.ModelTypeID != 1 && model.ModelTypeID != 2)
                ShowDangerAlert("نوع سند صحیح نمی باشد");

            else return await Validate();
        }
        return false;

    }
    private async Task<bool> Validate()
    {

        if (model.CODID == null || model.CODID == 0)
            ShowDangerAlert("کالایی انتخاب کنید");
        else if (model.Count <= 0)
            ShowDangerAlert("تعدادی وارد کنید");
        else if (string.IsNullOrEmpty(model.Date))
            ShowDangerAlert("تاریخ را مشخص کنید");
        else if (model.Date.Replace("/", "").Length != 8)
            ShowDangerAlert("تاریخ صحیح نمی باشد");
        else if (string.IsNullOrEmpty(model.info))
            ShowDangerAlert("توضیحی مشخص کنید");
        else return true;

        return false;
    }
    private async Task<AutoCompleteDataProviderResult<CODIdName<int>>> CODDataProvider(AutoCompleteDataProviderRequest<CODIdName<int>> request)
    {
        return await Task.FromResult(request.ApplyTo(CODrequest.OrderBy(cod => cod.ID)));
    }
    private void OnAutoCompleteChanged(CODIdName<int> cOD)
    {
        model.CODID = cOD.ID;
    }
}