@page "/stock/biaoDing"
@using MasaBlazorApp3.Pojo.Config;
@using MasaBlazorApp3.Util;
@using Microsoft.AspNetCore.Components
@using Microsoft.Extensions.Options;
@using Newtonsoft.Json;
@using log4net;
<style>
    .rz-custom-header {
    width: 100%;
    }
</style>

<RadzenStack Orientation="Orientation.Horizontal">
    <div class="row  justify-content-center">
        @if (DrawerNos.Count() > 8)
        {
            <div class="col-12 row justify-content-center align-items-center text-center" style="background: url('/images/box-16.jpg')  no-repeat; background-size: 100% 100%; width: 380px; height:650px">
                <div class="row justify-content-around align-items-center" style="margin-top: 220px; height: 430px;">
                    @foreach (int i in DrawerNos)
                    {
                        <RadzenButton class="col-5" Click="@(() => SelectDrawer(i))" Text="@i.ToString()" Disabled="@(status > 0||!setting.Value.weigh.Contains(i))" Shade="Shade.Light" Variant="@(drawerNo !=i ? Variant.Outlined : Variant.Flat)" />

                    }
                </div>
            </div>
        }
        else
        {
            <div class="col-12 row justify-content-center align-items-center text-center" style="background: url('/images/box.png')  no-repeat; background-size: 100% 100%; width: 380px; height:650px">
                <div class="row justify-content-around align-items-center" style="margin-top: 220px; height: 430px;">
                    @foreach (int i in DrawerNos)
                    {
                        <RadzenButton class="col-12" Click="@(() => SelectDrawer(i))" Text="@i.ToString()" Disabled="@(status > 0)" Shade="Shade.Light" Variant="@(drawerNo !=i ? Variant.Outlined : Variant.Flat)" />

                    }
                </div>
            </div>
        }

    </div>
    <RadzenDataGrid @ref="grid"
    LoadData="@LoadData"
    IsLoading="@isLoading"
    Count="@count"
    EmptyText="无数据"
    Data="@channels"
    AllowColumnResize="true" AllowAlternatingRows="false"
    CellClick="@((DataGridCellMouseEventArgs<ChannelStock> args) => OnCellClick(args))"
    AllowPaging="true" PageSize="10" PagerHorizontalAlign="HorizontalAlign.Left" ShowPagingSummary="true" PagingSummaryFormat="{0}/{1} 共{2}条数据">
        <HeaderTemplate>
            <RadzenRow JustifyContent="JustifyContent.End">
                @if (status < 3)
                {
                    <RadzenButton IsBusy="@(status>0)" BusyText="抽屉已打开。。。" ButtonStyle="ButtonStyle.Warning" Variant="Variant.Flat" Shade="Shade.Light" Text="开抽屉" Click="@OpenDrawer" />
                }
                @if (status > 0 && status <= 3)
                {
                    <RadzenButton Visible="@CancleIsEnable" Variant="Variant.Flat" Text="取消" Click="@Cancel" Style="width: 120px" />
                }
            </RadzenRow>
        </HeaderTemplate>
        <Columns>
            <RadzenDataGridColumn Width="70px" Title="库位" Property="ColNo"></RadzenDataGridColumn>
            <RadzenDataGridColumn Title="药品名称" Property="Drug.DrugName">
                <Template Context="channel">
                    <RadzenText TextStyle="TextStyle.Subtitle2" class="mb-0">@channel.Drug?.DrugName</RadzenText>
                    <RadzenText TextStyle="TextStyle.Caption">@channel.Drug?.DrugSpec</RadzenText>
                </Template>
            </RadzenDataGridColumn>
            <RadzenDataGridColumn Title="批次" Property="ManuNo">
                <Template Context="channel">
                    <RadzenText TextStyle="TextStyle.Subtitle2" class="mb-0">@channel.drugManuNo?.ManuNo</RadzenText>
                    <RadzenText TextStyle="TextStyle.Caption">@channel.drugManuNo?.EffDate.ToString().Substring(0,10)</RadzenText>
                </Template>
            </RadzenDataGridColumn>
            <RadzenDataGridColumn Title="库存" Property="Quantity">
                <Template Context="cs">
                    <RadzenButton ButtonStyle="ButtonStyle.Info" Variant="Variant.Flat" Shade="Shade.Lighter" class="m-1" Text="@cs.Quantity.ToString()" />
                </Template>
            </RadzenDataGridColumn>
            <RadzenGridColumn Title="状态" Property="BiaoDingStatus">

            </RadzenGridColumn>
        </Columns>
    </RadzenDataGrid>
