@page "/return/drug/{records}"
@using MasaBlazorApp3.Pojo.Config;
@using MasaBlazorApp3.Pojo.Vo;
@using MasaBlazorApp3.Util;
@using Microsoft.Extensions.Options;
@using Newtonsoft.Json;
@using log4net;

<RadzenStack Gap="1rem" Orientation="Orientation.Vertical" JustifyContent="JustifyContent.SpaceBetween" Style="height: 100%;">

    <RadzenStack>

        <RadzenDataGrid @ref="grid" Data="@data" ExpandMode="DataGridExpandMode.Multiple"
        RowRender="@RowRender"
        EmptyText="无数据" AllowAlternatingRows="false">

            <Template Context="di">
                <RadzenDataGrid Data="@di.ChannelStocks" EmptyText="无数据" @ref="di.Grid"
                CellClick="@((DataGridCellMouseEventArgs<ChannelStock> args) => OnCellClick(args, di.Grid))">
                    <Columns>
                        <RadzenDataGridColumn Title="库位" Property="DrawerNo">
                            <Template Context="s">
                                @s.DrawerNo - @s.ColNo
                            </Template>
                        </RadzenDataGridColumn>
                        <RadzenDataGridColumn Title="库存" Property="Quantity"></RadzenDataGridColumn>
                        @* <RadzenDataGridColumn Title="批次" Property="ManuNo"></RadzenDataGridColumn>
                            <RadzenDataGridColumn Title="效期" Property="EffDate"></RadzenDataGridColumn> *@
                        <RadzenDataGridColumn Title="入库数量" Property="ReturnQuantity">
                            <EditTemplate Context="cs">
                                <RadzenNumeric Disabled="status > 0" Style="display: block" Min="0" Max="@di.Quantity" Name="Quantity" @bind-Value=@cs.ReturnQuantity />
                                <RadzenNumericRangeValidator Style="position: absolute;z-index: 9999;" Min="0" Max="@di.Quantity" Text="请填写正确的添加数量" Component="Quantity" />
                                <RadzenCustomValidator Validator="@(() => di.ChannelStocks.Sum(cs2 => cs2.ReturnQuantity) == di.Quantity)" Component="Quantity" Text="入库总量应等于还药总数" Style="position: absolute;z-index: 9999;" />
                            </EditTemplate>
                        </RadzenDataGridColumn>
                    </Columns>
                </RadzenDataGrid>
            </Template>
            <Columns>
                <RadzenDataGridColumn Property="Drug.DrugName" Title="药品" />
                <RadzenDataGridColumn Property="Drug.DrugSpec" Title="规格" />
                <RadzenDataGridColumn Property="ManuNo" Title="批次">
                    <Template Context="ov">
                        @ov.data.First().ManuNo
                    </Template>
                </RadzenDataGridColumn>
                <RadzenDataGridColumn Property="EffDate" Title="效期">
                    <Template Context="ov">
                        @ov.data.First().EffDate
                    </Template>
                </RadzenDataGridColumn>
                <RadzenDataGridColumn Property="Quantity" Title="还药总数">
                    <HeaderTemplate>
                        <div style="text-align: center;">
                            还药<br>总数
                        </div>
                    </HeaderTemplate>
                </RadzenDataGridColumn>
                <RadzenDataGridColumn Property="StockQuantity" Title="总库存" />
            </Columns>
        </RadzenDataGrid>



    </RadzenStack>
    <RadzenStack Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.Center" Gap="0.5rem">
        @if (status < 2)
        {
            <RadzenButton Click="@StartAdd" Disabled="!CanTakeDrug" IsBusy="status > 0" BusyText="加药中。。。" ButtonStyle="ButtonStyle.Warning" Variant="Variant.Flat" Text="加药" Style="width: 120px" />
        }
        @if (status == 2)
        {
            <RadzenButton Click="@AddFinish" ButtonStyle="ButtonStyle.Success" Variant="Variant.Flat" Text="完成" Style="width: 120px" />
        }
        @if (status < 2)
        {
            <RadzenButton Click="@((args) => CancelOpera())" Variant="Variant.Flat" Text="取消" Style="width: 120px" />
        }
    </RadzenStack>
</RadzenStack>

