@page "/account/login"
@layout EmptyLayout
@inject ILogger<Login> Logger


<PageTitle>登录</PageTitle>

@if (!dataLoaded)
{
    <Spin Spinning="_isLoading" />
}
else
{
    <Flex Style="height:100vh" Justify="FlexJustify.Center" Align="FlexAlign.Center" Direction="FlexDirection.Vertical">
        <GridRow Justify="RowJustify.Center" Class="">
            <GridCol>
                <Card>
                    <Form @ref="form" Model="@login" OnFinish="LoginAsync">
                        <FluentValidationValidator />
                        <FormItem>
                            <AntDesign.Input Placeholder="登录账号" Size="InputSize.Large" @bind-Value="@login.Account">
                                <Prefix><Icon Type="user" /></Prefix>
                            </AntDesign.Input>
                        </FormItem>
                        <FormItem>
                            <AntDesign.Input Placeholder="登录密码" Size="InputSize.Large" @bind-Value="@login.Password" Type="InputType.Password">
                                <Prefix><Icon Type="lock" /></Prefix>
                            </AntDesign.Input>
                        </FormItem>
                        <FormItem>
                            <a style="float: left;">
                                忘记密码
                            </a>
                            <a style="float: right;">
                                <NavLink href="/register">马上注册</NavLink>
                            </a>
                        </FormItem>
                        <FormItem>
                            <Button Type="ButtonType.Primary" HtmlType="submit" Class="submit" Size="ButtonSize.Large" Block>登录</Button>
                        </FormItem>
                    </Form>
                </Card>
            </GridCol>
        </GridRow>
        <GridRow Style="padding-top:40px">
            <span style="font-size:12px;padding-right:3px;">Copyright © 2025-@DateTime.Now.Year Atomx.cn All rights reserved.</span>
            <span style="font-size:12px">runing as @handler</span>
        </GridRow>
    </Flex>
}


@code {
    string handler = "Server";

    [Parameter]
    [SupplyParameterFromQuery(Name = "ReturnUrl")]
    public string? ReturnUrl { get; set; }

    [SupplyParameterFromForm]
    public LoginModel login { get; set; } = new();
    private Form<LoginModel> form = null!;

    bool dataLoaded = false;

    string message { get; set; } = string.Empty;

    private bool _isLoading = false;


    protected override void OnInitialized()
    {
        if (OperatingSystem.IsBrowser())
        {
            handler = "Wasm";
        }
        else
        {
            handler = "Server";
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var authState = await AuthStateProvider.GetAuthenticationStateAsync();
            if (authState.User.Identity != null)
            {
                if (authState.User.Identity.IsAuthenticated)
                {
                    Navigation.NavigateTo(ReturnUrl ?? "/");
                }
            }
        }
        if (!dataLoaded)
        {
            dataLoaded = true;
            StateHasChanged();
        }
    }

    private async Task LoginAsync()
    {
        if (form.Validate())
        {
            var api = "/api/sign/in";
            var result = await HttpService.Post<ApiResult<string>>(api, login);
            if (result.Success)
            {
                Console.WriteLine("请求api成功");
                if (!string.IsNullOrEmpty(result.Data))
                {
                    await localStorage.SetItemAsStringAsync(StorageKeys.JWTTokenKeyName, result.Data);
                    await localStorage.SetItemAsStringAsync("refreshToken", result.Data);
                    var authState = (AuthStateProvider as PersistentAuthenticationStateProvider);
                    if (authState != null)
                    {
                        authState.UpdateAuthenticationState(result.Data);
                    }
                    Logger.LogInformation($"登录成功跳转目标,{ReturnUrl}");
                    Navigation.NavigateTo(ReturnUrl ?? "/");
                }
            }
            else
            {
                ModalService.Error(new ConfirmOptions() { Title = "提示", Content = result.Message });
            }
        }

    }

    private async Task OnPasswordKeyDown(KeyboardEventArgs value)
    {
        if (value.Key == "Enter")
        {
            await LoginAsync();
        }
    }
}