@using MasaBlazorApp3.Pojo.Config
@using MasaBlazorApp3.Util
@using MasaBlazorApp3.Pojo.Vo;
@using Microsoft.Extensions.Options
@using log4net;

<RadzenStack>

    <div Style="width:100%;height:70vh;overflow:auto">

        @* <RadzenListBox AllowClear="true" @bind-Value=@listBoxSelectedcsList Style="width:50vw;overflow:auto" AllowFiltering="false" 
                       Data=@csList>
            <Template Context="contextDate">
                <RadzenStack Orientation="Orientation.Horizontal">
                    <RadzenText Style="width:20vw;text-align:left">@contextDate.Drug.DrugName</RadzenText>
                    <RadzenText Style="width:10vw">@contextDate.ManuNo</RadzenText>
                    <RadzenStack Gap="10" Style="text-align:right">
                        <div style="text-align: center;">
                            @if (contextDate.ReturnDrawerChanneStock != null && contextDate.ReturnDrawerChanneStock.ReturnQuantity>0)
                            {
                                <div style="text-align: center;">
                                    还药库位【@contextDate.ReturnDrawerChanneStock?.DrawerNo】还药数【contextDate.ReturnDrawerChanneStock?.ReturnQuantity】< br />
                                </div>
                            }
                            @if (contextDate.OrderList.fore > 0)
                            {
                                <div style="text-align: center;">
                                    空瓶库位【@contextDate.EmptyStock】空瓶数【@contextDate.EmptyQuantity】< br />
                                </div>
                            }
                        </div>
                    </RadzenStack>
                    <RadzenStack Gap="10" Style="text-align:right">
                        <div style="text-align: center;">
                            基数【@contextDate.BaseQuantity】<br />
                            库存数【@contextDate.Quantity】<br />
                            用药数【@contextDate.UseQuantity】<br />
                            处方数【@contextDate.OrderQuantity】<br />
                            空瓶数【@contextDate.EmptyQuantity】<br />
                        </div>
                    </RadzenStack>
                </RadzenStack>
            </Template>
        </RadzenListBox> *@

        <RadzenListBox AllowClear="true" @bind-Value=@listBoxSelectedcsList Style="width:100%;overflow:auto" AllowFiltering="false" TValue="ChannelStock"
        Data=@csList>
            <Template>
                <RadzenStack Orientation="Orientation.Horizontal">
                    <RadzenText Style="width:20vw;text-align:left">@((context as ChannelStock).Drug.ToString())</RadzenText>
                    <RadzenText Style="width:10vw">@((context as ChannelStock).ManuNo)</RadzenText>
                    <RadzenStack Gap="10" Style="text-align:right">
                        <div style="text-align: center;">
                            @if (((context as ChannelStock).DrawerChanneStockList) != null && ((context as ChannelStock).DrawerChanneStockList.Count) > 0)
                            {
                                for (int i = 0; i < (context as ChannelStock).DrawerChanneStockList.Count; i++)
                                {
                                    <div style="text-align: center;">
                                        还药品库位【@((context as ChannelStock).DrawerChanneStockList[i].Location)】还药数【@((context as ChannelStock).DrawerChanneStockList[i].ReturnQuantity)】
                                    </div>
                                }
                            }
                            @if ((context as ChannelStock).EmptyQuantity > 0)
                            {
                                <div style="text-align: center;">
                                    还空瓶库位【@((context as ChannelStock).EmptyStock.Location)】空瓶数【@((context as ChannelStock).EmptyStock.ReturnQuantity)】
                                </div>
                            }
                        </div>
                    </RadzenStack>
                    <RadzenStack Gap="10" Style="text-align:right">
                        <div style="text-align: center;">
                            基数【@((context as ChannelStock).BaseQuantity)】<br />
                            @* 总库存【@((context as ChannelStock).TotalQuantity)】<br /> *@
                            库存数【@((context as ChannelStock).Quantity)】<br />
                            用药数【@((context as ChannelStock).UseQuantity)】<br />
                            处方数【@((context as ChannelStock).OrderQuantity)】<br />
                            空瓶数【@((context as ChannelStock).EmptyQuantity)】<br />
                        </div>
                    </RadzenStack>
                </RadzenStack>
            </Template>
        </RadzenListBox>
    </div>


    <RadzenStack Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.Center" Gap="0.5rem">
        @* <RadzenButton Click="@ConfirmOK" ButtonStyle="ButtonStyle.Success" Variant="Variant.Flat" Text="归还" Style="width: 120px" />

        <RadzenButton Click="@((args) => dialogService.Close(false))" Variant="Variant.Flat" Text="取消" Style="width: 120px" /> *@
        @if (status < 2)
        {
            <RadzenButton Click="@OpenDrawer" IsBusy="status > 0" BusyText="归还中。。。" ButtonStyle="ButtonStyle.Warning" Variant="Variant.Flat" Text="归还" Style="width: 120px" />
        }
        @if (status == 2)
        {
            <RadzenButton Click="@TakeFinish" ButtonStyle="ButtonStyle.Success" Variant="Variant.Flat" Text="完成" Style="width: 120px" />
        }
        @if (status <= 2)
        {
            <RadzenButton Click="@Cancel" Variant="Variant.Flat" Text="取消" Style="width: 120px" />
        }

    </RadzenStack>
