@page "/loginDialog"
@using MasaBlazorApp3.Pojo.Config;
@using MasaBlazorApp3.Pojo.Vo;
@using MasaBlazorApp3.Util;
@using Microsoft.Extensions.Options;
@using Newtonsoft.Json;
@using log4net;

<style>
    .rz-dialog-content {
    padding: 0 !important;
    }
</style>

<RadzenRow Gap="0" Style="overflow: hidden;width:100%;height:100%">
    <RadzenColumn Size="12" SizeMD="5">
        <RadzenCard class="rz-shadow-0 rz-border-radius-0 rz-text-align-center rz-p-12 align-items-center justify-content-center" Style="height: 100%; background: var(--rz-primary-light) no-repeat 100% 70% fixed url('data:image/svg+xml;base64,[encoded data, 4480 characters]')">
            @if (loginMode == 2)
            {
                <RadzenText TextStyle="TextStyle.H6" class="rz-color-white">操作人：@globalStateService.Operator?.NickName</RadzenText>
                <RadzenText TextStyle="TextStyle.H6" class="rz-color-white">复核人：@globalStateService.Reviewer?.NickName</RadzenText>
            }
        </RadzenCard>
    </RadzenColumn>
    <RadzenColumn Size="12" SizeMD="7">
        <RadzenCard Class="rz-shadow-0 rz-border-radius-0 rz-p-12" Style="width:100%;height:100%">
            <RadzenText TextStyle="TextStyle.H5" TagName="TagName.H2" class="rz-mb-6">
                登录
            </RadzenText>
            <RadzenTemplateForm Data="@loginModel" Submit="@((Pojo.User args) => { Submit(args); })" Style="width:100%;height:100%">
                <div class="rz-form-row">
                    <label class="rz-label" for="username">账号</label>
                    <div class="rz-form-input-wrapper">
                        <!--@onfocusin="@(() => Util.VirtualKeyboardHelper.ShowVirtualKeyboard())"-->
                        <RadzenTextBox id="username" Name="Username" @bind-Value="@loginModel.Username"  Style="width:100%" />
                        <RadzenRequiredValidator Component="Username" Text="请填写用户名" />
                    </div>
                </div>
                <div class="rz-form-row">
                    <label class="rz-label" for="password">密码</label>
                    <div class="rz-form-input-wrapper">
                        <RadzenPassword id="password" Name="Password" @bind-Value="@loginModel.Password" Style="width:100%" />
                        <RadzenRequiredValidator Component="Password" Text="请填写密码" />
                    </div>
                </div>
                <div class="rz-form-row">
                    <label class="rz-label"></label>
                    <div class="rz-form-input-wrapper rz-login-buttons">
                        <RadzenButton Style="background:#255dd4;color:white;width:110px" ButtonType="ButtonType.Submit" Text="登录" />
                        <RadzenButton Style="border-color:#255dd4;width:110px" Variant="Variant.Outlined" Text="取消" Click="@Exit" />

                    </div>
                </div>
            </RadzenTemplateForm>
        </RadzenCard>
    </RadzenColumn>

</RadzenRow>

