@page "/Box/BoxRemove"
@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" Style="height: 100%;">
    <RadzenStack>
        <RadzenStack class="rz-p-4 rz-border-radius-1" Style="border: var(--rz-grid-cell-border)" Orientation="Orientation.Horizontal" Gap="1rem">
            @*   <RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">药名:</RadzenText>
            <RadzenText Class="rz-text-truncate"><b>@(channelStock.Drug.DrugName)</b></RadzenText>
            <RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">规格:</RadzenText>
            <RadzenText TextStyle="TextStyle.Body1" Class="rz-text-truncate"><b>@(channelStock.Drug.DrugSpec)</b></RadzenText>
            <RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">批次:</RadzenText>
            <RadzenText TextStyle="TextStyle.Body1" Class="rz-text-truncate"><b>@(channelStock.ManuNo)</b></RadzenText>
            <RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">效期:</RadzenText>
            <RadzenText TextStyle="TextStyle.Body1" Class="rz-text-truncate"><b>@(channelStock.EffDate)</b></RadzenText>
            <RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">库存:</RadzenText>
            <RadzenText TextStyle="TextStyle.Body1" Class="rz-text-truncate"><b>@(channelStock.Quantity)</b></RadzenText> *@
            <div style="text-align: left;width:15vw">
                <div class="rz-text-h6 rz-mb-0">药品名称</div>
                @(channelStock.Drug.DrugName)
            </div>
            <div style="text-align: left;width:6vw">
                <div class="rz-text-h6 rz-mb-0">规格</div>
                @(channelStock.Drug.DrugSpec)
            </div>
            <div style="text-align: left;width:8vw;">
                <div class="rz-text-h6 rz-mb-0">批次</div>
                @(channelStock.ManuNo)
            </div>
            <div style="text-align: left;width:8vw;">
                <div class="rz-text-h6 rz-mb-0">效期</div>
                @(channelStock.EffDate)
            </div>
            <div style="text-align: left;width:4vw;">
                <div class="rz-text-h6 rz-mb-0">库存</div>
                @(channelStock.Quantity)
            </div>
        </RadzenStack>
    </RadzenStack>
    <RadzenStack style="align-content:center">

        <RadzenStack class="rz-p-4 rz-border-radius-1" Style="border: var(--rz-grid-cell-border);align-content:center" Orientation="Orientation.Horizontal" Gap="1rem">
            <RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">移入</RadzenText>
            <RadzenDropDownDataGrid AllowVirtualization="true" Name="BoxColorList" TValue="BoxModel" Data="@BoxColorList" Value="BoxColor" Style="width: 11vw;"
                                    ValueChanged="@((args) => OnColorChanged(args))" AllowFiltering="false"
                                    AllowFilteringByAllStringColumns="true" TextProperty="药箱号">
                <Template>
                    @((context as BoxModel).BoxNo == 1 ? "白" : (context as BoxModel).BoxNo == 2 ? "绿" : (context as BoxModel).BoxNo == 3 ? "非常规" : "抽屉")
                </Template>
                <Columns>
                    <RadzenDropDownDataGridColumn Property="BoxNo" Title="药箱颜色" Sortable="false" />
                </Columns>
            </RadzenDropDownDataGrid>
            <RadzenDropDown @bind-Value="SelectedDrawerNo" Data="@DrawerNos" Style="display: block;" Name="DropDownChangeEvent">
                <RadzenText TextStyle="TextStyle.Subtitle2" class="mb-0">@(SelectedDrawerNo)</RadzenText>
            </RadzenDropDown>

            <RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">移入数量</RadzenText>

            <RadzenNumeric Min="0" Style="display: block" Max=@channelStock.Quantity Name="Quantity" @bind-Value="removeQuantity" />
        </RadzenStack>
    </RadzenStack>
    <RadzenStack Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.Center" Gap="0.5rem">
        @if (BoxColor.BoxNo == 4)
        {
            @if (status < 3)
            {
                <RadzenButton IsBusy="@(status > 0)" BusyText="加药中。。。" ButtonStyle="ButtonStyle.Warning" Variant="Variant.Flat" Shade="Shade.Light" Text="加药" Click="@OpenDrawer" Style="width: 120px" />
                <RadzenButton Visible="@CancleIsEnable" Variant="Variant.Flat" Text="取消" Click="@Cancel" Style="width: 120px" />
            }
            @if (status == 3)
            {
                <RadzenButton Visible="@CompleteIsEnable" ButtonStyle="ButtonStyle.Warning" Variant="Variant.Flat" Shade="Shade.Light" Text="完成" Click="@AddFinish" Style="width: 120px" />
                <RadzenButton Visible="@CancleIsEnable" Variant="Variant.Flat" Text="取消" Click="@Cancel" Style="width: 120px" />
            }
        }
        else
        {
            <RadzenButton Click="@Save" ButtonStyle="ButtonStyle.Success" Variant="Variant.Flat" Text="完成" Style="width: 120px" />
            <RadzenButton Click="@Cancel" Variant="Variant.Flat" Text="取消" Style="width: 120px" />
        }

    </RadzenStack>
