@page "/Box/Check"
@using MasaBlazorApp3.Pojo.Config
@using MasaBlazorApp3.Report
@using Radzen.Blazor.Rendering

<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);
    }
</style>

<RadzenStack Orientation="Orientation.Horizontal">
    @*   <div class="col-4 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;overflow:auto">
            @foreach (int i in DrawerNos)
            {
                <RadzenButton class="col-5" Style="margin-bottom:5px" Click="@(() => SelectDrawer(i))" Text="@i.ToString()" Disabled="@(status > 0)" Shade="Shade.Light" Variant="@(drawerNo != i ? Variant.Outlined : Variant.Flat)" />

            }
        </div>
    </div> *@
    @*     <div class="col-2 row justify-content-center align-items-center text-center">
        <div class="row justify-content-around align-items-center" style="height:600px;overflow:auto">
            @foreach (int i in DrawerNos)
            {
                <RadzenButton class="col-12" Style="margin-bottom:5px" Click="@(() => SelectDrawer(i))" Text="@i.ToString()" Disabled="@(status > 0)" Shade="Shade.Light" Variant="@(drawerNo != i ? Variant.Outlined : Variant.Flat)" />

            }
        </div>
    </div> *@
    <div class="col-12">
        <form onsubmit="@(() => grid.Reload())">
            <RadzenFieldset Text="查询">
                @* <RadzenStack Orientation="Orientation.Horizontal" Gap="1rem"> *@
                <RadzenRow AlignItems="AlignItems.Center">
                    <RadzenColumn Size="6">
                        <RadzenLabel Text="麻醉师" Component="NamesList" />
                        <RadzenDropDownDataGrid AllowVirtualization="true" Name="NamesList" TValue="Anaesthetist" Data="@NamesList" @bind-Value="Name"
                                                Style="width:100%; display: block;" AllowFilteringByAllStringColumns="true" TextProperty="Name">

                            <Columns>
                                <RadzenDropDownDataGridColumn Property="Name" Title="麻醉师" Sortable="false" />
                            </Columns>
                        </RadzenDropDownDataGrid>
                    </RadzenColumn>

                    <RadzenColumn Size="6">
                        <RadzenLabel Text="处方号" Component="OrderNo" />
                        <RadzenTextBox @bind-Value="OrderNo" Style="width: 100%;" Name="OrderNo"></RadzenTextBox>

                    </RadzenColumn>
                </RadzenRow>
                <RadzenRow AlignItems="AlignItems.Center">
                    <RadzenColumn Size="6">
                        <RadzenLabel Text="处方时间" Component="OrderDate" />
                        <RadzenDatePicker DateFormat="yyyy-MM-dd" CurrentDateChanged="@OnCurrentDateChanged" AllowClear @bind-Value="OrderDate" Style="width: 100%;" Name="OrderDate" />
                    </RadzenColumn>
                    <RadzenColumn Size="6" Style="margin-top:0.5rem">
                        <RadzenButton Size="ButtonSize.Medium" ButtonType="ButtonType.Submit" IsBusy="isLoading" Icon="search" Text="查询" />
                        <RadzenButton Size="ButtonSize.Medium" Click="reloadGrid" IsBusy="isLoading" Icon="refresh" Text="重置" ButtonStyle="ButtonStyle.Warning" />
                    </RadzenColumn>
                </RadzenRow>
                @* </RadzenStack> *@
            </RadzenFieldset>
            <RadzenStack Orientation="Orientation.Horizontal" Gap="1rem" Style="margin:0.5rem">
                <RadzenLabel Text="核对药箱" Component="BoxList" Style="margin:0.5rem" />
                <RadzenDropDownDataGrid AllowVirtualization="true" Name="BoxList" TValue="BoxModel" Data="@BoxList" @bind-Value="BoxNum"
                                        AllowFilteringByAllStringColumns="true" TextProperty="BoxName">

                    <Columns>
                        <RadzenDropDownDataGridColumn Property="BoxName" Title="药箱号" Sortable="false" />
                    </Columns>
                </RadzenDropDownDataGrid>
                <RadzenButton Size="ButtonSize.Medium" Click="Confirm" ButtonType="ButtonType.Button" IsBusy="isLoading" Icon="check_circle" Text="确认" />
                <RadzenButton 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>
            </RadzenStack>
        </form>
        <RadzenDataGrid @ref="grid" AllowRowSelectOnRowClick="@allowRowSelectOnRowClick" AllowFiltering="true" LoadData="@LoadData"
                        FilterPopupRenderMode="PopupRenderMode.OnDemand" FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive"
                        Data="@orderInfos" ColumnWidth="200px" IsLoading="@isLoading" Count="@count" EmptyText="无数据"
                        SelectionMode="DataGridSelectionMode.Multiple" @bind-Value=@selectedOrderInfos
                        CellClick="@((DataGridCellMouseEventArgs<OrderInfo> args) => OnCellClick(args))"
                        AllowPaging="true" PageSize="10" PagerHorizontalAlign="HorizontalAlign.Left" ShowPagingSummary="true" PagingSummaryFormat="{0}/{1} 共{2}条数据">
            <Columns>
                <RadzenDataGridColumn Sortable="false" Filterable="false" Width="4rem">
                    <HeaderTemplate>
                        <RadzenCheckBox TabIndex="-1" TriState="false" TValue="bool?" InputAttributes="@(new Dictionary<string, object>() { { "aria-label", "Select all items" } })"
                                        Value="@(selectedOrderInfos == null || selectedOrderInfos?.Any() != true ? false : !orderInfos.All(i => selectedOrderInfos.Contains(i)) ? null : orderInfos.Any(i => selectedOrderInfos.Contains(i)))"
                                        Change="@(args => selectedOrderInfos = args == true ? orderInfos.ToList() : null)" />
                    </HeaderTemplate>
                    <Template Context="data">
                        <RadzenCheckBox TabIndex="-1" TriState="false" Value="@(selectedOrderInfos != null && selectedOrderInfos.Contains(data))" InputAttributes="@(new Dictionary<string, object>() { { "aria-label", "Select item" } })"
                                        TValue="bool" Change="@(args => { if (!allowRowSelectOnRowClick) { grid.SelectRow(data); } })" />
                    </Template>
                </RadzenDataGridColumn>
                <RadzenDataGridColumn Property="PatientName" Title="姓名" Sortable="false" Filterable="false" Width="4rem" />
                <RadzenDataGridColumn Property="Sex" Title="性别" Sortable="false" Filterable="false" Width="2rem" />
                <RadzenDataGridColumn Property="OrderNo" Title="单号" Sortable="false" Filterable="false" Width="8rem" />
                <RadzenDataGridColumn Property="DetailInfo.Drug.DrugName" Title="药品名称" FormatString="{0:d}" Sortable="false" Filterable="false" Width="8rem" />
                @* <Template Context="DetailInfo">
                       @for (int i = 0; i < DetailList.DetailList.Count; i++)
                        {
                            OrderDetail orderDetail = DetailList.DetailList[i]; *@
                @*     <RadzenText TextStyle="TextStyle.Subtitle2" class="rz-mb-0">@DetailInfo.Drug.DrugName</RadzenText>
                    }
                    </Template> 
                </RadzenDataGridColumn>*@
                @*  <RadzenDataGridColumn Property="Detail.SetManuNo" Title="药品批次" Sortable="false" Filterable="false" Width="8rem">
                    <Template Context="DetailList">
                        @for (int i = 0; i < DetailList.DetailList.Count; i++)
                        {
                            OrderDetail orderDetail = DetailList.DetailList[i];
                            <RadzenText TextStyle="TextStyle.Subtitle2" class="rz-mb-0">@orderDetail.SetManuNo</RadzenText>
                        }
                    </Template>
                </RadzenDataGridColumn> *@
                <RadzenDataGridColumn Width="110px" Title="批次" Property="DetailInfo.SetManuNo">
                    @*            <Template Context="DetailInfo">
                        <RadzenText TextStyle="TextStyle.Subtitle2" class="mb-0">@DetailInfo.DetailInfo.SetManuNo</RadzenText>

                        @if (DetailInfo.DetailInfo.SetManuNo != null )
                        {
                            <RadzenText TextStyle="TextStyle.Caption">
                                @DetailInfo.DetailInfo.SetManuNo
                            </RadzenText>
                        }
                    </Template> *@
                    <EditTemplate Context="DetailInfo">
                        <RadzenDropDown TValue="DrugManuNo" Name="ManuNo" @bind-Value="DetailInfo.DetailInfo.drugManuNo" Data="DetailInfo.DetailInfo.Drug.Manus" Style="width:100%; display: block;">
                            <Template>
                                <RadzenText TextStyle="TextStyle.Subtitle2" class="mb-0">@((context as DrugManuNo)?.ManuNo)</RadzenText>
                                @if ((context as DrugManuNo).EffDate != null && (context as DrugManuNo).EffDate.ToString().Length > 10)
                                {

                                    <RadzenText TextStyle="TextStyle.Caption">@((context as DrugManuNo).EffDate.ToString().Substring(0, 10))</RadzenText>
                                }
                                else
                                {

                                    <RadzenText TextStyle="TextStyle.Caption">@((context as DrugManuNo)?.EffDate)</RadzenText>
                                }
                            </Template>
                            <ValueTemplate>
                                <RadzenStack Orientation="Orientation.Horizontal">
                                    <RadzenText TextStyle="TextStyle.Subtitle2" class="mb-0">@((context as DrugManuNo)?.ManuNo)</RadzenText>
                                    @if ((context as DrugManuNo).EffDate != null && (context as DrugManuNo).EffDate.ToString().Length > 10)
                                    {

                                        <RadzenText TextStyle="TextStyle.Caption">@((context as DrugManuNo).EffDate.ToString().Substring(0, 10))</RadzenText>
                                    }
                                    else
                                    {

                                        <RadzenText TextStyle="TextStyle.Caption">@((context as DrugManuNo)?.EffDate)</RadzenText>
                                    }
                                </RadzenStack>
                            </ValueTemplate>
                        </RadzenDropDown>
                        <RadzenRequiredValidator Text="请选择批次" Component="ManuNo" Popup="true" />
                    </EditTemplate>
                </RadzenDataGridColumn>
                <RadzenDataGridColumn Property="DetailInfo.Quantity" Title="数量" Sortable="false" Filterable="false" Width="2rem" />
                @*  <Template Context="DetailInfo">
                       @for (int i = 0; i < DetailList.DetailList.Count; i++)
                        {
                            OrderDetail orderDetail = DetailList.DetailList[i];
                            <RadzenText TextStyle="TextStyle.Subtitle2" class="rz-mb-0">@orderDetail.Quantity</RadzenText>
                        }
                    </Template>
                </RadzenDataGridColumn> *@
            </Columns>
        </RadzenDataGrid>
    </div>
