@page "/Box/Check"
@using MasaBlazorApp3.Pojo.Config
@using MasaBlazorApp3.Report
@using Microsoft.Extensions.Options
@using Radzen.Blazor.Rendering
@using log4net;

<style>
    .my-popup {
    display: none;
    position: absolute;
    overflow: auto;
    /* height: 360px; */
    width: 900px;
    border: var(--rz-panel-border);
    background-color: var(--rz-panel-background-color);
    box-shadow: var(--rz-panel-shadow);
    border-radius: var(--rz-border-radius);
    }

    .rz-grid-table {
    position: relative;
    border-collapse: separate;
    border-spacing: 0;
    }
</style>

@* <RadzenStack Orientation="Orientation.Horizontal"> *@
<div class="col-12" style="margin-bottom:5px;">
    @* <RadzenStack Orientation="Orientation.Horizontal" Gap="1rem"> *@
    <RadzenRow AlignItems="AlignItems.Center">
        <RadzenColumn Size="12">
            <RadzenLabel Text="核对药箱" Component="BoxList" />
            <RadzenDropDownDataGrid AllowVirtualization="true" Name="BoxColorList" TValue="BoxModel" Data="@BoxColorList" Value="BoxColor" Style="width: 8vw;"
            ValueChanged="@((args) => OnColorChanged(args))" AllowFiltering="false"
            AllowFilteringByAllStringColumns="true" TextProperty="药箱号">
                <Template>
                    @((context as BoxModel).BoxNo == 1 ? "白" : (context as BoxModel).BoxNo == 3 ? "非常规" : "绿")
                </Template>
                <Columns>
                    <RadzenDropDownDataGridColumn Property="BoxNo" Title="药箱颜色" Sortable="false" />
                </Columns>
            </RadzenDropDownDataGrid>
            <RadzenDropDownDataGrid AllowVirtualization="true" Name="BoxList" TValue="BoxModel" Data="@BoxList" Value="BoxNum" Style="width: 10vw;"
            ValueChanged="@((args) => OnBoxChanged(args))" AllowFilteringByAllStringColumns="true" TextProperty="药箱号">
                <Template>

                    @((context as BoxModel).BoxName == 99 ? "急诊药盒" : (context as BoxModel).BoxName == 111 ? "恢复室药盒" :
                                (context as BoxModel).BoxName == 31 ? "胃镜药盒" :
                                (context as BoxModel).BoxName == 32 ? "导管药盒" :
                                (context as BoxModel).BoxName == 33 ? "生殖药盒" :
                                (context as BoxModel).BoxName == 34 ? "妇门药盒" : (context as BoxModel).BoxName + "-" + ((context as BoxModel).BoxNo == 1 ? "白" : "绿"))

                    @* @((context as BoxModel).BoxName + "-" + (context as BoxModel).BoxNo) *@

                </Template>
                <Columns>
                    <RadzenDropDownDataGridColumn Property="BoxName" Title="药箱号" Sortable="false" />
                </Columns>
            </RadzenDropDownDataGrid>
            <RadzenLabel Text="处方时间" Component="OrderDate" />
            <RadzenDatePicker DateFormat="yyyy-MM-dd" CurrentDateChanged="@OnCurrentDateChanged" @bind-Value="OrderDate" Style="width: 15vw;" Name="OrderDate" />
            @*             <RadzenButton Size="ButtonSize.Medium" Click="Search" IsBusy="isLoading" Icon="search" Text="查询" /> *@
            <RadzenButton Size="ButtonSize.Medium" Click="Confirm" ButtonType="ButtonType.Button" ButtonStyle="ButtonStyle.Success" IsBusy="isLoading" Icon="check_circle" Text="确认" />
            <RadzenButton Size="ButtonSize.Medium" Click="AddOrderMethod" ButtonType="ButtonType.Button" IsBusy="isLoading" ButtonStyle="ButtonStyle.Warning" Icon="input" Text="导入" />
            <RadzenButton Style="margin-top:2px" Icon="download" @ref=button Text="麻醉药品使用登记本导出" Variant="Variant.Outlined" Click="@(args => popup.ToggleAsync(button.Element))" />
            <Popup @ref=popup Lazy=true class="my-popup">
                <RadzenStack Orientation="Orientation.Vertical" Gap="1rem" class="rz-h-100 rz-p-4">
                    <RadzenFieldset Text="条件选择">
                        <RadzenStack Orientation="Orientation.Horizontal" Gap="1rem">
                            <RadzenRow AlignItems="AlignItems.Center">
                                <RadzenColumn Size="6">
                                    <RadzenLabel Text="处方时间" Component="PortOrderDate" />
                                </RadzenColumn>
                                <RadzenColumn Size="6">
                                    <RadzenDatePicker DateFormat="yyyy-MM-dd" CurrentDateChanged="@OnCurrentPortDateChanged" @bind-Value="PortOrderDate" Style="width: 100%;" Name="PortOrderDate" />
                                </RadzenColumn>
                            </RadzenRow>

                            <RadzenRow JustifyContent="JustifyContent.End" AlignItems="AlignItems.Center">
                                <RadzenButton Icon="download" Text="导出" Variant="Variant.Outlined" Click="StockExport" />
                            </RadzenRow>
                        </RadzenStack>
                    </RadzenFieldset>
                </RadzenStack>
            </Popup>
        </RadzenColumn>
    </RadzenRow>