</RadzenStack>

@code {
    @inject Radzen.DialogService dialogService;
    @inject IChannelListDao channelListDao;
    @inject IOptions<SettingConfig> setting
    @inject IOptions<DrawerConfig> drawerSetting;
    @inject IOptions<PortConfig> portSetting;
    @inject NotificationService _message
    @inject PortUtil PortUtil;
    private readonly ILog logger = LogManager.GetLogger(typeof(OrderDetailDialog));

    bool CompleteIsEnable = true;
    bool CancleIsEnable = true;

    int removeQuantity = 0;
    int status;

    string[] AllDrawerNos;
    string[] DrawerNos;
    string SelectedDrawerNo = "1-1";

    //药盒集合
    List<BoxModel> BoxList = new List<BoxModel>();
    //药盒颜色集合
    List<BoxModel> BoxColorList = new List<BoxModel>()
        {
            new  BoxModel{BoxNo=1,BoxName=1 },
            new  BoxModel{BoxNo=2 ,BoxName=1},
            new  BoxModel{BoxNo=3 ,BoxName=1},
            new  BoxModel{BoxNo=4 ,BoxName=1}
        };
    BoxModel BoxColor = new BoxModel { BoxNo = 1, BoxName = 1 };
    BoxModel BoxNum;
    [Parameter] public ChannelStock channelStock { get; set; }
    private bool CanTakeDrug = true;

    // public List<BoxTakeVo> data { get; set; }


    //称重取药数量
    int[] WeightFinnalQuantity { get; set; } = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

    //开抽屉前操作标识
    List<string> DrawerNoColNoList = new List<string>();

    protected override async Task OnInitializedAsync()
    {
        AllDrawerNos = await channelListDao.GetDrawerNumForRemove(channelStock);
        if (AllDrawerNos != null && AllDrawerNos.Count() > 0)
        {
            DrawerNos = AllDrawerNos.Where(d => d.EndsWith('白')).ToArray();
            if (DrawerNos != null && DrawerNos.Length > 0)
                SelectedDrawerNo = DrawerNos[0];
            // var result = await channelListDao.GetChannelStockByDrug(channelStock, SelectedDrawerNo, 8, 0);
            // selectedDrawerData = result.Desserts;
        }
        else
        {
            DrawerNos = new string[] { "无库位" };
        }
        base.OnInitializedAsync();
    }

    // void RestData()
    // {
    // 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];
    // DrawerNoColNoList.Clear();
    // }

    private async Task OnColorChanged(object value)
    {
        BoxColor = (BoxModel)value;
        if (AllDrawerNos != null && AllDrawerNos.Length > 0 && AllDrawerNos[0] != "无库位")
        {
            if ((((BoxModel)value).BoxNo) == 3)
            {
                DrawerNos = AllDrawerNos.Where(d => !(d.EndsWith('白')) && !(d.EndsWith('绿')) && !(d.Contains('-'))).ToArray();
                if (DrawerNos != null && DrawerNos.Length > 0 && DrawerNos[0] != "无库位")
                {
                    SelectedDrawerNo = DrawerNos[0];
                }
                else
                {
                    SelectedDrawerNo = "无库位";
                }
                await InvokeAsync(StateHasChanged);
            }
            else
            {
                if ((((BoxModel)value).BoxNo) == 1)
                {
                    DrawerNos = AllDrawerNos.Where(d => d.EndsWith('白')).ToArray();
                    if (DrawerNos != null && DrawerNos.Length > 0 && DrawerNos[0] != "无库位")
                    {
                        SelectedDrawerNo = DrawerNos[0];
                    }
                    else
                    {
                        SelectedDrawerNo = "无库位";
                    }
                    await InvokeAsync(StateHasChanged);
                }
                else if ((((BoxModel)value).BoxNo) == 2)
                {
                    DrawerNos = AllDrawerNos.Where(d => d.EndsWith('绿')).ToArray();
                    if (DrawerNos != null && DrawerNos.Length > 0 && DrawerNos[0] != "无库位")
                    {
                        SelectedDrawerNo = DrawerNos[0];
                    }
                    else
                    {
                        SelectedDrawerNo = "无库位";
                    }
                    await InvokeAsync(StateHasChanged);
                }
                else if ((((BoxModel)value).BoxNo) == 4)
                {
                    DrawerNos = AllDrawerNos.Where(d => !(d.EndsWith('绿')) && !(d.EndsWith('白')) && d.Contains('-')).ToArray();
                    if (DrawerNos != null && DrawerNos.Length > 0 && DrawerNos[0] != "无库位")
                    {
                        SelectedDrawerNo = DrawerNos[0];
                    }
                    else
                    {
                        SelectedDrawerNo = "无库位";
                    }
                    await InvokeAsync(StateHasChanged);

                }
            }
        }
    }
    void Cancel()
    {
        RestData();
        // 关闭弹窗
        dialogService.Close(false);
    }
    async Task Save()
    {
        if (removeQuantity <= 0)
        {
            _message.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = "请输入移入数量", Duration = 4000 });
            return;
        }
        if (string.IsNullOrEmpty(SelectedDrawerNo) || SelectedDrawerNo == "无库位")
        {
            _message.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = "无可移入的药盒", Duration = 4000 });
            return;
        }
        SelectedDrawerNo = SelectedDrawerNo == "急诊药盒" ? "99-1" : SelectedDrawerNo == "恢复室药盒" ? "111-1" : SelectedDrawerNo;
        var b = await channelListDao.BoxRemoveFinish(channelStock, SelectedDrawerNo, removeQuantity);
        if (!b)
        {
            _message.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"数据保存失败", Duration = 4000 });
            logger.Error($"药盒移出保存数据失败，数据{JsonConvert.SerializeObject(channelStock)}");
        }
        else
        {
            _message.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "提示", Detail = $"交换完成", Duration = 4000 });
            // 关闭弹窗
            dialogService.Close(true);

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

    int drawerNo = 1;
    int colNo = 1;
    int[] BeforeQuantity = new int[9];
    int[] AfterQuantity = new int[9];
    async Task OpenDrawer()
    {
        this.status = 1;
        var selectSpl = SelectedDrawerNo.Split('-');

        if (selectSpl != null && selectSpl.Count() > 0)
        {
            drawerNo = Convert.ToInt32(selectSpl[0]);
            colNo = Convert.ToInt32(selectSpl[1]);
        }
        PortUtil.DrawerNo = drawerNo;
        // 根据抽屉类型来决定打开前是否需要查询数量
        var promiseUtil = new PromiseUtil<object>();
        await promiseUtil.taskAsyncLoop(500, null, async (data, next, stop) =>
        {
            try
            {
                if (this.status == 0)
                {
                    stop();
                }
                // 开启抽屉
                else if (this.status == 1)
                {
                    // 判断是否为单支抽屉
                    if (drawerSetting.Value.single != null && drawerSetting.Value.single.Contains(this.drawerNo))
                    {
                        PortUtil.PowerOn(drawerNo);
                        await Task.Delay(portSetting.Value.delayTime);
                        byte[] quantity = await PortUtil.CheckQuantityByDrawer(this.drawerNo);
                        BeforeQuantity = quantity.Select(it => Convert.ToInt32(it)).ToArray().Skip(3).Take(9).ToArray();
                        logger.Info($"单支抽屉，开抽屉前检测数量【{string.Join(",", BeforeQuantity)}】");
                    }
                    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 if (this.status == 2)
                {
                    // 查询抽屉是否为关闭状态
                    var b = await PortUtil.CheckDrawerStatus2(drawerNo);
                    // 关闭则改变状态并终止循环
                    if (b)
                    {
                        PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
                        PortUtil.SpeakAsync($"加药完成，请，点击完成按钮");
                        this.status = 3;
                        PortUtil.Operate = false;
                        if (drawerSetting.Value.single.Contains(drawerNo))
                        {
                            PortUtil.PowerOff(drawerNo);
                        }
                        stop();
                    }
                    else
                    {
                        if (drawerSetting.Value.single != null && drawerSetting.Value.single.Contains(this.drawerNo))
                        {
                            byte[] quantity = await PortUtil.CheckQuantityByDrawer(this.drawerNo);
                            AfterQuantity = quantity.Select(it => Convert.ToInt32(it)).ToArray().Skip(3).Take(9).ToArray();
                            logger.Info($"单支抽屉，抽屉未关检测数量【{string.Join(",", AfterQuantity)}】");

                            removeQuantity = this.AfterQuantity[colNo - 1] - this.BeforeQuantity[colNo - 1];
                            await InvokeAsync(StateHasChanged);
                        }
                        next(); // continue iteration
                    }

                }
            }
            catch (Exception e)
            {
                logger.Info($"抽屉加药发生错误，{e.Message}");
                _message.Notify(
                    new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"发生错误，{e.Message}", Duration = 4000 }
                );
                if (drawerSetting.Value.single != null && drawerSetting.Value.single.Contains(this.drawerNo))
                {
                    PortUtil.PowerOff(drawerNo);
                }
                RestData();
                stop();
            }
        });
    }

    void RestData()
    {
        PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
        this.status = 0;
        // this.BeforeQuantity = new int[9];
        // this.AfterQuantity = new int[9];
        // currentCol = 0;
        // ColNos.Clear();
    }
    async Task AddFinish()
    {
        if (removeQuantity <= 0)
        {
            _message.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = "请输入移入数量", Duration = 4000 });
            return;
        }
        // 保存账册、操作记录
        var b = await channelListDao.RemoveDrugToDrawerFinish(SelectedDrawerNo, channelStock, removeQuantity);
        if (!b)
        {
            _message.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"数据保存失败", Duration = 4000 });
            logger.Error($"抽屉加药保存数据库失败，数据{JsonConvert.SerializeObject(channelStock)}");
        }
        //重置状态
        this.RestData();
        // 关闭弹窗
        dialogService.Close(true);
    }
}