</RadzenStack>
@code {
    @inject IOrderInfoDao orderInfoDao;
    @inject DialogService dialogService;
    @inject Microsoft.Extensions.Options.IOptions<Pojo.Config.SettingConfig> setting;
    @inject NotificationService _message;
    @inject IReportDataDao reportDataDao;

    bool allowRowSelectOnRowClick = true;
    IEnumerable<OrderInfo> orderInfos;
    IList<OrderInfo> selectedOrderInfos;
    RadzenDataGrid<OrderInfo> grid;
    //麻醉师集合
    List<Anaesthetist> NamesList = new List<Anaesthetist>();
    Anaesthetist Name;
    //麻醉师集合
    List<BoxModel> BoxList = new List<BoxModel>();
    BoxModel BoxNum;
    bool isLoading;
    int count;
    int[] DrawerNos = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    int status = 0;
    string OrderNo;
    DateTime? OrderDate = null;
    DateTime PortOrderDate = DateTime.Now;
    Popup popup; 
    RadzenButton button;
    void OnCurrentDateChanged(DateTime args)
    {
        OrderDate = new DateTime(args.Year, args.Month, args.Day);
    }
    void OnCurrentPortDateChanged(DateTime args)
    {
        PortOrderDate = new DateTime(args.Year, args.Month, args.Day);
    }
    //重置
    async Task reloadGrid()
    {
        OrderNo = "";
        OrderDate = DateTime.MinValue;
        await grid.Reload();
    }
    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();
        }
        grid.EditRow(args.Data);
    }
    //确认
    async Task Confirm()
    {
        if (selectedOrderInfos.Any(it => it.DetailInfo.drugManuNo == null))
        {
            _message.Notify(
                         new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"请选择批次信息", Duration = 4000 }
                     );
            return;
        }
        bool bResult = await orderInfoDao.CheckOrderInfo(selectedOrderInfos, BoxNum.BoxNo);
        if (bResult)
        {
            _message.Notify(
                            new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "提示", Detail = $"处方已核对完成", Duration = 4000 }
                        );
            await GetInitialDate();
            await grid.Reload();
        }
        else
        {
            _message.Notify(
                          new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"处方已核对失败", Duration = 4000 }
                   );
        }
    }
    PageData<OrderInfo> result;
    protected override async Task OnInitializedAsync()
    {
        await GetInitialDate();
        await base.OnInitializedAsync();
    }
    async Task GetInitialDate()
    {
         result = await orderInfoDao.GetAllOrderInfo(null, null, null, null, null);
        List<string> nameList = result.Desserts.Select(it => it.anaesthetistName).Distinct().ToList();
        NamesList = nameList.Select(it => new Anaesthetist { Name = it }).ToList();
        Name = NamesList.FirstOrDefault();        
    }
    async Task LoadData(LoadDataArgs args)
    {
        if (result != null)
        {
            isLoading = true;
            orderInfos = result.Desserts;
            // Update the count
            count = result.TotalDesserts;
            // Update the Data property
            if (Name != null)
            {
                orderInfos = orderInfos.Where(it => it.anaesthetistName == Name.Name);
                count = orderInfos.Count();
            }
            if(OrderDate != null && OrderDate != DateTime.MinValue)
            {
                orderInfos = orderInfos.Where(it => it.ChargeDate.Date == OrderDate.Value.Date);
                // Update the count
                count = orderInfos.Count();
            }
            if(!string.IsNullOrEmpty(OrderNo))
            {
                orderInfos = orderInfos.Where(it => it.OrderNo.Contains(OrderNo));
                // Update the count
                count = orderInfos.Count();
            }
            if (Name != null && OrderDate != null && OrderDate != DateTime.MinValue && !string.IsNullOrEmpty(OrderNo))
            {
                orderInfos = orderInfos.Where(it => it.anaesthetistName == Name.Name && it.ChargeDate.Date == OrderDate.Value.Date && it.OrderNo.Contains(OrderNo));
                // Update the count
                count = orderInfos.Count();
            }
            orderInfos = orderInfos.Skip(args.Skip.Value).Take(args.Top.Value).ToList();

            //查找该麻醉师对应的手术室
            //List<string> roomNameList = orderInfos.Select(it => it.RoomName).Distinct().ToList();
            List<int> roomNameList = orderInfos.Select(it => Convert.ToInt32(it.RoomName.Substring(it.RoomName.Length - 2, 2))).ToList();
            BoxList = await orderInfoDao.GetDrawerNumByOperationNum(setting.Value.machineId, roomNameList); //roomNameList.Select(it => new BoxModel { BoxName = it, BoxNo = Convert.ToInt32(it.Substring(it.Length - 2, 2)) }).ToList();

            BoxNum = BoxList.FirstOrDefault();

            isLoading = false;

        }
    }
    //麻醉药品使用登记本导出
    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;
    // }
}