@page "/TaxPayerInvoiceItem/{InvoiceID:int}"
@page "/FullInvoiceItem/{InvoiceID:int}"
@using Front.Services
@using Shared
@using Shared.DTOs
@layout PanelLayout
@inject HttpClientController hc;
@inject Fixedvalues fv;
<Preload LoadingText="در حال بارگذاری..." />
<ConfirmDialog @ref="dialog" />
<Toasts AutoHide="true" Delay="6000" class="p-3" Messages="messages" Placement="ToastsPlacement.TopRight" />
<Modal @ref="modal" />
@if (FullInvoice)
{
    <PageTitle>اطلاعات تکمیلی صورتحساب</PageTitle>
}
else
{
    <PageTitle>آماده سازی صورتحساب</PageTitle>
}


@* alert *@
<div class="row">

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

    
</div>
<div class="row">
    <div class="col-md-10">
@if (FullInvoice)
{
    <h4 class="fw-bold py-3 mb-4">
        <span class="text-muted fw-light">سرویس ها / صورتحساب /</span>  اطلاعات تکمیلی صورتحساب
    </h4>
}
else
{
    <h4 class="fw-bold py-3 mb-4">
        <span class="text-muted fw-light">سرویس ها / صورتحساب /</span>  آماده سازی قبل از ارسال به سامانه مودیان
    </h4>
    }
</div>
    <div class="col-md-2">
        <Spinner Visible="SpinnerVisible" Color="SpinnerColor.Primary" />
    </div>
</div>
@if (!FullInvoice)
{
    <div class="row">
        <div class="col-md-12">
            <div class="card mb-4">
                <h4 style="color:red;" class="card-header">توجه</h4>
                <div class="card-body">
                    <p>1) این یک پیش نمایش کامل از صورتحساب شماست با دقت آنرا بررسی کنید</p>
                    <p>2) یسری از فیلدها قابل دسترس هستند میتوانید در این مرحله اطلاعات تکمیلی بیشتری برای صورتحساب وارد کنید</p>
                    <p>3) فیلد هایی که قابل دسترسی نیستند به صورت خودکار از صورتحساب پر شده اند</p>
                    <p>4) فیلد های قرمز را حتما مشخص کنید</p>
                </div>
            </div>
        </div>
    </div>
}