@code {
    @inject Radzen.DialogService dialogService;
    @inject IMachineRecordDao machineRecordDao;
    @inject IOptions<DrawerConfig> setting;
    @inject NotificationService _message
    @inject PortUtil PortUtil;

    RadzenDataGrid<OperationVo<List<MachineRecord>>> grid;


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

    [Parameter] public List<MachineRecord> records { get; set; }
    private bool CanTakeDrug = true;
    int status = 0;

    public List<OperationVo<List<MachineRecord>>> data { get; set; }

    async Task StartAdd()
    {
        if (data.Any(it => it.Quantity != it.ChannelStocks.Sum(cs => cs.ReturnQuantity)))
        {
            _message.Notify(
                new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"请填写正确的入库数量！", Duration = 4000 }
            );

        }
        else
        {
            await OpenDrawer();
        }
    }

    async Task CancelOpera()
    {
        PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
        status = 0;
        dialogService.Close(false);
    }


    async Task OpenDrawer()
    {
        this.status = 1;
        PortUtil.PowerOn();
        await Task.Delay(200);
        // 解析需要打开的抽屉列表
        List<ChannelStock> channels = new();
        for (int i = 0; i < data.Count; i++)
        {
            channels = channels.Concat(data[i].ChannelStocks.Where(cs => cs.ReturnQuantity > 0)).ToList();
        }
        if (channels.Count == 0)
        {
            _message.Notify(
                new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"请填写正确的入库数量！", Duration = 4000 }
            );
            return;
        }

        List<int> drawerNos = channels.GroupBy(it => it.DrawerNo).Select(it => it.Key).ToList();

        // 根据抽屉类型来决定打开前是否需要查询数量
        int index = 0;
        var BeforeQuantity = new int[9];
        var AfterQuantity = new int[9];
        await new PromiseUtil<int>().taskAsyncLoop(500, 0, async (options, next, stop) =>
        {
            var drawerNo = drawerNos[index];
            try
            {
                if (this.status == 0)
                {
                    stop();
                }
                // 开启抽屉
                else if (this.status == 1)
                {
                    if (options._data == 0)
                    {
                        BeforeQuantity = new int[9];
                        AfterQuantity = new int[9];
                        // 判断是否为单支抽屉
                        if (setting.Value.single.Contains(drawerNo))
                        {
                            byte[] quantity = await PortUtil.CheckQuantityByDrawer(drawerNo);
                            BeforeQuantity = quantity.Select(it => Convert.ToInt32(it)).ToArray().Skip(3).Take(9).ToArray();
                            logger.Info($"单支抽屉【{drawerNo}】，开抽屉前检测数量【{string.Join(",", BeforeQuantity)}】");
                            var colNo = data.Select(ot => ot.ChannelStocks.Where(cs => cs.DrawerNo == drawerNo).Select(cs => cs.ColNo));
                            await PortUtil.NoLightOnByCol(drawerNo, colNo.SelectMany(x => x).ToArray());
                        }
                        var b = await PortUtil.OpenDrawerStatus(drawerNo);
                        if (b)
                        {
                            PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
                            PortUtil.SpeakAsync($"{drawerNo}号抽屉已经打开，请，加药");
                            options._data = 1;
                            next();
                        }
                        else
                        {
                            _message.Notify(
                                new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"抽屉【{drawerNo}】打开失败，请检测硬件", Duration = 4000 }
                            );
                            logger.Info($"抽屉打开失败");
                            PortUtil.PowerOff();
                            RestData();
                            stop();
                        }
                    }
                    // 检测状态
                    else if (options._data == 1)
                    {
                        // 查询抽屉是否为关闭状态
                        var b = await PortUtil.CheckDrawerStatus2(drawerNo);
                        // 关闭则改变状态并终止循环
                        if (b)
                        {
                            options._data = 0;
                            if (setting.Value.single.Contains(drawerNo))
                            {
                                PortUtil.PowerOff();
                            }
                            if (index == drawerNos.Count - 1)
                            {
                                PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
                                PortUtil.SpeakAsync($"加药完成，请，点击完成按钮进行确认");
                                this.status = 2;
                                stop();
                            }
                            else
                            {
                                index += 1;
                                next();
                            }
                        }
                        else
                        {
                            if (setting.Value.single.Contains(drawerNo))
                            {
                                byte[] quantity = await PortUtil.CheckQuantityByDrawer(drawerNo);
                                AfterQuantity = quantity.Select(it => Convert.ToInt32(it)).ToArray().Skip(3).Take(9).ToArray();
                                logger.Info($"单支抽屉【{drawerNo}】，抽屉未关检测数量【{string.Join(",", AfterQuantity)}】");

                                data.ForEach(cl =>
                                {
                                    // cl.ChannelStocks.Where(cs => cs.DrawerNo == drawerNo).ToList().ForEach(cs =>
                                    // {
                                    //     logger.Info($"单支抽屉【{drawerNo}】，应加药品数量【{cs.AddQuantity}】,现实加药数量【{AfterQuantity[cs.ColNo - 1] - BeforeQuantity[cs.ColNo - 1]}】");
                                    // });
                                    cl.ChannelStocks.Where(cs => cs.DrawerNo == drawerNo).ToList().ForEach(cs =>
                                    {
                                        cl.ReturnQuantity = AfterQuantity[cs.ColNo - 1] - BeforeQuantity[cs.ColNo - 1];
                                    });
                                });
                            }
                            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();
        this.status = 0;
    }

    async Task AddFinish()
    {

        // 保存账册、操作记录
        var b = await machineRecordDao.ReturnDrugFinish(data);
        if (!b)
        {
            _message.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"数据保存失败", Duration = 4000 });
            logger.Error($"抽屉加药保存数据库失败，数据{JsonConvert.SerializeObject(data)}");
            // 关闭弹窗
            dialogService.Close(false);
        }
        else
        {
            // 关闭弹窗
            dialogService.Close(true);

        }
        //重置状态
        this.RestData();
    }


    protected override async Task OnInitializedAsync()
    {
        data = await machineRecordDao.getReturnDrugInfoByRecords(records);
        // 如果有库位列表未空则说明不能取药，需要增加库位
        if (data.Any(it => it.ChannelStocks.Count == 0))
        {
            CanTakeDrug = false;
        }
        base.OnInitializedAsync();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        base.OnAfterRender(firstRender);

        if (firstRender)
        {
            await Task.Delay(15);
            await grid.ExpandRows(grid.PagedView.Where(it => it.ChannelStocks.Count > 0));
        }
    }


    void RowRender(RowRenderEventArgs<OperationVo<List<MachineRecord>>> args)
    {
        args.Expandable = args.Data.ChannelStocks != null && args.Data.ChannelStocks.Count > 0;
    }


    void OnCellClick(DataGridCellMouseEventArgs<ChannelStock> args, RadzenDataGrid<ChannelStock> Grid)
    {
        Grid.EditRow(args.Data);
    }


}