@code {
    @inject Radzen.DialogService dialogService;

    @inject FingerprintUtil FingerprintUtil;
    @inject PortUtil PortUtil;
    @inject NavigationManager na;
    @inject NotificationService _message
    @inject GlobalStateService globalStateService;
    @inject IUserDao userDao;
    @inject Microsoft.Extensions.Options.IOptions<Pojo.Config.SettingConfig> setting;



    private readonly ILog logger = LogManager.GetLogger(typeof(LoginDialog));

    private int loginMode = 1;
    private bool opFirst = true;



    bool isShow;

    private Pojo.User loginModel = new();

    protected override Task OnInitializedAsync()
    {
        FingerprintUtil.axCZKEM1.OnAttTransactionEx += axCZKEM1_OnAttTransactionEx;

        loginMode = setting.Value.loginMode;
        opFirst = setting.Value.opFirst;

        return base.OnInitializedAsync();
    }

    private void SetUser(Pojo.User user)
    {

        // 判断是否为双人登录模式
        if (loginMode == 2)
        {
            // 判断是否是操作人优先登录
            if (opFirst)
            {
                // 判断操作人是否已经登录，已经登录说明此时为第二人登录
                if (globalStateService.Operator != null)
                {
                    // 判断是否还是操作人的验证
                    if (globalStateService.Operator.Id != user.Id)
                    {
                        FingerprintUtil.axCZKEM1.OnAttTransactionEx -= axCZKEM1_OnAttTransactionEx;
                        globalStateService.Reviewer = user;
                        logger.Info($"双人登录模式：操作人【{globalStateService.Operator.NickName}】复核人【{user.NickName}】登录");
                        PortUtil.mouseClickTime = DateTime.Now;
                        dialogService.Close(true);
                    }
                    else
                    {
                        _message.Notify(
                            new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"验证重复，请使用其他账号", Duration = 3000 }
                        );
                    }
                }
                else
                {
                    // 此时为第一人登录
                    globalStateService.Operator = user;
                    InvokeAsync(StateHasChanged);
                }
            }
            // 操作人为第二人登录
            else
            {
                // 判断复核人是否已经登录，已经登录说明此时为第二人登录
                if (globalStateService.Reviewer != null)
                {
                    // 判断是否还是复核人的验证
                    if (globalStateService.Reviewer.Id != user.Id)
                    {
                        FingerprintUtil.axCZKEM1.OnAttTransactionEx -= axCZKEM1_OnAttTransactionEx;
                        globalStateService.Operator = user;
                        logger.Info($"双人登录模式：操作人【{user.NickName}】复核人【{globalStateService.Reviewer.NickName}】登录");
                        PortUtil.mouseClickTime = DateTime.Now;
                        dialogService.Close(true);
                    }
                    else
                    {
                        _message.Notify(
                            new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"验证重复，请使用其他账号", Duration = 3000 }
                        );
                    }
                }
                else
                {
                    // 此时为第一人登录
                    globalStateService.Reviewer = user;
                    InvokeAsync(StateHasChanged);
                }

            }

        }
        else
        {
            FingerprintUtil.axCZKEM1.OnAttTransactionEx -= axCZKEM1_OnAttTransactionEx;
            globalStateService.Operator = user;
            logger.Info($"单人登录模式：用户【{user.NickName}】登录");
            PortUtil.mouseClickTime = DateTime.Now;
            dialogService.Close(true);
        }
    }



    private void Submit(Pojo.User user)
    {
        Pojo.User u = userDao.GetByUsername(loginModel.Username);
        if (u != null)
        {
            if (Util.MD5.GetMD5Hash(loginModel.Password).ToLower().Equals(u.Password))
            {
                SetUser(u);
                loginModel.Username="";
                loginModel.Password = "";
            }
            else
            {
                _message.Notify(
                    new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"密码错误", Duration = 4000 }
                );
                logger.Info($"用户【{u.NickName}】密码输入错误");

            }

        }
        else
        {
            _message.Notify(
                new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"无此用户", Duration = 4000 }
            );
            logger.Info($"没有用户：【{loginModel.Username}】");
        }
    }

    private void axCZKEM1_OnAttTransactionEx(string sEnrollNumber, int iIsInValid, int iAttState, int iVerifyMethod, int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond, int iWorkCode)
    {

        Pojo.User u = userDao.GetById(Convert.ToInt32(sEnrollNumber));
        if (u != null)
        {
            SetUser(u);
        }
        else
        {
            _message.Notify(
                new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"系统中没有ID为【{sEnrollNumber}】的用户", Duration = 4000 }
            );
            logger.Info($"指纹机验证通过id为【{sEnrollNumber}】，但是华康数据库中无此用户");
        }

    }

    private void Exit()
    {
        if (globalStateService.Operator != null)
        {
            globalStateService.Operator = null;
            globalStateService.Reviewer = null;
        }
        dialogService.Close(false);
    }




}