</RadzenStack>

@code {
    @inject Radzen.DialogService dialogService;
    @inject IOptions<DrawerConfig> setting;
    @inject PortUtil PortUtil;
    @inject NotificationService _message;
    @inject IOrderInfoDao orderInfoDao;
    [Parameter] public IList<ChannelStock> csList { get; set; }
    List<OrderDetail> orderDetailList = new();
    ChannelStock listBoxSelectedcsList = new();
    private readonly ILog logger = LogManager.GetLogger(typeof(OrderDetailDialog));
    int status;

    List<OrderTakeVo> data = new();
    //计数取药数量
    int[] WeightFinnalQuantity { get; set; } = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    // //取药数量小于库存
    // tempData.Add(new OrderTakeVo()
    // {
    //     Drug = detail.Drug,
    //                             OrderDetail = detail,
    //                             ChannelStock = stock,
    //                             StockQuantity = total,
    //                             Quantity = Quantity,
    //                         });
    protected override async Task OnInitializedAsync()
    {
        for (int i = 0; i < csList.Count; i++)
        {
            if (csList[i].EmptyStock != null && csList[i].EmptyStock.ReturnQuantity > 0)
            {
                data.Add(new OrderTakeVo()
                    {
                        ChannelStock = csList[i].EmptyStock
                    });
            }
            if (csList[i].DrawerChanneStockList != null && csList[i].DrawerChanneStockList.Count > 0)
            {
                for (int j = 0; j < csList[i].DrawerChanneStockList.Count; j++)
                {
                    data.Add(new OrderTakeVo()
                        {
                            ChannelStock = csList[i].DrawerChanneStockList[j]
                        });
                }
            }
        }
        base.OnInitializedAsync();
    }
    // async Task ConfirmOK()
    // {
    //     // 关闭弹窗
    //     dialogService.Close(true);
    // }
    async Task OpenDrawer()
    {
        this.status = 1;
        PortUtil.PowerOn();
        await Task.Delay(200);
        // 解析需要打开的抽屉列表
        List<OrderTakeVo> drawerNos = this.data.GroupBy(it => it.ChannelStock.DrawerNo).Select(it => it.First()).ToList();

        // 根据抽屉类型来决定打开前是否需要查询数量
        var promiseUtil = new PromiseUtil<int>();

        await promiseUtil.taskAsyncLoop(500, 0, async (options, next, stop) =>
        {
            var orderTakeVo = drawerNos[options._data];
            var drawerNo = orderTakeVo.ChannelStock.DrawerNo;
            var drawerType = orderTakeVo.ChannelStock.DrawerType;
            try
            {
                if (this.status == 0)
                {
                    stop();
                }
                // 开启抽屉
                else if (this.status == 1)
                {
                    if (orderTakeVo.Status == 0)
                    {
                        // 判断是否为单支抽屉
                        if (setting.Value.single.Contains(drawerNo))
                        {
                            byte[] quantity = await PortUtil.CheckQuantityByDrawer(drawerNo);
                            orderTakeVo.BeforeQuantity = quantity.Select(it => Convert.ToInt32(it)).ToArray().Skip(3).Take(9).ToArray();
                            logger.Info($"单支抽屉，开抽屉前检测数量【{string.Join(",", orderTakeVo.BeforeQuantity)}】");

                            await PortUtil.HasLightOnByCol(drawerNo, data.Where(ot => ot.ChannelStock.DrawerNo == drawerNo).Select(ot => ot.ChannelStock.ColNo).ToArray());
                        }
                        var b = await PortUtil.OpenDrawerStatus(drawerNo);
                        if (b)
                        {
                            PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
                            if (drawerType==1)
                            {
                                PortUtil.SpeakAsync($"{drawerNo}号抽屉已经打开，请，环药");
                            }
                            else
                            {
                                PortUtil.SpeakAsync($"{drawerNo}号抽屉已经打开，请，环空瓶");
                            }
                            orderTakeVo.Status = 1;
                            next();
                        }
                        else
                        {
                            _message.Notify(
                            new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"抽屉【{drawerNo}】打开失败，请检测硬件", Duration = 4000 }
                        );
                            logger.Info($"抽屉打开失败");
                            PortUtil.PowerOff();
                            RestData();
                            stop();
                        }
                    }
                    // 检测状态
                    else if (orderTakeVo.Status == 1)
                    {
                        // 查询抽屉是否为关闭状态
                        var b = await PortUtil.CheckDrawerStatus2(drawerNo);
                        // 关闭则改变状态并终止循环
                        if (b)
                        {

                            data.ForEach(cl =>
                            {
                                if (cl.ChannelStock.DrawerNo == drawerNo)
                                {
                                    cl.GetQuantity = cl.Quantity;

                                }
                            });
                            orderTakeVo.Status = 2;
                            PortUtil.PowerOff();
                            if (options._data == drawerNos.Count - 1)
                            {
                                PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
                                PortUtil.SpeakAsync($"抽屉关闭，请，点击完成按钮进行确认");
                                this.status = 2;
                                string alertMessage = string.Empty;
                                //检查是否称重抽屉，核对实际取出数量是否与应取数量一致，不一致则弹出提示
                                for (int i = 0; i < data.Count; i++)
                                {

                                    if (data[i].ChannelStock.BoardType.ToString().Contains("2"))
                                    {
                                        byte[] quantity = await PortUtil.CheckQuantityByDrawer(drawerNo);
                                        orderTakeVo.AfterQuantity = quantity.Select(it => Convert.ToInt32(it)).ToArray().Skip(3).Take(9).ToArray();
                                        logger.Info($"单支抽屉，关抽屉后检测数量【{string.Join(",", orderTakeVo.AfterQuantity)}】");
                                        WeightFinnalQuantity[data[i].ChannelStock.ColNo - 1] = orderTakeVo.BeforeQuantity[data[i].ChannelStock.ColNo - 1] - orderTakeVo.AfterQuantity[data[i].ChannelStock.ColNo - 1];
                                        if (data[i].Quantity != WeightFinnalQuantity[data[i].ChannelStock.ColNo - 1])
                                        {
                                            alertMessage += $"{data[i].Drug.DrugName}应取数量【{orderTakeVo.Quantity}】,实际取出数量【{WeightFinnalQuantity[data[i].ChannelStock.ColNo - 1]}】";
                                        }
                                    }
                                }
                                if (!string.IsNullOrEmpty(alertMessage))
                                {
                                    //弹出确认对话框
                                    alertMessage += "应取数与实际取出数不一致确认要保存吗？";
                                    //弹出确认提示框
                                    var confirm = await dialogService.OpenAsync<ConfirmDialog>(
                                          $"保存确认",
                                          new Dictionary<string, object>() { { "confirmInfo", alertMessage } },
                                          new DialogOptions() { Width = "45vw", Resizable = true, Draggable = true, ShowClose = false });
                                    logger.Info(alertMessage);
                                    if (!confirm)
                                    {
                                        RestData();
                                        logger.Info("取消保存");
                                        // 关闭弹窗
                                        dialogService.Close(false);
                                    }
                                }
                                stop();
                            }
                            else
                            {
                                options._data += 1;
                                next();
                            }
                        }
                        else
                        {
                            next(); // continue iteration
                        }
                    }


                }

            }
            catch (Exception e)
            {
                RestData();
                logger.Info($"处方取药发生错误，{e.Message}");
                _message.Notify(
                new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"发生错误，{e.Message}", Duration = 4000 }
            );
                if (setting.Value.single.Contains(drawerNo))
                {
                    PortUtil.PowerOff();
                }
                stop();
            }
        });
        PortUtil.PowerOff();
    }

    void RestData()
    {
        PortUtil.PowerOff();
        PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
        this.status = 0;
        data.ForEach(it =>
        {
            it.Status = 0;
            it.BeforeQuantity = new int[9];
            it.AfterQuantity = new int[9];
        });
        this.WeightFinnalQuantity = new int[9];
    }
    void Cancel()
    {
        RestData();
        // 关闭弹窗
        dialogService.Close(false);
    }
    async Task TakeFinish()
    {

        // 保存账册、操作记录
        bool bResult = await orderInfoDao.CheckOrderInfoByChannelStock(csList.ToList(), null);
        if (bResult)
        {
            _message.Notify(
                            new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "提示", Detail = $"处方已核对完成", Duration = 4000 }
                        );
            // 关闭弹窗
            dialogService.Close(true);
        }
        else
        {
            _message.Notify(
                          new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"处方核对失败", Duration = 4000 }
                   );
        }
        //重置状态
        this.RestData();
    }

}
