@page "/take/self"
<div class="container-fluid">
    <div class="row">
        <div class="col-12 mb-4">

            <RadzenTemplateForm Data="@orderInfo" Submit="@(((OrderInfo args) => { Submit(args); }))">
                <RadzenFieldset Text="手写处方">
                    <RadzenRow Gap="1rem">
                        <RadzenColumn Size="4">
                            <RadzenRow AlignItems="AlignItems.Center">
                                <RadzenColumn Size="4">
                                    <RadzenLabel Text="处方号" Component="OrderNo" />
                                </RadzenColumn>
                                <RadzenColumn Size="8">
                                    <RadzenTextBox @bind-Value="orderInfo.OrderNo" Style="width: 100%;" Name="OrderNo"></RadzenTextBox>
                                    <RadzenRequiredValidator Text="请输入处方号" Component="OrderNo" />
                                </RadzenColumn>
                            </RadzenRow>
                        </RadzenColumn>
                        <RadzenColumn Size="4">
                            <RadzenRow AlignItems="AlignItems.Center">
                                <RadzenColumn Size="4">
                                    <RadzenLabel Text="处方时间" Component="OrderDate" />
                                </RadzenColumn>
                                <RadzenColumn Size="8">
                                    <RadzenDatePicker DateFormat="yyyy-MM-dd" CurrentDateChanged="@OnCurrentDateChanged"
                                     ShowSeconds="true"
                                                      @bind-Value="orderInfo.ChargeDate" Style="width: 100%;" Name="OrderDate" />
                                    <RadzenRequiredValidator Text="请输入处方时间" Component="OrderDate" />
                                </RadzenColumn>
                            </RadzenRow>
                        </RadzenColumn>
                        <RadzenColumn Size="4">
                            <RadzenRow AlignItems="AlignItems.Center">
                                <RadzenColumn Size="4">
                                    <RadzenLabel Text="患者姓名" Component="PatientName" />
                                </RadzenColumn>
                                <RadzenColumn Size="8">
                                    <RadzenTextBox @bind-Value="orderInfo.PatientName" Style="width: 100%;" Name="PatientName"></RadzenTextBox>
                                    <RadzenRequiredValidator Text="请输入患者姓名" Component="PatientName" />
                                </RadzenColumn>
                            </RadzenRow>
                        </RadzenColumn>
                        <RadzenColumn Size="2">
                            <RadzenRow AlignItems="AlignItems.Center">
                                <RadzenColumn Size="4">
                                    <RadzenLabel Text="性别" Component="Sex" />
                                </RadzenColumn>
                                <RadzenColumn Size="8">
                                    <RadzenTextBox @bind-Value="orderInfo.Sex" Style="width: 100%;" Name="Sex"></RadzenTextBox>
                                    <RadzenRequiredValidator Text="请输入患者性别" Component="Sex" />
                                </RadzenColumn>
                            </RadzenRow>
                        </RadzenColumn>
                        <RadzenColumn Size="2">
                            <RadzenRow AlignItems="AlignItems.Center">
                                <RadzenColumn Size="4">
                                    <RadzenLabel Text="年龄" Component="Age" />
                                </RadzenColumn>
                                <RadzenColumn Size="8">
                                    <RadzenTextBox @bind-Value="orderInfo.Age" Style="width: 100%;" Name="Age"></RadzenTextBox>
                                    <RadzenRequiredValidator Text="请输入患者年龄" Component="Age" />
                                </RadzenColumn>
                            </RadzenRow>
                        </RadzenColumn>
                        <RadzenColumn Size="4">
                            <RadzenRow AlignItems="AlignItems.Center">
                                <RadzenColumn Size="4">
                                    <RadzenLabel Text="处方医生" Component="DoctorName" />
                                </RadzenColumn>
                                <RadzenColumn Size="8">
                                    <RadzenTextBox @bind-Value="orderInfo.DoctorName" Style="width: 100%;" Name="DoctorName"></RadzenTextBox>
                                    <RadzenRequiredValidator Text="请输入处方医生" Component="DoctorName" />
                                </RadzenColumn>
                            </RadzenRow>
                        </RadzenColumn>
                        <RadzenColumn Size="4">
                            <RadzenRow AlignItems="AlignItems.Center">
                                <RadzenColumn Size="4">
                                    <RadzenLabel Text="科室" Component="DeptName" />
                                </RadzenColumn>
                                <RadzenColumn Size="8">
                                    <RadzenTextBox @bind-Value="orderInfo.DeptName" Style="width: 100%;" Name="DeptName"></RadzenTextBox>
                                    <RadzenRequiredValidator Text="请输入科室" Component="DeptName" />
                                </RadzenColumn>
                            </RadzenRow>
                        </RadzenColumn>
                        <RadzenColumn Size="6">
                            <RadzenRow AlignItems="AlignItems.Center">
                                <RadzenColumn Size="2">
                                    <RadzenLabel Text="诊断" Component="Disease" />
                                </RadzenColumn>
                                <RadzenColumn Size="10">
                                    <RadzenTextBox @bind-Value="orderInfo.Disease" Style="width: 100%;" Name="Disease"></RadzenTextBox>
                                    <RadzenRequiredValidator Text="请输入诊断" Component="Disease" />
                                </RadzenColumn>
                            </RadzenRow>
                        </RadzenColumn>
                        <RadzenColumn Size="6">
                            <RadzenStack Orientation="Orientation.Horizontal" AlignItems="AlignItems.Center" JustifyContent="JustifyContent.SpaceBetween">
                                <RadzenButton Size="ButtonSize.Large" ButtonType="ButtonType.Submit" Disabled="@(detailsToInsert.Count() > 0 || detailsToUpdate.Count() > 0)" Text="确定" />
                                <RadzenButton Size="ButtonSize.Large" Icon="add_circle_outline" ButtonStyle="ButtonStyle.Success" Click="@InsertRow" Disabled="@(detailsToInsert.Count() > 0)" Text="添加" />
                            </RadzenStack>
                        </RadzenColumn>
                    </RadzenRow>
                </RadzenFieldset>
            </RadzenTemplateForm>
        </div>
        <div class="col-12 mb-4">

            <RadzenDataGrid @ref="grid"
            EmptyText="请添加手写处方详情"
            Data="@orderDetails"
            EditMode="DataGridEditMode.Single"
            RowUpdate="@((OrderDetail od) => { OnUpdateRow(od); })" RowCreate="@((OrderDetail od) => { OnCreateRow(od); })"
            AllowColumnResize="true" AllowAlternatingRows="false"
            SelectionMode="DataGridSelectionMode.Single">
                <Columns>
                    <RadzenDataGridColumn Title="药品名称" Property="Drug.DrugName">
                        <EditTemplate Context="od">
                            @* <RadzenDropDown Name="Drug" TValue="DrugInfo" @bind-Value="od.Drug" Data="@drugInfos" Style="width:100%; display: block;"  /> *@
                            <RadzenDropDownDataGrid AllowVirtualization="true" Name="Drug" TValue="DrugInfo" @bind-Value="od.Drug" Data="@drugInfos" Style="width:100%; display: block;" AllowFilteringByAllStringColumns="true">
                                <Columns>
                                    <RadzenDropDownDataGridColumn Property="DrugId" Title="药品编码" />
                                    <RadzenDropDownDataGridColumn Property="DrugName" Width="120px" Title="名称" />
                                    <RadzenDropDownDataGridColumn Property="DrugSpec" Title="规格" />
                                    <RadzenDropDownDataGridColumn Property="StockQuantity" Title="库存" Frozen="true" FrozenPosition="FrozenColumnPosition.Right" />
                                </Columns>
                            </RadzenDropDownDataGrid>
                            <RadzenCustomValidator Style="position: absolute;z-index: 9999;" Component="Drug" Validator="@(() => !String.IsNullOrEmpty(od.Drug.DrugId ))" Text="请选择药品" />
                            <RadzenCustomValidator Component="Drug" Validator="@(() => ValidateDrug(od.Drug))" Text="已经选择的药品不能再次选择" />
                        </EditTemplate>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Title="规格" Property="Drug.DrugSpec"></RadzenDataGridColumn>
                    <RadzenDataGridColumn Title="数量" Property="Quantity">
                        <EditTemplate Context="od">
                            <RadzenNumeric Style="width:100%; display: block;" Name="Quantity" @bind-Value=@od.Quantity />
                            <RadzenNumericRangeValidator Style="position: absolute;z-index: 9999;" Min="1" Max="@od.Drug.StockQuantity" Text="请填写正确的取出数量" Component="Quantity" />
                        </EditTemplate>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Context="detail" Filterable="false" Sortable="false" TextAlign="TextAlign.Right" Frozen="true" FrozenPosition="FrozenColumnPosition.Right">
                        <Template Context="detail">
                            <RadzenButton Icon="edit" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@(args => EditRow(detail))" @onclick:stopPropagation="true">
                            </RadzenButton>

                            <RadzenButton ButtonStyle="ButtonStyle.Danger" Icon="delete" Variant="Variant.Flat" Shade="Shade.Lighter" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@(args => DeleteRow(detail))" @onclick:stopPropagation="true">
                            </RadzenButton>
                        </Template>
                        <EditTemplate Context="detail">
                            <RadzenButton Icon="check" ButtonStyle="ButtonStyle.Success" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@((args) => SaveRow(detail))" aria-label="Save">
                            </RadzenButton>
                            <RadzenButton Icon="close" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@((args) => CancelEdit(detail))" aria-label="Cancel">
                            </RadzenButton>
                            <RadzenButton ButtonStyle="ButtonStyle.Danger" Icon="delete" Variant="Variant.Flat" Shade="Shade.Lighter" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@(args => DeleteRow(detail))" aria-label="Delete">
                            </RadzenButton>
                        </EditTemplate>
                    </RadzenDataGridColumn>
                </Columns>
            </RadzenDataGrid>
        </div>
    </div>