</div>

<RadzenStack Orientation="Orientation.Horizontal">
    <div Style="width:55vw;overflow:auto">
        @*   <RadzenDataGrid @ref="grid" AllowRowSelectOnRowClick="@allowRowSelectOnRowClick" AllowFiltering="true" LoadData="@LoadData" Style="width:50vw;overflow:auto"
        FilterPopupRenderMode="PopupRenderMode.OnDemand" FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive"
        Data="@csList" IsLoading="@isLoading" Count="@count" EmptyText="无数据"
        SelectionMode="DataGridSelectionMode.Multiple" @bind-Value=@selectedcsList
        CellClick="@((DataGridCellMouseEventArgs<ChannelStock> args) => OnDrugCellClick(args))"
        AllowPaging="false">
            <Columns>
                <RadzenDataGridColumn Property="Drug.DrugName" Title="药品名称" FormatString="{0:d}" Sortable="false" Filterable="false" Width="2vw" />
                <RadzenDataGridColumn Title="批次" Property="ManuNo" Filterable="false" Width="2vw">
                </RadzenDataGridColumn>
                <RadzenDataGridColumn Property="DetailInfo.Quantity" Title="合计" Filterable="false" Width="3vw">
                    <Template Context="contextDate">
                        <div style="text-align: center;">
                            库存量【@contextDate.Quantity】<br />
                            用药量【@contextDate.UseQuantity】<br />
                            处方数【@contextDate.OrderQuantity】
                        </div>
                    </Template>
                </RadzenDataGridColumn>
            </Columns>
        </RadzenDataGrid> *@

        <RadzenListBox AllowClear="true" @bind-Value=@listBoxSelectedcsList Style="width:45vw;height:70vh;overflow:auto" AllowFiltering="false" TValue="ChannelStock"
        LoadData=@LoadData Data=@csList>
            <Template>
                <RadzenStack Orientation="Orientation.Horizontal">
                    <RadzenText Style="width:15vw;text-align:left">@((context as ChannelStock).Drug.DrugName)</RadzenText>
                    <RadzenText Style="width:10vw">@((context as ChannelStock).ManuNo)</RadzenText>
                    <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).SelectedOrderList.Aggregate(0, (a, b) => a + b.DetailInfo.Quantity))】<br />
                            处方数【@((context as ChannelStock).SelectedOrderList.Count)】
                        </div>
                    </RadzenStack>
                </RadzenStack>
            </Template>
        </RadzenListBox>
    </div>
    <div Style="width:75vw;overflow:auto;box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3); ">
        @if ((listBoxSelectedcsList != null && string.IsNullOrEmpty(listBoxSelectedcsList.ListId) && listBoxSelectedcsList.Quantity > listBoxSelectedcsList.UseQuantity) || (listBoxSelectedcsList.Quantity > listBoxSelectedcsList.BaseQuantity))
        {
            //ListId为空则是没有在套餐里的药，库存量大于使用量时需要把药还到抽屉里
            //列出需要还到抽屉里的药品的抽屉库位
            @*  <RadzenRow AlignItems="AlignItems.Center" Style="margin:1vw;">
                <RadzenColumn Size="12">
                    <RadzenLabel Text="库位" Component="DrawerList" />
                    <RadzenDropDownDataGrid AllowVirtualization="true" Name="DrawerList" TValue="ChannelStock" @bind-Value="@listBoxSelectedcsList.ReturnDrawerChanneStock" Data="@(listBoxSelectedcsList?.DrawerChanneStockList)"
                    Style="width:20vw;" AllowFilteringByAllStringColumns="true" TextProperty="Location">
                        <Columns>
                            <RadzenDropDownDataGridColumn Property="Location" Title="库位" Sortable="false" />
                            <RadzenDropDownDataGridColumn Property="Quantity" Title="库存" Sortable="false" />
                        </Columns>
                    </RadzenDropDownDataGrid>
                    <RadzenLabel Text="还药数" Component="ReturnQuantity" />
                    <RadzenNumeric Min="0" Name="ReturnQuantity" TValue="int" @bind-Value=@listBoxSelectedcsList.ReturnQuantity Style="width:5vw;" />
                    <RadzenNumericRangeValidator Min="0" Max=@listBoxSelectedcsList.Quantity Text="请填写正确的还药数量" Component="ReturnQuantity" Popup="true" />

                </RadzenColumn>
            </RadzenRow> 
            <RadzenRow AlignItems="AlignItems.Center" Style="margin:1vw;">
                <RadzenColumn Size="12">*@
            @if (listBoxSelectedcsList?.DrawerChanneStockList != null)
            {
                <RadzenListBox AllowClear="true" @bind-Value=@returnList AllowFiltering="false" TValue="ChannelStock" Style="width:70vw;overflow:auto"
                Data=@(listBoxSelectedcsList?.DrawerChanneStockList)>
                    <Template>
                        <RadzenStack Orientation="Orientation.Horizontal">
                            <RadzenText Style="width:20vw;text-align:left">还药库位@((context as ChannelStock).Location)</RadzenText>
                            <RadzenText Style="width:10vw">还药数@((context as ChannelStock).ReturnQuantity)</RadzenText>
                        </RadzenStack>
                    </Template>
                </RadzenListBox>
            }
            @*   </RadzenColumn>
            </RadzenRow> *@
        }

        <RadzenDataGrid Style="width:55vw;height:70vh;overflow:auto"
        FilterPopupRenderMode="PopupRenderMode.OnDemand" FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive"
        Data="@(listBoxSelectedcsList?.OrderList)" EmptyText="无处方数据"
        @bind-Value="@(listBoxSelectedcsList.SelectedOrderList)"
        SelectionMode="DataGridSelectionMode.Multiple"
        AllowRowSelectOnRowClick="true"
        AllowPaging="false">
            <Columns>
                <RadzenDataGridColumn Sortable="false" Filterable="false" Width="1rem">
                    @* <HeaderTemplate>
                        <RadzenCheckBox TabIndex="-1" TriState="false" TValue="bool?" InputAttributes="@(new Dictionary<string, object>() { { "aria-label", "Select all items" } })"
                                        Value="@(listBoxSelectedcsList?.OrderList!=null&&(bool)listBoxSelectedcsList?.OrderList.Any(oi=>oi. ItemIsChecked))"
                        Change="@(args => ChangeHeaderCheckBox(args))" />
                    </HeaderTemplate>
                    <Template Context="data">
                        <RadzenCheckBox TabIndex="-1" TriState="false" Value="@data.ItemIsChecked" InputAttributes="@(new Dictionary<string, object>() { { "aria-label", "Select item" } })"
                        TValue="bool" Change="@(args => { data.ItemIsChecked=!data.ItemIsChecked;})" />
                    </Template> *@
                    <HeaderTemplate>
                        <RadzenCheckBox TabIndex="-1" TriState="false" TValue="bool?" InputAttributes="@(new Dictionary<string, object>() { { "aria-label", "Select all items" } })"
                        Value="@(listBoxSelectedcsList?.SelectedOrderList==null || listBoxSelectedcsList?.SelectedOrderList.Any() !=true? false: !(bool)listBoxSelectedcsList?.OrderList.All(i => (bool)(listBoxSelectedcsList?.SelectedOrderList.Contains(i)))?null:listBoxSelectedcsList?.OrderList.Any(i => (bool)listBoxSelectedcsList?.SelectedOrderList.Contains(i)))"
                        Change="@(args =>listBoxSelectedcsList.SelectedOrderList = args == true ? listBoxSelectedcsList?.OrderList.ToList():new List<OrderInfo>())" />
                    </HeaderTemplate>
                    <Template Context="data">
                        <RadzenCheckBox TabIndex="-1" TriState="false" Value="@(listBoxSelectedcsList.SelectedOrderList.Contains(data))" InputAttributes="@(new Dictionary<string, object>() { { "aria-label", "Select item" } })"
                        TValue="bool" />
                    </Template>
                </RadzenDataGridColumn>
                <RadzenDataGridColumn Property="OrderNo" Title="处方号" Sortable="false" Filterable="false" Width="5vw" />
                <RadzenDataGridColumn Property="anaesthetistName" Title="医师" Sortable="false" Filterable="false" Width="3vw" />
                <RadzenDataGridColumn Property="PatientName" Title="患者" Sortable="false" Filterable="false" Width="3vw" />
                <RadzenDataGridColumn Property="Sex" Title="性别" Sortable="false" Filterable="false" Width="2vw" />
                <RadzenDataGridColumn Property="DetailInfo.Quantity" Title="数量" Sortable="false" Filterable="false" Width="2vw" />
            </Columns>
        </RadzenDataGrid>
    </div>
