@page "/0"
@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 (userI == 1)
            {
                <RadzenText TextStyle="TextStyle.H5" class="rz-color-white">
                    请交班操作人 @FromOperator?.NickName
                    <p>登录验证</p>
                </RadzenText>
            }
            else if (userI == 2)
            {
                <RadzenText TextStyle="TextStyle.H5" class="rz-color-white">
                    请交班复核人 @FromRviewer?.NickName
                    <p>登录验证</p>
                </RadzenText>
            }
            else
            @if (userI == 3)
            {
                <RadzenText TextStyle="TextStyle.H5" class="rz-color-white">
                    请接班操作人 @ToOperator?.NickName
                    <p>登录验证</p>
                </RadzenText>
            }
            else if (userI == 4)
            {
                <RadzenText TextStyle="TextStyle.H5" class="rz-color-white">
                    请接班复核人 @ToReviewer?.NickName
                    <p>登录验证</p>
                </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>
                @if (userI > 2)
                {
                    <div class="rz-form-row">
                        <label class="rz-label" for="remark">备注</label>
                    <div class="rz-form-input-wrapper">
                            <RadzenTextBox id="remark" @bind-Value="@remarks" Style="width:100%" />
                    </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;
    [Parameter] public int userI { get; set; }

    Pojo.User FromOperator = new Pojo.User();
    Pojo.User FromRviewer = new Pojo.User();
    Pojo.User ToOperator = new Pojo.User();
    Pojo.User ToReviewer = new Pojo.User();

    HkcChangeShifts hkcChange = new HkcChangeShifts();
    string remarks = string.Empty;
    bool isShow;

    private Pojo.User loginModel = new();

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

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

        //查询当前值班信息
        hkcChange = userDao.GetOnDuty();
        if (hkcChange != null && !string.IsNullOrEmpty(hkcChange.FromOperator))
        {
            FromOperator = userDao.GetByUsername(hkcChange.FromOperator);
        }
        if (hkcChange != null && string.IsNullOrEmpty(hkcChange.FromRviewer))
        {
            FromRviewer = userDao.GetByUsername(hkcChange.FromRviewer);
        }
        return base.OnInitializedAsync();
    }

    private async Task SetUser(Pojo.User user)
    {
        if (userI == 1)
        {
            if(FromOperator.Id != user.Id)
            {
                _message.Notify(
                          new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"值班操作人有误，请核查当前值班人", Duration = 3000 }
                      );
                return;
            }
            //交班人操作人登录
            if (FromRviewer != null)
            {
                userI = 2;
            }
            else
            {
                userI = 3;
            }

        }
        else if (userI == 2)
        {
            if (FromOperator != null && FromOperator.Id == user.Id)
            {
                _message.Notify(
                           new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"验证重复，请使用其他账号", Duration = 3000 }
                       );
                return;
            }
            else
            {
                if(FromRviewer.Id!=user.Id)
                {
                    _message.Notify(
                           new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"值班审核人有误，请核查当前值班人", Duration = 3000 }
                       );
                    return;
                }
                FromRviewer = user;
                userI = 3;
            }
        }
        else if (userI == 3)
        {
            if (loginMode == 2)
            {
                if (FromOperator.Id == user.Id || (FromRviewer != null && FromRviewer.Id == user.Id))
                {
                    _message.Notify(
                           new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"验证重复，请使用其他账号", Duration = 3000 }
                       );
                    return;
                }
                userI = 4;
                ToOperator = user;
            }
            else
            {
                if (FromOperator.Id == user.Id || (FromRviewer != null && FromRviewer.Id == user.Id))
                {
                    _message.Notify(
                           new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"验证重复，请使用其他账号", Duration = 3000 }
                       );
                    return;
                }
                else
                {
                    ToOperator = user;
                    //保存交接班信息
                    HkcChangeShifts hkcChangeNew = new HkcChangeShifts
                    {
                        FromOperator = ToOperator.Username,
                        optDate = DateTime.Now,
                        ToDate = DateTime.Now,
                        State = "0", //状态为1表示交接班完成
                        MachineId = hkcChange.MachineId,
                        Remarks = remarks
                    };
                    hkcChange.ToOperator = ToOperator.Username;
                    bool bResult = await userDao.UpdateChangeShift(hkcChange, hkcChangeNew);
                    if (bResult)
                    {
                        FingerprintUtil.axCZKEM1.OnAttTransactionEx -= axCZKEM1_OnAttTransactionEx;
                        logger.Info($"交接班完成，交班人{FromOperator.NickName};{FromRviewer?.NickName}，接班人{ToOperator?.NickName};{ToOperator?.NickName}");
                        _message.Notify(
                                    new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "提示", Detail = $"交接班完成", Duration = 3000 }
                                );
                        dialogService.Close(true);
                    }
                    else
                    {
                        _message.Notify(
                          new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = "交接班保存数据失败", Duration = 3000 }
                      );
                    }
                }
            }
        }
        else if (userI == 4)
        {
            if (FromOperator.Id == user.Id || (FromRviewer != null && FromRviewer.Id == user.Id) || (ToOperator != null && ToOperator.Id == user.Id))
            {
                _message.Notify(
                         new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"验证重复，请使用其他账号", Duration = 3000 }
                     );
                return;
            }
            ToReviewer = user;
            hkcChange.ToReviewer = ToReviewer?.Username;
            //保存交接班信息
            HkcChangeShifts hkcChangeNew = new HkcChangeShifts
            {
                FromOperator = ToOperator.Username,
                FromRviewer = ToReviewer?.Username,
                optDate = DateTime.Now,
                State = "0", //状态为1表示交接班完成
                MachineId = hkcChange.MachineId,
                Remarks = remarks
            };
            bool bResult = await userDao.UpdateChangeShift(hkcChange, hkcChangeNew);
            if (bResult)
            {
                FingerprintUtil.axCZKEM1.OnAttTransactionEx -= axCZKEM1_OnAttTransactionEx;
                logger.Info($"交接班完成，交班人{FromOperator.NickName};{FromRviewer?.NickName}，接班人{ToOperator?.NickName};{ToReviewer?.NickName}");
                _message.Notify(
                            new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "提示", Detail = $"交接班完成", Duration = 3000 }
                        );
                dialogService.Close(true);
            }
            else
            {
                _message.Notify(
                           new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = "交接班保存数据失败", Duration = 3000 }
                       );
            }
        }
    }



    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);
            InvokeAsync(StateHasChanged);
        }
        else
        {
            _message.Notify(
                new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"系统中没有ID为【{sEnrollNumber}】的用户", Duration = 4000 }
            );
            logger.Info($"指纹机验证通过id为【{sEnrollNumber}】，但是华康数据库中无此用户");
        }

    }

    private void Exit()
    {
        dialogService.Close(false);
    }




}
