@using Front.Services
@using Shared.DTOs
@using Shared
@inject HttpClientController hc;
@layout PanelLayout
@inject Fixedvalues fv;
@page "/InvoiceDetails/{InvoiceID:int}"
@page "/InvoiceDetails"
<Modal @ref="modal" />
<Preload LoadingText="در حال بارگذاری..." />
<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>

    <div class="row g-3">
        <div class="form-group col-md-2">
            <label class="col-sm-4 col-form-label" style="color:red" for="inputTitle">عنوان</label>
            <InputText @bind-Value="invoice.Title" type="text" class="form-control" id="inputTitle" placeholder="عنوان" />
        </div>
        <div class="form-group col-md-2">
            <label class="col-sm-4 col-form-label" for="inputinvoiceTypeTitle">نوع</label>
            <select @bind="invoice.invoiceType" class="form-control" aria-label="Default select example" id="inputinvoiceTypeTitle">
                @if (!invoice.invoiceType.HasValue)
                {
                    <option value="0" style="color: #b5b5b5" selected>انتخاب کنید...</option>
                }
                else
                {
                    <option value="0" style="color: #b5b5b5">انتخاب کنید...</option>
                }


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

                    if (invoice.invoiceType == i)
                    {
                        <option value="@i" selected>@i.GetEnumDisplayName()</option>
                    }
                    else
                    {
                        <option value="@i">@i.GetEnumDisplayName()</option>
                    }

                }


            </select>
        </div>

        <div class="form-group col-md-2">
            <label class="col-sm-8 col-form-label" for="inputPatternID">الگو صورتحساب</label>
            <select @bind="invoice.PatternID" class="form-control" aria-label="Default select example" id="inputPatternID">
                @if (invoice.PatternID == null || invoice.PatternID == 0)
                {
                    <option value="0" style="color: #b5b5b5" selected>انتخاب کنید...</option>
                }
                else
                {
                    <option value="0" style="color: #b5b5b5">انتخاب کنید...</option>
                }

                @if (Patterns != null)
                {
                    foreach (var item in Patterns)
                    {
                        if (invoice.PatternID == 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-2">
            <label class="col-sm-5 col-form-label" style="color:red" for="inputCustomerID">مشتری</label>
            <select @bind="invoice.CustomerID" class="form-control" aria-label="Default select example" id="inputCustomerID">
                @if (invoice.CustomerID == null || invoice.CustomerID == 0)
                {
                    <option value="0" style="color: #b5b5b5" selected>انتخاب کنید...</option>
                }
                else
                {
                    <option value="0" style="color: #b5b5b5">انتخاب کنید...</option>
                }

                @if (Cus != null)
                {
                    foreach (var item in Cus)
                    {
                        if (invoice.CustomerID == item.ID)
                        {
                            <option value="@item.ID" selected>@item.CustomerName</option>
                        }
                        else
                        {
                            <option value="@item.ID">@item.CustomerName</option>
                        }
                    }
                }
            </select>
        </div>
        <div class="form-group col-md-2">
            <label class="col-sm-5 col-form-label" for="inputInvoicIssueDate">تاریخ صدور</label>
            <InputText style=" text-align: center;" @bind-Value="invoice.InvoicIssueDate" type="text" class="form-control" id="inputInvoicIssueDate" placeholder="تاریخ صدور" />
        </div>
        <div class="form-group col-md-2">
            <label class="col-sm-4 col-form-label" for="inputInvoiceDate">تاریخ</label>
            <InputText style=" text-align: center;" @bind-Value="invoice.InvoiceDate" type="text" class="form-control" id="inputInvoiceDate" placeholder="تاریخ" />
        </div>
    </div>
    <br />  <hr class="hr" />
    <div class="row g-3">
        <Tabs NavStyle="NavStyle.VerticalUnderline">
            <Tab Title="آیتم ها" IsActive="InvoiceID==0 || InvoiceID==null ? false : true">
                <Content>
                    <div class="row g-3">
                        <div class="form-group col-md-11">
                            <LGridInvoiceItem InvoiceID="InvoiceID??0" OnMultipleOfThree="EventCallback.Factory.Create<string>(this, CallBack)" InvoiceItems="invoice.items" />
                        </div>
                        <div class="form-group col-md-1">

                            <Button class="mt-3" Color="ButtonColor.Dark" @onclick="NewItemClick" Outline="true" Type="ButtonType.Button">
                                +
                            </Button>
                        </div>
                    </div>

                </Content>
            </Tab>
            @*  <Tab Title="پرداختی ها">
            <Content>
            <div class="row g-3">
            <div class="form-group col-md-11">
            <LGridInvoicePayment InvoicePays="invoice.payments" />
            </div>
            <div class="form-group col-md-1">

            <Button class="mt-3" Color="ButtonColor.Dark" @onclick="OnClickDelete" Outline="true" Type="ButtonType.Button">
            +
            </Button>
            </div>
            </div>


            </Content>
            </Tab> *@

        </Tabs>
    </div>
    <hr class="hr" />
    <br />
    <div class="row g-3">
        <div class="form-group col-md-8">
            <label class="col-sm-4 col-form-label" for="inputdes">توضیحات</label>
            <InputText @bind-Value="invoice.Des" type="text" class="form-control" id="inputdes" placeholder="توضیحات" />
        </div>
        <div class="form-group col-md-2">
            <label class="col-sm-5 col-form-label" for="inputUdate">آخرین ویرایش</label>
            <InputText style=" text-align: center;" @bind-Value="invoice.Udate" class="form-control" id="inputUdate" readonly />

        </div>
        <div class="form-group col-md-2">
            <br />
            @if (invoice.ID == 0)
            {
                <Button class="mt-3" Color="ButtonColor.Success" @onclick="OnClickAdd" Type="ButtonType.Button">
                    جدید
                </Button>
            }
            else
            {
                <Button class="mt-3" Color="ButtonColor.Success" @onclick="OnClickUpdate" Type="ButtonType.Button">
                    ثبت تغییرات
                </Button>
                <Button class="mt-3" Color="ButtonColor.Danger" @onclick="ShowConfirmationDeleteAsync" Type="ButtonType.Button">
                    حذف
                </Button>
            }
        </div>
    </div>



</form>





@code {
    [Inject] ToastService ToastService { get; set; } = default!;
    private ConfirmDialog dialog = default!;
    private Modal modal = default!;
    [Inject] protected PreloadService PreloadService { get; set; } = default!;
    // alert
    AlertColor alertColor = AlertColor.Primary;
    IconName alertIconName = IconName.CheckCircleFill;
    bool Hidealert = true;
    string alertMessage = "";
    [Parameter] public int? InvoiceID { get; set; }
    public List<ForCustomerSearch>? Cus { get; set; }
    public List<IdName<int>>? Patterns { get; set; }
    public InvoiceDTO? invoice { get; set; }

    protected override async Task OnInitializedAsync()
    {
        invoice = new InvoiceDTO();
        await base.OnInitializedAsync();
    }

    protected override async Task OnParametersSetAsync()
    {
        PreloadService.Show(SpinnerColor.Dark);
        Cus = await fv.GetCustomers();
        Patterns = await fv.GetPatterns();
        if (InvoiceID != null && InvoiceID > 0)
        {

            await LoadData();
        }
        else
        {
            invoice = new InvoiceDTO()
                {
                    ID = 0,
                    InvoiceDate = DateTime.Now.ConvertMiladiToShamsiinFront().ShamciToFormatShamciinFront(),
                    InvoicIssueDate = DateTime.Now.ConvertMiladiToShamsiinFront().ShamciToFormatShamciinFront(),
                    Udate = DateTime.Now.ConvertMiladiToShamsiinFront().ShamciToFormatShamciinFront()
                };
        }


        Hidealert = true;
        alertMessage = "";
        PreloadService.Hide();
        await base.OnParametersSetAsync();
    }
}
@functions {
    private async Task NewItemClick()
    {
        if (InvoiceID.HasValue)
        {
            var parameters = new Dictionary<string, object>();

            parameters.Add("InvoiceID", InvoiceID);
            parameters.Add("itemDTO", new InvoiceItemDTO());
            parameters.Add("OnMultipleOfThree", EventCallback.Factory.Create<ActionInResultComponent>(this, CallBack));
            await modal.ShowAsync<CUSComponent.InvoiceItem>(title: "آیتم جدید", parameters: parameters);
        }


    }
    private async Task LoadData()
    {
        var rsp = await hc.Get($"Invoice/Get/{InvoiceID}");
        if (rsp.IsSuccessStatusCode)
        {
            invoice = await rsp.Content.ReadFromJsonAsync<InvoiceDTO>();
        }
        else
            hc._nav.NavigateTo("/Panel");
    }
    public async Task CallBack(ActionInResultComponent result)
    {
        string msg = "";
        if (result.Action == ComponentAction.add)
        {
            if (result.Status == ComponentStatus.success)
                msg = "آیتم جدید با موفقیت اضافه شد";

        }
        else if (result.Action == ComponentAction.update)
        {
            if (result.Status == ComponentStatus.success)
                msg = "اطلاعات آیتم با موفقیت ویرایش شد";
        }
        else if (result.Action == ComponentAction.delete)
        {
            if (result.Status == ComponentStatus.success)
                msg = "آیتم با موفقیت حذف شد";
        }
        await CallBack(msg);
        // if (result.Status == ComponentStatus.success)
        //     await LoadCod(1);

        await modal.HideAsync();
    }
    private async Task CallBack(string result)
    {
        if (!string.IsNullOrEmpty(result))
        {
            ShowSuccessAlert(result);
            await LoadData();
        }
    }
    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 (InvoiceID.HasValue)
        {
            var rsp = await hc.Delete($"Invoice/Delete/{InvoiceID.Value}");
            if (rsp.IsSuccessStatusCode)
            {
                var request = await rsp.Content.ReadFromJsonAsync<bool>();
                if (request)
                {
                    ToastService.Notify(new ToastMessage(ToastType.Success, $"عملیات حذف با موفقیت انجام شد"));
                    hc._nav.NavigateTo("Invoice");
                }
                else ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
            }

            else if (rsp.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                ShowDangerAlert("صورتحساب با این شناسه یافت نشد");
            }
            else ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
        }


    }
    public async Task OnClickUpdate()
    {
        if (InvoiceID.HasValue)
        {
            if (await Validate())
            {
                var rsp = await hc.Put<NUInvoiceDTO>("Invoice/Update", new NUInvoiceDTO
                    {
                        ID = InvoiceID,
                        CustomerID = invoice.CustomerID,
                        Des = invoice.Des,
                        InvoiceDate = invoice.InvoiceDate,
                        InvoicIssueDate = invoice.InvoicIssueDate,
                        PatternID = invoice.PatternID,
                        Title = invoice.Title
                    });
                if (rsp.IsSuccessStatusCode)
                {
                    var request = await rsp.Content.ReadFromJsonAsync<int>();

                    if (request > 0)
                    {
                        InvoiceID = request;
                    }
                    else ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
                }
                else
                {

                    var request = await rsp.Content.ReadFromJsonAsync<List<string>>();
                    ShowDangerAlert(request[0]);
                }
            }
        }
        // if (Cod.UnitID > 0 && Cod.TaxRate > 0 && !string.IsNullOrEmpty(Cod.Title))
        // {

        //     var rsp = await hc.Put<RCOD>("Cod/Update", Cod);
        //     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]);
        //     }
        // }
        // else ShowDangerAlert("فیلدهای قرمز باید مقدار دهی شوند");
    }
    public async Task OnClickAdd()
    {
        if (await Validate())
        {
            var rsp = await hc.Post<NUInvoiceDTO>("Invoice/Add", new NUInvoiceDTO
                {
                    CustomerID = invoice.CustomerID,
                    Des = invoice.Des,
                    InvoiceDate = invoice.InvoiceDate,
                    InvoicIssueDate = invoice.InvoicIssueDate,
                    PatternID = invoice.PatternID,
                    Title = invoice.Title
                });
            if (rsp.IsSuccessStatusCode)
            {
                var request = await rsp.Content.ReadFromJsonAsync<int>();

                if (request > 0)
                {
                    InvoiceID = request;
                }
                else ShowDangerAlert("خطایی در اجرای عملیات رخ داده");
            }
            else
            {

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

    }
    public async Task<bool> Validate()
    {
        if (string.IsNullOrEmpty(invoice.Title))
        {
            ShowDangerAlert("عنوان نمی تواند خالی باشد");
            return false;
        }


        if (string.IsNullOrEmpty(invoice.InvoiceDate))
        {
            ShowDangerAlert("تاریخ صورتحساب نمی تواند خالی باشد");
            return false;
        }
        else
        {
            int InvoiceDate = 0;
            if (invoice.InvoiceDate.Replace("/", "").Length != 8 || !int.TryParse(invoice.InvoiceDate.Replace("/", ""), out InvoiceDate))
            {
                ShowDangerAlert("تاریخ صورتحساب صحیح نمی باشد");
                return false;
            }


            else if (InvoiceDate.ToString().Trim().ToMiladiinFront() > DateTime.Now)
            {
                ShowDangerAlert("تاریخ صورتحساب نمی تواند از امروز جلوتر باشد");
                return false;
            }

        }


        if (string.IsNullOrEmpty(invoice.InvoicIssueDate))
        { ShowDangerAlert("تاریخ صدور نمی تواند خالی باشد"); return false; }
        else
        {
            int InvoicIssueDate = 0;
            if (invoice.InvoicIssueDate.Replace("/", "").Length != 8 || !int.TryParse(invoice.InvoicIssueDate.Replace("/", ""), out InvoicIssueDate))
            { ShowDangerAlert("تاریخ صدور صحیح نمی باشد"); return false; }

            else if (InvoicIssueDate.ToString().Trim().ToMiladiinFront() > DateTime.Now)
            { ShowDangerAlert("تاریخ صدور نمی تواند از امروز جلوتر باشد"); return false; }
        }

        if (invoice.PatternID.HasValue)
            if (invoice.PatternID <= 0 || !Patterns.Any(w => w.ID == invoice.PatternID.Value))
            { ShowDangerAlert("شناسه الگو صحیح نمی باشد"); return false; }

        if (invoice.CustomerID == null || invoice.CustomerID <= 0 || !Cus.Any(w => w.ID == invoice.CustomerID))
        { ShowDangerAlert("مشتری صحیح نمی باشد"); return false; }

        return true;
    }
    private async Task ShowConfirmationDeleteAsync()
    {
        if (InvoiceID.HasValue)
        {
            var confirmation = await dialog.ShowAsync(
                title: "عملیات حذف صورتحساب",
                message1: $"از حذف صورتحساب {InvoiceID}",
                message2: "اطمینان دارید?");

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

        }

    }
}