</div>
@code {
    @inject IChannelListDao channelListDao;
    @inject IDrugInfoDao drugInfoDao;
    @inject NotificationService _message
    @inject DialogService dialogService;
    RadzenDataGrid<OrderDetail> grid;
    List<OrderDetail> orderDetails = new();

    List<DrugInfo> drugInfos = new();

    List<OrderDetail> detailsToInsert = new();
    List<OrderDetail> detailsToUpdate = new();


    OrderInfo orderInfo = new OrderInfo()
        {
            OrderDate = DateTime.Now
        };



    void Reset()
    {
        detailsToInsert.Clear();
        detailsToUpdate.Clear();
    }
    void Reset(OrderDetail orderDetail)
    {
        detailsToInsert.Remove(orderDetail);
        detailsToUpdate.Remove(orderDetail);
    }

    async Task InsertRow()
    {

        Reset();
        var orderDetail = new OrderDetail();
        detailsToInsert.Add(orderDetail);
        await grid.InsertRow(orderDetail);
    }

    async Task EditRow(OrderDetail orderDetail)
    {

        Reset();

        detailsToUpdate.Add(orderDetail);
        await grid.EditRow(orderDetail);
    }

    async Task SaveRow(OrderDetail orderDetail)
    {
        await grid.UpdateRow(orderDetail);
    }

    void CancelEdit(OrderDetail orderDetail)
    {
        Reset(orderDetail);

        grid.CancelEditRow(orderDetail);
        grid.Reload();
    }

    async Task DeleteRow(OrderDetail orderDetail)
    {
        Reset(orderDetail);
        orderDetails.Remove(orderDetail);
        grid.CancelEditRow(orderDetail);
        await grid.Reload();
    }

    void OnUpdateRow(OrderDetail orderDetail)
    {
        Reset(orderDetail);

        grid.Reload();
    }

    void OnCreateRow(OrderDetail orderDetail)
    {
        // 数据库添加用户
        detailsToInsert.Remove(orderDetail);
        orderDetails.Add(orderDetail);
        grid.Reload();
    }

    async void Submit(OrderInfo orderInfo)
    {
        if (orderDetails.Count == 0)
        {
            _message.Notify(
                new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"请添加用药详情", Duration = 3000 }
            );
        }
        else
        {
            //弹出待取药品所在库位、库存信息
            var b = await dialogService.OpenAsync<SelfTakeDialog>(
                $"取药详情",
              new Dictionary<string, object>() { { "order", orderInfo }, { "orderDetails", orderDetails } },
              new DialogOptions() { Width = "85vw", Resizable = true, Draggable = true, ShowClose = false }
            );
            if (b)
            {
                _message.Notify(
                new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "提示", Detail = $"取药完成", Duration = 3000 }
            );
            }
        }
    }
    async Task reloadGrid()
    {

        await grid.Reload();
    }
    bool ValidateDrug(DrugInfo drugInfo)
    {
        return !orderDetails.Any(od => od.Drug.DrugId.Equals(drugInfo?.DrugId));
    }

    protected override async Task OnInitializedAsync()
    {
        drugInfos = await drugInfoDao.GetAllDrugAndStock();

        base.OnInitializedAsync();
    }

    void OnCurrentDateChanged(DateTime args)
    {
        orderInfo.ChargeDate = new DateTime(args.Year, args.Month, args.Day, args.Hour, args.Minute, args.Second);
    }
}
