@using MasaBlazorApp3.Util
@using log4net
<RadzenStack>

    @* <RadzenTemplateForm Submit="@((int BDQuantity) => { ConfirmOK(BDQuantity); })" Style="width:100%;height:100%"> *@
    <div class="rz-form-row">
        <div class="rz-form-input-wrapper">
            <!--@onfocusin="@(() => Util.VirtualKeyboardHelper.ShowVirtualKeyboard())"-->
            @if (channelStockInfo.Quantity>0)
            {
                <RadzenText TextStyle="TextStyle.Body1" Style="color: var(--rz-text-tertiary-color); align-content:center; text-align:center; font-size:medium;">库位库存不为零，请取出药品后点击【清空】按钮，清空完成后输入标定数量并放入对应数量药品并根据下一步提示操作</RadzenText>
            }
            else
            {
                <RadzenText TextStyle="TextStyle.Body1" Style="color: var(--rz-text-tertiary-color); align-content:center; text-align:center; font-size:medium;">正在清零，清零完成后输入标定数量并放入对应数量药品后点击【标定】按钮</RadzenText>
            }
            <RadzenTextBox id="BDQuantity" Name="BDQuantity" Value="10" Style="width:100%" />
            <RadzenRequiredValidator Component="BDQuantity" Text="请填写标定数量" />
        </div>
    </div>
    @* </RadzenTemplateForm> *@
    <RadzenStack Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.Center" Gap="0.5rem">

        <RadzenButton Click="@Clear" ButtonStyle="ButtonStyle.Warning" Variant="Variant.Flat" Disabled="@(channelStockInfo.Quantity<=0)" Text="清空" Style="width: 120px" />

        <RadzenButton Click="ConfirmOK" ButtonStyle="ButtonStyle.Success" IsBusy="@(status==2)" BusyText="正在标定。。。" Variant="Variant.Flat" Text="标定" Disabled=@(this.status<=0||this.status==2||iClearFinish>0) Style="width: 120px" />

        <RadzenButton Click="@CancelClick" Variant="Variant.Flat" Text="取消" Style="width: 120px" />

    </RadzenStack>
</RadzenStack>

@code {
    @inject Radzen.DialogService dialogService;
    @inject NotificationService _message
    @inject PortUtil PortUtil;
    [Parameter] public ChannelStock channelStockInfo { get; set; }

    PromiseUtil<object> promiseUtil = new PromiseUtil<object>();
    private readonly ILog logger = LogManager.GetLogger(typeof(BiaoDingDialog));

    int BDQuantity = 10;

    int status = 0;
    int iClear = 0;
    int iBiaoDing = 0;
    int iClearFinish = 1;
    protected override async Task OnInitializedAsync()
    {
        if(channelStockInfo!=null&&channelStockInfo.Quantity<=0)
        {
            //库存为零，直接进行清空操作
            await Clear();
        }
        base.OnInitializedAsync();
    }
    //清空按钮
    async Task Clear()
    {
        PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
        PortUtil.SpeakAsync($"正在清空，请稍等");

        this.status = 1;
        int i = 0;
        await promiseUtil.taskAsyncLoop(200, null, async (data, next, stop) =>
        {
            i++;
            if (this.status == 0)
            {
                iClear = 0;
                stop();
            }
            else
            {
                try
                {
                    if (iClear == 0)
                    {
                        logger.Info($"清零操作{i}");
                        //无库存发送计数清零指令
                        await PortUtil.ClearCount(channelStockInfo.DrawerNo, channelStockInfo.ColNo);
                        iClear += 1;
                        next();
                    }
                    else
                    {
                        logger.Info($"查数操作{i}");
                        //发查数指令
                        PortUtil.DrawerNo = channelStockInfo.DrawerNo;
                        PortUtil.Operate = true;
                        int stock = await PortUtil.CheckQuantityForBiaoDing(channelStockInfo.ColNo);
                        if (stock != 0)
                        {
                            _message.Notify(
                                                new NotificationMessage
                                                    { Severity = NotificationSeverity.Success, Summary = "提示", Detail = "清空操作成功", Duration = 3000 }
                                            );

                            PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
                            PortUtil.SpeakAsync("清空完成，请放入10个药品，放好后点击标定按钮");
                            iClear = 0;
                            iClearFinish = 0;
                            stop();
                        }
                        else
                        {
                            next();
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Info($"清空操作异常");
                    next();
                }
            }

        });
    }
    //标定按钮
    async Task ConfirmOK()
    {
        if (BDQuantity > 0)
        {
            try
            {
                status = 2;
                PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
                PortUtil.SpeakAsync("正在标定，请稍等");
                //提示输入标定数量，发26指令
                await PortUtil.SetNumCount(channelStockInfo.DrawerNo, channelStockInfo.ColNo, BDQuantity);
                await Task.Delay(200);
                int i = 1;
                await promiseUtil.taskAsyncLoop(200, null, async (data, next, stop) =>
                {
                    if(status==0)
                    {
                        stop();
                    }
                    if (status == 2)
                    {
                        //查数量
                        int quantity = await PortUtil.CheckQuantityForBiaoDing(channelStockInfo.ColNo);
                        if (quantity == BDQuantity)
                        {
                            //标定完成
                            status = 0; 
                            _message.Notify(
                                                new NotificationMessage
                                                    { Severity = NotificationSeverity.Success, Summary = "提示", Detail = "标定成功", Duration = 3000 }
                                            );

                            PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
                            PortUtil.SpeakAsync("标定完成，请取出药品");
                            status = 0;
                            i = 0;
                            stop();
                            // 关闭弹窗
                            dialogService.Close(true);
                        }
                        else
                        {
                            i++;
                            logger.Info($"标定数量不一致{quantity}-{BDQuantity},标定次数{i}");
                            next();
                        }

                    }
                });
            }
            catch (Exception ex)
            {
                logger.Error($"标定异常{ex.Message}");
                _message.Notify(
                                    new NotificationMessage
                                        { Severity = NotificationSeverity.Error, Summary = "提示", Detail = "标定异常", Duration = 3000 }
                                );
            }
        }
        else
        {
            _message.Notify(
                    new NotificationMessage
                        { Severity = NotificationSeverity.Error, Summary = "提示", Detail = "请输入标定数量", Duration = 3000 });
        }
    }
    // 取消
    async Task CancelClick()
    {
        status = 0;
        // 关闭弹窗
        dialogService.Close(true);
    }
}