</RadzenStack>
@code {
    @inject IChannelListDao channelListDao;
    @inject NavigationManager na;
    @inject PortUtil PortUtil;
    @inject NotificationService _message
    @inject IOptions<DrawerConfig> setting;
    @inject DialogService dialogService;
    int status = 0;
    int drawerNo = 0;
    RadzenDataGrid<ChannelStock> grid;
    private List<ChannelStock>? channels;
    bool isLoading;
    int count;
    int[] DrawerNos = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
    int[] BeforeQuantity = new int[9];
    int[] AfterQuantity = new int[9];
    private readonly ILog logger = LogManager.GetLogger(typeof(BiaoDing));

    // 当前操作的库位号列表
    public List<int> ColNos { get; set; } = new List<int>();
    //当前操作的库位数据
    ChannelStock currentChannelStock;
    bool CompleteIsEnable = true;
    bool CancleIsEnable = true;

    void SelectDrawer(int drawerNo)
    {
        this.drawerNo = drawerNo;
        grid.Reload();
    }

    async Task LoadData(LoadDataArgs args)
    {
        isLoading = true;
        if (drawerNo > 0)
        {
            var result = await channelListDao.GetChannelStockByBiaoDing(drawerNo);
            DrawerNos = result.DrawerArray;
            channels = result.ChannelStocks;
            count = result.ChannelStocks.Count;
        }

        isLoading = false;
    }
    async Task OpenDrawer()
    {
        this.status = 1;
        var promiseUtil = new PromiseUtil<object>();
        await promiseUtil.taskAsyncLoop(300, null, async (data, next, stop) =>
        {
            try
            {
                if (this.status == 0)
                {
                    stop();
                }
                else
                {
                    if (this.status == 1)
                    {
                        PortUtil.DrawerNo = this.drawerNo;
                        var b = await PortUtil.OpenDrawerStatus(this.drawerNo);
                        if (b)
                        {
                            PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
                            PortUtil.SpeakAsync($"{drawerNo}号抽屉已经打开，请选择库位开药盒");
                            this.status = 2;
                            PortUtil.Operate = true;
                            next();
                        }
                        else
                        {
                            _message.Notify(
                            new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"抽屉【{drawerNo}】打开失败，请检测硬件", Duration = 4000 }
                            );
                            logger.Info($"抽屉打开失败");
                            RestData();
                            PortUtil.Operate = false;
                            stop();
                        }
                    }
                    else
                    {
                        //查询抽屉状态
                        var b = await PortUtil.CheckDrawerStatus2(drawerNo);
                        if (!b)
                        {
                            if (this.status == 2)
                            {
                                //药盒称重抽屉
                                if (currentChannelStock != null && currentChannelStock.BoardType.ToString().Contains("3"))
                                {
                                    //打开药盒
                                    await PortUtil.OpenBoxByColNo(currentChannelStock.ColNo);
                                    this.status = 3;
                                }
                            }
                            if (this.status == 3)
                            {
                                this.status = 4;
                                //弹出标定对话框
                                var dialog = await dialogService.OpenAsync<BiaoDingDialog>(
                                          $"标定库位{currentChannelStock.ColNo}",
                                        new Dictionary<string, object>() { { "channelStockInfo",
                                                currentChannelStock } },
                                        new DialogOptions() { Width = "45vw", Resizable = true, Draggable = true, ShowClose = false });
                                currentChannelStock = null;
                                //关闭弹窗后将状态置为2以便下次点击药盒进行开药盒操作
                                this.status = 2;
                            }
                            next();
                        }
                        else
                        {
                            //抽屉已关闭
                            stop();
                            this.status = 0;
                            logger.Info($"抽屉关闭");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger.Info($"标定药品发生错误，{e.Message}");
                _message.Notify(
                new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"发生错误，{e.Message}", Duration = 4000 }
            );
                if (setting.Value.single != null && setting.Value.single.Contains(this.drawerNo))
                {
                    PortUtil.AllLightOff();
                }
                RestData();
                stop();
            }
        });
    }
    void RestData()
    {
        this.status = 0;
    }
    void Cancel()
    {
        this.status = 0;
    }

    void OnCellClick(DataGridCellMouseEventArgs<ChannelStock> args)
    {
        if (this.status == 0)
        {
            PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
            PortUtil.SpeakAsync("请先打开抽屉后再点开药盒");
        }
        else
        {
            currentChannelStock = args.Data;
            if (args.Data.BoardType.ToString().Contains("3"))
            {
                PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
                PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
                PortUtil.SpeakAsync("正在打开药盒");
            }
            // else
            // {
            //     grid.EditRow(args.Data);
            // }
        }
    }
}