<div class="row">
    <div class="col-md-12">
        <div class="card mb-4">
            <h5 class="card-header">اطلاعات تکمیلی سرآمد صورتحساب</h5>
            <div class="card-body">

                <form>
                    @if (invoice?.header != null)
                    {

                        <div class="row">
                            @foreach (var item in invoice?.header.filds)
                            {
                                <div class="mb-1 col-md-3">
                                    @if (item.ModeID == 1 && item.InputBox != "autofild")
                                    {
                                        if (item.Des != null && item.Des.Count() > 0 && !FullInvoice)
                                        {
                                            <Badge style="cursor: pointer;" @onclick="()=>ShowConditions(item.Des,item.fName)" Color="BadgeColor.Primary" IndicatorType="BadgeIndicatorType.RoundedPill">شرایط خاص</Badge>

                                            <label style="color:red;" class="form-label">@item.fName</label>


                                        }
                                        else
                                        {
                                            <label style="color:red;" class="form-label">@item.fName</label>
                                        }

                                    }
                                    else
                                    {
                                        if (item.Des != null && item.Des.Count() > 0 && !FullInvoice)
                                        {
                                            <Badge style="cursor: pointer;" @onclick="()=>ShowConditions(item.Des,item.fName)" Color="BadgeColor.Primary" IndicatorType="BadgeIndicatorType.RoundedPill">...</Badge>

                                            <label class="form-label">@item.fName</label>

                                        }
                                        else
                                        {
                                            <label class="form-label">@item.fName</label>
                                        }
                                    }
                                    @if (item.InputBox == "fromdb")
                                    {

                                        <select @bind="item.Value" class="form-control" aria-label="Default select example">
                                            <option style="color: #b5b5b5; " selected>@item.fName...</option>
                                            @foreach (var itema in item.DefVals)
                                            {
                                                if (itema.ID == item.Value)
                                                {
                                                    <option value="@itema.ID" selected>@itema.Name</option>
                                                }
                                                else
                                                {
                                                    <option value="@itema.ID">@itema.Name</option>
                                                }
                                            }
                                        </select>


                                    }
                                    else if (item.InputBox == "autofild")
                                    {
                                        if (item.eName.ToLower() == "inty")
                                        {
                                            var bill = BillTypes.Where(w => w.ID == Convert.ToInt32(item.Value)).Select(s => s.Title).FirstOrDefault();

                                            <input value="@bill" style="text-align:center;" class="form-control" type="text" placeholder="@item.fName" disabled />

                                        }
                                        else if (item.eName.ToLower() == "inp")
                                        {
                                            patt = item.Value;
                                            var _patt = Patterns.Where(w => w.ID == Convert.ToInt32(item.Value)).Select(s => s.Title).FirstOrDefault();
                                            <input value="@_patt" style="text-align:center;" class="form-control" type="text" placeholder="@item.fName" disabled />

                                        }
                                        else if (item.eName.ToLower() == "ins")
                                        {
                                            InvoiceType foo = (InvoiceType)Enum.Parse(typeof(InvoiceType), item.Value);
                                            <input value="@foo.GetEnumDisplayName()" style="text-align:center;" class="form-control" type="text" placeholder="@item.fName" disabled />

                                        }

                                        else if (item.eName.ToLower() == "tob")
                                        {
                                            CustomerType foo = (CustomerType)Enum.Parse(typeof(CustomerType), item.Value);
                                            <input value="@foo.GetEnumDisplayName()" style="text-align:center;" class="form-control" type="text" placeholder="@item.fName" disabled />

                                        }
                                        else
                                        {
                                            <input @bind-value="item.Value" style="text-align:center;" class="form-control" type="text" placeholder="@item.fName" disabled />

                                        }







                                    }

                                    else
                                    {
                                        <input @bind-value="item.Value" style="text-align:center;" class="form-control" type="text" placeholder="@item.fName" />

                                    }
                                </div>
                            }

                        </div>


                    }

                </form>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="card mb-4">
            <h5 class="card-header">اطلاعات تکمیلی بدنه صورتحساب (کالاها)</h5>
            <div class="card-body">
                @if (invoice?.Bodys != null)
                {
                    <Accordion>
                        @foreach (var item in invoice?.Bodys)
                        {
                            <div class="col-md-12">
                                <div class="card mb-4">
                                    <AccordionItem Title="@item.filds.Where(w=>w.eName=="sstt").Select(s=>s.Value).First()">
                                        <Content>
                                            <div class="row">
                                                @foreach (var itemB in item.filds)
                                                {
                                                    <div class="mb-1 col-md-3">
                                                        @if (itemB.ModeID == 1 && itemB.InputBox != "autofild")
                                                        {
                                                            if (itemB.Des != null && itemB.Des.Count() > 0 && !FullInvoice)
                                                            {
                                                                <Badge style="cursor: pointer;" @onclick="()=>ShowConditions(itemB.Des,itemB.fName)" Color="BadgeColor.Primary" IndicatorType="BadgeIndicatorType.RoundedPill">...</Badge>
                                                                <label style="color:red;" class="form-label">@itemB.fName</label>
                                                            }
                                                            else
                                                            {
                                                                <label style="color:red;" class="form-label">@itemB.fName</label>
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if (itemB.Des != null && itemB.Des.Count() > 0 && !FullInvoice)
                                                            {
                                                                <Badge style="cursor: pointer;" @onclick="()=>ShowConditions(itemB.Des,itemB.fName)" Color="BadgeColor.Primary" IndicatorType="BadgeIndicatorType.RoundedPill">...</Badge>
                                                                <label class="form-label">@itemB.fName</label>
                                                            }
                                                            else
                                                            {
                                                                <label class="form-label">@itemB.fName</label>

                                                            }
                                                        }
                                                        @if (itemB.InputBox == "fromdb")
                                                        {

                                                            <select @bind="itemB.Value" class="form-control" aria-label="Default select example">
                                                                <option value="100" style="color: #b5b5b5; " selected>@itemB.fName...</option>
                                                                @foreach (var itema in itemB.DefVals)
                                                                {
                                                                    if (itema.ID == itemB.Value)
                                                                    {
                                                                        <option value="@itema.ID" selected>@itema.Name</option>
                                                                    }
                                                                    else
                                                                    {
                                                                        <option value="@itema.ID">@itema.Name</option>
                                                                    }
                                                                }
                                                            </select>


                                                        }
                                                        else if (itemB.InputBox == "autofild" || (itemB.eName.ToLower() == "_cfee" && patt != "2"))
                                                        {
                                                            @if (itemB.eName.ToLower() == "mu")
                                                            {

                                                                var mu = units.Where(w => w.ID == Convert.ToInt32(itemB.Value)).Select(s => s.Title).FirstOrDefault();

                                                                <input value="@mu" style="text-align:center;" class="form-control" type="text" placeholder="@itemB.fName" disabled />


                                                            }
                                                            else
                                                            {
                                                                <input @bind-value="itemB.Value" style="text-align:center;" class="form-control" type="text" placeholder="@itemB.fName" disabled />

                                                            }
                                                        }
                                                        else
                                                        {
                                                            <input @bind-value="itemB.Value" style="text-align:center;" class="form-control" type="text" placeholder="@itemB.fName" />

                                                        }




                                                    </div>
                                                }
                                            </div>

                                        </Content>
                                    </AccordionItem>
                                </div>
                            </div>
                        }

                    </Accordion>



                }
            </div>
        </div>
    </div>
</div>

@if (invoice != null)
{
    @* action *@
    <div class="row">
        <div class="col-md-12">
            <div class="mb-2">
                <div class="row">
                    <div class="col-md-6">
                    
                            @if (FullInvoice)
                            {
                                <Button Disabled="SpinnerVisible" Color="ButtonColor.Primary" @onclick="Send">ثبت تغییرات</Button>
                            }
                            else
                            {
                                <Button Disabled="SpinnerVisible" Color="ButtonColor.Primary" @onclick="Send">آماده سازی و ارسال</Button>
                            }

                       
                    </div>

                    <div class="col-md-1">
                        <Spinner Visible="SpinnerVisible" Color="SpinnerColor.Primary" />
                    </div>
                </div>
            </div>
        </div>
    </div>
}


@code {
    public bool SpinnerVisible { get; set; } = false;
    string patt = "";
    private List<IdName<int>>? Patterns = new List<IdName<int>>();
    private List<IdName<int>>? BillTypes = new List<IdName<int>>();
    private List<IdName<int>>? units = new List<IdName<int>>();
    private Modal modal = default!;
    private ConfirmDialog dialog = default!;
    [Parameter] public int? InvoiceID { get; set; }
    List<ToastMessage> messages = new List<ToastMessage>();
    [Inject] protected PreloadService PreloadService { get; set; } = default!;
    public _TaxPayer.Atemplatefield? invoice { get; set; }
    public bool FullInvoice { get; set; } = true;
    // alert
    AlertColor alertColor = AlertColor.Primary;
    IconName alertIconName = IconName.CheckCircleFill;
    bool Hidealert = true;
    string alertMessage = "";

    protected override async Task OnParametersSetAsync()
    {
        SpinnerVisible = true;
        PreloadService.Show(SpinnerColor.Dark);
        Patterns = await fv.GetPatternsbyinp();
        BillTypes = await fv.GetBillTypes();
        units = await fv.GetUnitsbyUnitTaxID();
        SpinnerVisible = false;
        await LoadData();
        PreloadService.Hide();

        if (hc._nav.Uri.ToString().Contains("FullInvoiceItem"))
            FullInvoice = true;
        else FullInvoice = false;
        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,
           };
    public async Task Send()
    {
        SpinnerVisible = true;

        string route = "PreparationInvoiceBeforeSending";
        if (FullInvoice)
            route = "UpdateInvoice";

        var rsp = await hc.Post<_TaxPayer.Atemplatefield>($"TaxPayer/{route}", invoice);
        if (rsp.IsSuccessStatusCode)
        {
            var response = await rsp.Content.ReadFromJsonAsync<bool>();
            if (response)
            {
                if (FullInvoice)
                {
                    ShowMessage(ToastType.Success, "تغییرات با موفقیت انجام شد");
                   await LoadData();
                }

                    else
                    {
                        ShowMessage(ToastType.Light, "در حال ارسال صورتحساب");
                        rsp = await hc.Get($"TaxPayer/SendInvoice/{InvoiceID}");
                        if (rsp.IsSuccessStatusCode)
                        {
                            response = await rsp.Content.ReadFromJsonAsync<bool>();
                            if (response)
                            {
                                hc._nav.NavigateTo($"TaxPayer/{InvoiceID}");
                                // ShowMessage(ToastType.Success, "ارسال با موفقیت انجام شد");
                            }
                            else
                            {
                                ShowMessage(ToastType.Danger, "خطای در ارسال رخ داده");
                            }
                        }
                        else
                        {
                            var request = await rsp.Content.ReadFromJsonAsync<List<string>>();
                            ShowMessage(ToastType.Danger, request[0]);
                        }
                    }

                }
                else
                {
                    ShowMessage(ToastType.Danger, "خطای در آماده سازی اطلاعات رخ داده");
                }
            }
            else
            {
                var request = await rsp.Content.ReadFromJsonAsync<List<string>>();
                ShowMessage(ToastType.Danger, request[0]);
            }
        
        SpinnerVisible = false;
    }
    public async Task<bool> CheckAuth()
    {
        SpinnerVisible = true;
        var rsp = await hc.Get($"TaxPayer/CheckAuth");
        if (rsp.IsSuccessStatusCode)
        {
            var response = await rsp.Content.ReadFromJsonAsync<bool>();
            if (response)
            {
                SpinnerVisible = false;
                return true;
            }
        }
        SpinnerVisible = false;
        return false;
    }
    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 LoadData()
    {
        SpinnerVisible = true;
        var rsp = await hc.Get($"TaxPayer/GetInvoice/{InvoiceID}");
        if (rsp.IsSuccessStatusCode)
        {
            invoice = await rsp.Content.ReadFromJsonAsync<_TaxPayer.Atemplatefield?>();
        }
        else
        {
            var request = await rsp.Content.ReadFromJsonAsync<List<string>>();
            ShowDangerAlert(request[0]);
        }
        SpinnerVisible = false;
    }
    private async Task ShowConditions(string[]? Conditions, string fild)
    {
        if (Conditions != null)
        {
            var parameters = new Dictionary<string, object>();
            parameters.Add("Conditions", Conditions);
            await modal.ShowAsync<CUSComponent.SpecialConditions>(title: $"فیلد {fild}", parameters: parameters);
        }
    }
}
