@page "/Sign-in"
@page "/Sign-in/{from}"
@using Front.Services
@using Shared.DTOs
@inject ILocalStorageService Storage;
@inject UserAuthenticationDTO userinfo
@inject localService localserv;
@inject HttpClient _hc
@inject NavigationManager nav
<PageTitle>ورود</PageTitle>
<main>

    <!-- tp-banner-area-start -->
    <div class="signin-banner-area signin-banner-main-wrap d-flex align-items-center">
        <div class="signin-banner-left-box signin-banner-bg p-relative">
            <div class="signin-banner-bottom-shape">
                <img src="img/login/login-shape-1.png" alt="">
            </div>
            <div class="signin-banner-left-wrap">
                <div class="signin-banner-title-box mb-100">
                    <br />
                    <h4 class="signin-banner-title" style="color:black">
                        برای استفاده از بخش ها <br /> وارد شوید
                    </h4>
                </div>
                <div class="signin-banner-img-box position-relative">
                    <div class="signin-banner-img signin-img-1 d-none d-md-block z-index-3">
                        <img src="img/login/login-2.png" alt="">
                    </div>
                    <div class="signin-banner-img signin-img-2 d-none d-md-block">
                        <img src="img/login/login-1.png" alt="">
                    </div>
                    <div class="signin-banner-img signin-img-3 d-none d-md-block z-index-5">
                        <img src="img/login/login-3.png" alt="">
                    </div>
                    <div class="signin-banner-img signin-img-4 d-none d-sm-block">
                        <img src="img/login/login-4.png" alt="">
                    </div>
                </div>
            </div>
        </div>
        <div class="signin-banner-from d-flex justify-content-center align-items-center">
            <div class="signin-banner-from-wrap">
                <div class="signin-banner-title-box">
                    <h4 class="signin-banner-from-title">ورود به سیستم</h4>
                </div>

                <div class="signin-banner-from-box">
                    <EditForm Model="Model" OnValidSubmit="OnLoginClick">
                        <DataAnnotationsValidator />
                        <div class="postbox__comment-input mb-35">
                            <ValidationMessage For="()=>Model.Username" />
                            <ValidationMessage For="()=>Model.Password" />

                        </div>
                        <div class="row">
                            <div class="col-12">
                                <div class="postbox__comment-input mb-30">
                                    <InputText @bind-Value="Model.Username" id="Username" type="text" class="inputText" required="" />

                                    <span class="floating-label">نام کاربری(موبایل)</span>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="postbox__comment-input mb-30">
                                    <InputText @bind-Value="Model.Password" id="Password" class="inputText password" type="password" required="" />
                                    <span class="floating-label">گذرواژه</span>
                                    <span id="click" class="eye-btn">
                                        <span class="eye-on">
                                            <svg width="20" height="17" viewBox="0 0 20 17" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path opacity="0.5" d="M2.1474 11.1661C1.38247 10.1723 1 9.67544 1 8.2C1 6.72456 1.38247 6.22767 2.1474 5.2339C3.67477 3.2496 6.2363 1 10 1C13.7637 1 16.3252 3.2496 17.8526 5.2339C18.6175 6.22767 19 6.72456 19 8.2C19 9.67544 18.6175 10.1723 17.8526 11.1661C16.3252 13.1504 13.7637 15.4 10 15.4C6.2363 15.4 3.67477 13.1504 2.1474 11.1661Z" stroke="#1C274C" stroke-width="1.5"></path>
                                                <path d="M12.6969 8.2C12.6969 9.69117 11.488 10.9 9.99687 10.9C8.50571 10.9 7.29688 9.69117 7.29688 8.2C7.29688 6.70883 8.50571 5.5 9.99687 5.5C11.488 5.5 12.6969 6.70883 12.6969 8.2Z" stroke="#1C274C" stroke-width="1.5"></path>
                                            </svg>
                                        </span>
                                        <span class="eye-off">
                                            <svg width="18" height="18" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <g clip-path="url(#clip0_2547_24206)">
                                                    <path d="M18.813 18.9113C17.1036 20.2143 15.0222 20.9362 12.873 20.9713C5.87305 20.9713 1.87305 12.9713 1.87305 12.9713C3.11694 10.6532 4.84218 8.62795 6.93305 7.03134M10.773 5.21134C11.4614 5.05022 12.1661 4.96968 12.873 4.97134C19.873 4.97134 23.873 12.9713 23.873 12.9713C23.266 14.1069 22.5421 15.1761 21.713 16.1613M14.993 15.0913C14.7184 15.3861 14.3872 15.6225 14.0192 15.7865C13.6512 15.9504 13.2539 16.0386 12.8511 16.0457C12.4483 16.0528 12.0482 15.9787 11.6747 15.8278C11.3011 15.6769 10.9618 15.4524 10.6769 15.1675C10.392 14.8826 10.1674 14.5433 10.0166 14.1697C9.86567 13.7962 9.79157 13.3961 9.79868 12.9932C9.80579 12.5904 9.89396 12.1932 10.0579 11.8252C10.2219 11.4572 10.4583 11.126 10.753 10.8513" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
                                                    <path d="M1.87305 1.97131L23.873 23.9713" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
                                                </g>
                                                <defs>
                                                    <clipPath id="clip0_2547_24206">
                                                        <rect width="24" height="24" fill="white" transform="translate(0.873047 0.971313)"></rect>
                                                    </clipPath>
                                                </defs>
                                            </svg>
                                        </span>
                                    </span>
                                </div>
                            </div>
                        </div>

                        <div class="signin-banner-form-remember">
                            <div class="row">
                                <div class="col-6">
                                    <div class="postbox__comment-agree">
                                        <div class="form-check">
                                            <InputCheckbox @bind-Value="Model.Remember" id="Remember" class="form-check-input" type="checkbox" />
                                            <label class="form-check-label" for="flexCheckDefault">
                                                مرا به یاد داشته باش
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="postbox__forget text-end">
                                        <a onclick="@ForgetPass">رمز عبور را فراموش کرده اید؟</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="signin-banner-from-btn mb-20">
                            <button class="signin-btn ">ورود</button>
                        </div>
                    </EditForm>
                    <div class="row">
                        <Alert hidden="@Hidealert" Color="@alertColor" Dismissable="false">
                            <Icon Name="@alertIconName" class="me-2"></Icon>
                            @alertMessage
                            @if (showbtn)
                            {
                                <Button Color="ButtonColor.Primary" @onclick="EndForm">اتمام عملیات</Button>

                            }
                        </Alert>


                    </div>
                    <div class="signin-banner-from-register">
                        <NavLink href="Register">اکانت ندارید؟ <span>ثبت نام</span></NavLink>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- tp-banner-area-end -->