</RadzenStack>
@* </RadzenStack> *@
@code {
    private readonly ILog logger = LogManager.GetLogger(typeof(CheckOrder));
    @inject IOrderInfoDao orderInfoDao;
    @inject DialogService dialogService;
    @inject Microsoft.Extensions.Options.IOptions<Pojo.Config.SettingConfig> setting;
    @inject NotificationService _message;
    @inject IReportDataDao reportDataDao;
    @inject IOptions<SettingConfig> setting;
    //bool allowRowSelectOnRowClick = true;
    IEnumerable<ChannelStock> csList;
    IList<ChannelStock> selectedcsList;
    ChannelStock listBoxSelectedcsList = new();
    ChannelStock returnList = new();
    IEnumerable<OrderInfo> orderList;
    IList<OrderInfo> selectedOrderList;
    RadzenListBox<ChannelStock> listBox;
    RadzenDataGrid<OrderInfo> gridOrder;

    //麻醉师集合
    List<Anaesthetist> NamesList = new List<Anaesthetist>();
    Anaesthetist NameInfo;
    BoxModel BoxColor;
    //全部药盒集合
    List<BoxModel> AllBoxList = new List<BoxModel>();
    //药盒集合
    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}
        };
    BoxModel BoxNum;
    bool isLoading;
    int count;
    int[] DrawerNos = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    int status = 0;
    string OrderNo;
    string PatientName;
    DateTime? OrderDate = DateTime.Now;
    DateTime PortOrderDate = DateTime.Now;
    Popup popup;
    RadzenButton button;
    private async Task OnColorChanged(object value)
    {
        if ((((BoxModel)value).BoxNo) == 3)
        {
            BoxList = AllBoxList.Where(bl => bl.BoxName > 30).ToList();
            BoxNum = BoxList.FirstOrDefault();
            await InvokeAsync(StateHasChanged);
        }
        else
        {
            BoxList = AllBoxList.Where(bl => bl.BoxNo == ((BoxModel)value).BoxNo && bl.BoxName <= 30).ToList();
            BoxNum = BoxList.FirstOrDefault();
        }
        await LoadData(null);

    }
    //药箱选中修改
    private async Task OnBoxChanged(object value)
    {
        // BoxList = BoxList.Where(bl => bl.BoxNo == ((BoxModel)value).BoxNo && bl.BoxName == ((BoxModel)value).BoxName).ToList();
        BoxNum = (BoxModel)value;

        await LoadData(null);
    }
    bool? boolHeader = true;
    //全选/反选
    void ChangeHeaderCheckBox(bool? args)
    {
        if (args != null)
        {
            boolHeader = args;
            listBoxSelectedcsList?.OrderList.ToList().ForEach(it => it.ItemIsChecked = (bool)args);
        }
    }
    void OnCheckSeleced(object dete)
    {
        //listBoxSelectedcsList?.OrderList.ToList().Where(it => it.OrderNo == (OrderInfo as (dete).))(oi => oi.ItemIsChecked = true));
    }
    //日期修改
    async Task OnCurrentDateChanged(DateTime args)
    {
        OrderDate = new DateTime(args.Year, args.Month, args.Day);

        await LoadData(null);
    }
    void OnCurrentPortDateChanged(DateTime args)
    {
        PortOrderDate = new DateTime(args.Year, args.Month, args.Day);
    }
    void OnDrugCellClick(DataGridCellMouseEventArgs<ChannelStock> args)
    {

    }
    void OnCellClick(DataGridCellMouseEventArgs<OrderInfo> args)
    {
        if (args.Data.DetailInfo.SetManuNo != null)
        {
            args.Data.DetailInfo.drugManuNo = args.Data.DetailInfo.Drug.Manus.Where(m => m.ManuNo == args.Data.DetailInfo.SetManuNo).FirstOrDefault();
        }
        if (args.Data.DetailInfo.drugManuNo == null)
        {
            args.Data.DetailInfo.drugManuNo = args.Data.DetailInfo.Drug.Manus.FirstOrDefault();
        }
        args.Data.ItemIsChecked = !args.Data.ItemIsChecked;
        // gridOrder.EditRow(args.Data);
    }
    //查询
    async Task Search()
    {
        await LoadData(null);
    }
    //确认
    async Task Confirm()
    {
        csList = csList.ToList();
        List<ChannelStock> checkChannelStock = new();
        string errMessage = string.Empty;
        foreach (var item in csList)
        {
            if (item.SelectedOrderList.Aggregate(0, (a, b) => a + b.DetailInfo.Quantity)>item.Quantity)
            {
                _message.Notify(
                  new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"用药数不可大于库存数，请仔细核对！", Duration = 4000 }
              );
                return;
            }
            int i = 0;
            if (item.OrderList != null && item.SelectedOrderList.Count > 0)
            {
                item.UseQuantity = item.SelectedOrderList.Sum(oi => oi.DetailInfo.Quantity);
                item.OrderQuantity = item.SelectedOrderList.Count;
                // checkChannelStock.Add(item);
                i = 1;
            }
            if (item.DrawerChanneStockList != null && item.DrawerChanneStockList.Any(d => d.ReturnQuantity > 0))
            {
                //还药数量：使用量==库存？还0 ：库存>基数？ （库存数-使用数）>基数？  还 库存数-使用数：0；
                item.ReturnQuantity =
                (item.UseQuantity == item.Quantity) ? 0 :
                (item.Quantity <= item.BaseQuantity) ? 0 :
                ((item.Quantity - item.UseQuantity) > item.BaseQuantity) ?
                (item.Quantity - item.UseQuantity - item.BaseQuantity) : 0;
                //还药库位
                if (item.ReturnQuantity > 0)
                {
                    //药品未在套餐中绑定需要把药还到对应抽屉
                    List<ChannelStock> allDrugStock = await orderInfoDao.GetStockByDRrug(item.DrugId, item.ManuNo, 1);// await _connection.ChannelStock.Where(cs => cs.MachineId == _setting.machineId && cs.DrawerType == 1 && cs.DrugId == csList[i].DrugId && cs.ManuNo == csList[i].ManuNo).OrderBy(cs => cs.Quantity).ToListAsync();
                    if (allDrugStock != null && allDrugStock.Count > 0)
                    {
                        item.DrawerChanneStockList = new();
                        int iReturnQuantity = item.Quantity - item.UseQuantity - item.BaseQuantity;
                        for (int j = 0; j < allDrugStock.Count; j++)
                        {
                            if (allDrugStock[j].BoardType.ToString().Contains("2") && allDrugStock[j].Quantity >= 25)
                                continue;
                            if (allDrugStock[j].BoardType.ToString().Contains("2") && allDrugStock[j].Quantity + item.Quantity - item.UseQuantity > 25)
                            {
                                if (iReturnQuantity <= allDrugStock.Sum(it => it.Quantity))
                                {
                                    for (int q = 0; iReturnQuantity > 0; q++)
                                    {

                                        allDrugStock[j].ReturnQuantity = 25 - allDrugStock[q].Quantity;
                                        item.DrawerChanneStockList.Add(allDrugStock[q]);
                                        iReturnQuantity = iReturnQuantity - allDrugStock[q].ReturnQuantity;
                                        if (iReturnQuantity <= 0)
                                            break;
                                    }
                                }
                                else
                                {
                                    //库位不足，有药品无库位可放
                                    allDrugStock[j].ReturnQuantity = iReturnQuantity;
                                    item.DrawerChanneStockList.Add(allDrugStock[j]);
                                    logger.Info($"还药品【{item.Drug.DrugName}】库位不足，有药品无库位可放");
                                    errMessage += $"库位不足，药品【{item.Drug.DrugName}】无库位可放";
                                    _message.Notify(
                                          new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = errMessage, Duration = 4000 }
                                      );
                                    break; ;
                                }
                            }
                            else
                            {
                                allDrugStock[j].ReturnQuantity = iReturnQuantity;
                                item.DrawerChanneStockList.Add(allDrugStock[j]);
                                break;
                            }
                        }
                    }
                }
                // checkChannelStock.Add(item);
                i = 1;
            }

            //还空瓶数
            item.EmptyQuantity = item.SelectedOrderList.Sum(oi => oi.DetailInfo.Quantity);
            if (item.EmptyQuantity > 0)
            {
                //还空瓶库位
                //查询还空瓶库位
                //checkChannelStock[i].EmptyStock;

                List<ChannelStock> allDrugStock = await orderInfoDao.GetStockByDRrug(item.DrugId, item.ManuNo, 2);// await _connection.ChannelStock.Where(cs => cs.MachineId == _setting.machineId && cs.DrawerType == 1 && cs.DrugId == csList[i].DrugId && cs.ManuNo == csList[i].ManuNo).OrderBy(cs => cs.Quantity).ToListAsync();
                if (allDrugStock.Count > 0)
                {
                    item.EmptyStock = allDrugStock.FirstOrDefault();
                    item.EmptyStock.ReturnQuantity = item.EmptyQuantity;
                    i = 1;
                }
                // checkChannelStock.Add(item);
            }
            if (i == 1)
            {
                checkChannelStock.Add(item);
            }
        }
        if (errMessage.Length > 0)
        {
            return;
        }
        if (checkChannelStock == null || checkChannelStock.Count <= 0)
        {
            _message.Notify(
                   new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"无可操作的数据", Duration = 4000 }
               );
            return;
        }
        // //弹出确认提示框
        var b = await dialogService.OpenAsync<CheckOrderConfirmDialog>(
           $"核对确认",
         new Dictionary<string, object>() { { "csList", checkChannelStock } },
         new DialogOptions() { Width = "90vw", Resizable = true, Draggable = true, ShowClose = false });
        // if (b)
        // {
        //     bool bResult = await orderInfoDao.CheckOrderInfoByChannelStock(csList.ToList(), BoxNum);
        //     if (bResult)
        //     {
        //         _message.Notify(
        //                         new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "提示", Detail = $"处方已核对完成", Duration = 4000 }
        //                     );
        //         await LoadData(null);
        //     }
        //     else
        //     {
        //         _message.Notify(
        //                       new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"处方已核对失败", Duration = 4000 }
        //                );
        //     }
        // }
        if (b)
        {
            LoadData(null);
        }

    }
    //导处方
    async Task AddOrderMethod()
    {
        var b = await dialogService.OpenAsync<CheckOrderImportDialog>(
           $"导入处方信息",
         new Dictionary<string, object>() { { "boxModel", BoxNum } },
         new DialogOptions() { Width = "80vw", Resizable = true, Draggable = true, ShowClose = false });
        if (b != null)
        {
            try
            {

                List<OrderInfo> importOrderInfo = b;
                if (importOrderInfo.Count > 0)
                {
                    string errorMessage = string.Empty;
                    for (int i = 0; i < importOrderInfo.Count; i++)
                    {
                        if (!(bool)listBoxSelectedcsList?.OrderList.Contains(importOrderInfo[i]))
                        {
                            if (csList.Where(c => c.DrugId == importOrderInfo[i].DetailInfo.DrugId && c.ManuNo == importOrderInfo[i].DetailInfo.SetManuNo).FirstOrDefault() == null)
                            {
                                errorMessage += $"处方{importOrderInfo[i].OrderNo}导入失败，药品{importOrderInfo[i].DetailInfo.Drug.DrugName}不存在或批次{importOrderInfo[i].DetailInfo.SetManuNo}不存在";
                            }
                            else
                            {
                                csList.Where(c => c.DrugId == importOrderInfo[i].DetailInfo.DrugId && c.ManuNo == importOrderInfo[i].DetailInfo.SetManuNo).FirstOrDefault()?.SelectedOrderList.Add(importOrderInfo[i]);
                                //csList.Where(c => c.DrugId == importOrderInfo[i].DetailInfo.DrugId && c.ManuNo == importOrderInfo[i].DetailInfo.SetManuNo).FirstOrDefault()?.OrderList.Add(importOrderInfo[i]);
                            }
                        }
                        csList = csList;
                    }
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        _message.Notify(
                             new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = errorMessage, Duration = 4000 }
                      );
                        return;
                    }
                    else
                    {
                        StateHasChanged(); // 刷新UI
                    }
                }
            }
            catch (Exception)
            {

            }

        }
    }

    PageData<ChannelStock> result;
    protected override async Task OnInitializedAsync()
    {
        BoxColor = BoxColorList.FirstOrDefault();
        AllBoxList = await orderInfoDao.GetOperationNum(0);
        BoxList = AllBoxList.Where(bl => bl.BoxNo == BoxColor.BoxNo && bl.BoxName <= 30).ToList();
        BoxNum = AllBoxList.FirstOrDefault();
        await base.OnInitializedAsync();
    }
    async Task LoadData(LoadDataArgs args)
    {
        string? roomName = BoxNum == null ? "" : setting.Value.roomName + BoxNum.BoxName.ToString().PadLeft(2, '0');
        result = await orderInfoDao.GetAllOrderInfoDrugByBox(BoxNum, roomName, OrderDate);
        isLoading = true;
        csList = result.Desserts;
        if (csList != null && csList.Count() > 0)
        {
            listBoxSelectedcsList = csList.ElementAt(0);
        }
        count = result.TotalDesserts;
        isLoading = false;
        StateHasChanged(); // 刷新UI
    }
    //麻醉药品使用登记本导出
    async Task StockExport()
    {
        if (PortOrderDate == DateTime.MinValue)
        {
            _message.Notify(
                           new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"请选择处方时间再导出", Duration = 4000 }
                    );
            return;
        }
        PageData<ReportUsageDateInfo> pageData = await reportDataDao.GetOrderInfoData(PortOrderDate);
        GridReportUtil.PrintReport("Usage_Temp.grf", pageData);
    }
    // protected override async Task OnInitializedAsync()
    // {
    //     await base.OnInitializedAsync();

    //     // orderInfos = dbContext.Employees;

    //     var result = await orderInfoDao.GetAllOrderInfo(OrderNo, OrderDate, args.Top, args.Skip);
    //     // Update the Data property
    //     orderInfos = result.Desserts;
    //     // Update the count
    //     count = result.TotalDesserts;

    //     isLoading = false;
    // }
}