</main>

@code {
    [Parameter]
    public string from { get; set; } = "";
    bool showbtn = false;
    [SupplyParameterFromForm]
    public Authentication? Model { get; set; }
    // alert
    AlertColor alertColor = AlertColor.Primary;
    IconName alertIconName = IconName.CheckCircleFill;
    bool Hidealert = true;
    string alertMessage = "";
    protected override async Task OnParametersSetAsync()
    {
        if (from == "VerificationRegister")
        {
            ShowSuccessAlert("ثبت نام شما با موفقیت انجام شد");
        }
        else if (from == "VerificationFrogetPass")
        {
            ShowSuccessAlert("تغییر کلمه عبور با موفقیت انجام شد");
        }
        else if (from == "unon")
        {
            ShowSuccessAlert("برای استفاده از برنامه لطفا مجدد وارد شود");
        }
        else if (from == "changePass")
        {
            ShowSuccessAlert("کلمه عبور با موفقیت تغییر کرد");
            
        }
        await base.OnParametersSetAsync();
    }
    protected override async Task OnInitializedAsync()
    {

        if (await localserv.OnlineUser())
            nav.NavigateTo("/Panel");

        Model ??= new();
        await base.OnInitializedAsync();
    }
}
@functions {
    private void ShowDangerAlert(string msg)
    {
        showbtn = true;
        Hidealert = false;
        alertColor = AlertColor.Danger;
        alertIconName = IconName.ExclamationTriangleFill;
        alertMessage = msg;
    }
    private void ShowSuccessAlert(string msg)
    {
        showbtn = false;
        Hidealert = false;
        alertColor = AlertColor.Success;
        alertIconName = IconName.CheckCircleFill;
        alertMessage = msg;
    }
    private async Task EndForm() => nav.NavigateTo("/");
    private async Task ForgetPass()
    {
        if (string.IsNullOrEmpty(Model.Username))
        {
            ShowDangerAlert("لطفا نام کابری(موبایل) خود را وارد نمایید");
        }
        else if (string.IsNullOrEmpty(Model.Password))
        {
            ShowDangerAlert("لطفا کلمه عبور جدید را وارد نمایید");
        }
        else
        {
            var request = await _hc.PostAsJsonAsync("Base/ForgetPassWord", new ForgetPasswordItem
            {
                    Username = Model.Username,
                    PassWord = Model.Password
            });
            if (request.IsSuccessStatusCode)
            {
                var VerificationID = await request.Content.ReadFromJsonAsync<int>();
                nav.NavigateTo($"Verification/{VerificationID}");
            }
            else
            {
                var error = await request.Content.ReadFromJsonAsync<List<string>>();
                ShowDangerAlert(error[0]);

            }
        }
    }

    private async Task OnLoginClick()
    {
        _hc.DefaultRequestHeaders.Clear();
        var request = await _hc.PostAsJsonAsync("User/authenticate", Model);
        if (request.IsSuccessStatusCode)
        {
            var userinfomodel = await request.Content.ReadFromJsonAsync<UserAuthenticationDTO>();

            _hc.DefaultRequestHeaders.Clear();

            _hc.DefaultRequestHeaders.Add("Authorization",
                $"Bearer {userinfomodel?.Token}");

           if (Model.Remember)
               Storage.SetItem("token", userinfomodel?.Token);

            userinfo.Token = userinfomodel?.Token;
            userinfo.Company = userinfomodel?.Company;
            userinfo.FullName = userinfomodel.FullName;
            userinfo.Photo = userinfomodel.Photo;
            userinfo.exitDate = userinfomodel.exitDate;
            userinfo.enterDate = userinfomodel.enterDate;
            userinfo.UserName = userinfomodel.UserName;

            nav.NavigateTo("/Panel");
        }
        else if (request.StatusCode == System.Net.HttpStatusCode.NotFound)
            ShowDangerAlert("کاربری با این مشخصات یافت نشد");

        else ShowDangerAlert("خطای سیستمی");

    }
}