@page "/Box/Plan"
<style>
    .rz-custom-header {
        width: 100%;
    }
</style>

<div class="container-fluid">
    <div class="row">
        <div class="col-12  mb-4">
            <RadzenFieldset>
                <RadzenStack Orientation="Orientation.Horizontal" Gap="1rem">
                    <RadzenRow AlignItems="AlignItems.Center">
                        <RadzenColumn Size="12" Style="margin-top:12px">
                            <RadzenButton Size="ButtonSize.Large" Click="reloadGrid" IsBusy="isLoading" Icon="refresh" Text="刷新" ButtonStyle="ButtonStyle.Warning" />
                            <RadzenButton Size="ButtonSize.Large" ButtonStyle="ButtonStyle.Success" Icon="add_circle_outline" Click="@InsertPlanRow" Text="新增套餐" />
                        </RadzenColumn>
                    </RadzenRow>
                </RadzenStack>
            </RadzenFieldset>
        </div>
        <div class="col-4  mb-4">
            <RadzenDataGrid @ref="grid"
                            LoadData="@LoadData"
                            @bind-Value="@SelectedPlan"
                            IsLoading="@isLoading"
                            Count="@count"
                            EmptyText="无数据"
                            Data="@_forecasts"
                            AllowColumnResize="true" AllowAlternatingRows="false"
                            SelectionMode="DataGridSelectionMode.Single" RowUpdate="@((Plan di) => { OnUpdatePlanRow(di); })" RowCreate="@((Plan di) => { OnCreatePlanRow(di); })"
                            AllowPaging="true" PageSize="10" PagerHorizontalAlign="HorizontalAlign.Left" ColumnWidth="100px" ShowPagingSummary="true" PagingSummaryFormat="{0}/{1} 共{2}条数据">
                <Columns>
                    <RadzenDataGridColumn Frozen="true" Title="套餐名称" Property="Name">
                        <EditTemplate Context="planInfo">
                            <RadzenTextBox Name="Name" @bind-Value="planInfo.Name" Style="width:100%; display: block;" />
                            <RadzenRequiredValidator Text="请填写套餐名称" Component="Name" Popup="true" />
                        </EditTemplate>
                    </RadzenDataGridColumn>
                    @*   <RadzenDataGridColumn Width="200px" Title="套餐描述" Property="Description">
                        <EditTemplate Context="planInfo">
                            <RadzenTextBox Name="Description" @bind-Value="planInfo.Description" Style="width:100%;display:block;" />
                            <RadzenRequiredValidator Text="请填写套餐描述" Component="Description" Popup="true" />
                        </EditTemplate>
                    </RadzenDataGridColumn> *@

                    <RadzenDataGridColumn Context="planInfo" Title="操作" Filterable="false" Sortable="false" TextAlign="TextAlign.Left" Frozen="true" FrozenPosition="FrozenColumnPosition.Right" Width="5rem">
                        <Template Context="planInfo">
                            <RadzenButton Icon="edit" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@(args => EditPlanRow(planInfo))" @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 => DeletePlanRow(planInfo))" @onclick:stopPropagation="true">
                            </RadzenButton>
                        </Template>
                        <EditTemplate Context="planInfo">
                            <RadzenButton Icon="check" ButtonStyle="ButtonStyle.Success" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@((args) => SavePlanRow(planInfo))" aria-label="Save">
                            </RadzenButton>
                            <RadzenButton Icon="close" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@((args) => CancelPlanEdit(planInfo))" 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 => DeletePlanRow(planInfo))" aria-label="Delete">
                            </RadzenButton>
                        </EditTemplate>
                    </RadzenDataGridColumn>
                </Columns>
            </RadzenDataGrid>
        </div>
        <div class="col-8  mb-4">
            <RadzenDataGrid @ref="PlanDetailsGrid" EmptyText="无数据"
                            Data="@(SelectedPlan?.FirstOrDefault()?._PlanDetails)"
                            RowUpdate="@((PlanDetails pd) => { OnUpdateRow(pd); })"
                            RowCreate="@((PlanDetails pd) => { OnCreateRow(pd); })"
                            KeyProperty="Id"
                            AllowColumnResize="true" AllowAlternatingRows="false">
                @* <HeaderTemplate>
                        <RadzenRow JustifyContent="JustifyContent.End" AlignItems="AlignItems.Center">
                            <RadzenButton Icon="download" Text="添加" Variant="Variant.Outlined" />
                        </RadzenRow>
                    </HeaderTemplate> *@
                <Columns>
                    <RadzenDataGridColumn Title="序号" Property="index" Width="3rem">
                        <Template Context="data">
                            @(SelectedPlan.FirstOrDefault()?._PlanDetails.IndexOf(data) + 1)
                        </Template>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Title="药品" Property="_DrugInfo.DrugName" Width="15rem">
                        <Template Context="data">
                            <RadzenText TextStyle="TextStyle.Body1"><b>@(data._DrugInfo?.DrugName)</b></RadzenText>
                            <RadzenText TextStyle="TextStyle.Body1"><b>@(data._DrugInfo?.DrugSpec)</b></RadzenText>
                        </Template>
                        <EditTemplate Context="planDetails">

                            <RadzenDropDownDataGrid AllowVirtualization="true" Name="drugName" TValue="DrugInfo" @bind-Value="planDetails._DrugInfo" Data="@drugInfos"
                                                    Style="width:100%; display: block;" AllowFilteringByAllStringColumns="true" TextProperty="DrugName">
                                <Columns>
                                    <RadzenDropDownDataGridColumn Property="DrugId" Title="药品编码" />
                                    <RadzenDropDownDataGridColumn Property="DrugName" Title="名称" />
                                    <RadzenDropDownDataGridColumn Property="DrugSpec" Title="规格" />
                                </Columns>
                            </RadzenDropDownDataGrid>
                            <RadzenCustomValidator Component="drugName" Validator="@(() => (planDetails._DrugInfo.DrugId != null))" Text="请选择药品" Popup=true />
                            <RadzenCustomValidator Component="drugName" Validator="@(() => ValidatroDrug(planDetails))" Text="套餐中已包含该药品" Popup=true />

                        </EditTemplate>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Title="基数" Property="BaseQuantity" Width="7rem">
                        <EditTemplate Context="planDetails">
                            <RadzenNumeric Name="BaseQuantity" @bind-Value="planDetails.BaseQuantity" Style="width:100%; display: block;" />
                            <RadzenNumericRangeValidator Style="position: absolute;z-index: 9999;" Min="0" Text="请填写正确的添加数量" Component="BaseQuantity" Popup="true" />
                        </EditTemplate>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Title="操作" Filterable="false" Sortable="false" TextAlign="TextAlign.Left" Frozen="true" FrozenPosition="FrozenColumnPosition.Right" Width="9rem">
                        <Template Context="planDetails">
                            <RadzenButton Icon="edit" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@(args => EditRow(planDetails))" @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(planDetails))" @onclick:stopPropagation="true">
                            </RadzenButton>
                        </Template>
                        <EditTemplate Context="planDetails">
                            <RadzenButton Icon="check" ButtonStyle="ButtonStyle.Success" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@((args) => InsertRow(planDetails))" aria-label="Save">
                            </RadzenButton>
                            <RadzenButton Icon="close" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@((args) => CancelEdit(planDetails))" 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(planDetails))" aria-label="Delete">
                            </RadzenButton>
                        </EditTemplate>
                    </RadzenDataGridColumn>
                </Columns>
            </RadzenDataGrid>
            <div style="margin-top:5px">
                <RadzenButton Size="ButtonSize.Medium" ButtonStyle="ButtonStyle.Success" Icon="add_circle_outline"  Click="@InsertRow" Text="新增药品" />
            </div>
        </div>
    </div>
</div>

@code {
    @inject IPlanDao planDao;
    @inject DialogService dialogService;
    @inject NotificationService _message
    @inject GlobalStateService globalStateService;

    RadzenDataGrid<Plan> grid;
    RadzenDataGrid<PlanDetails> PlanDetailsGrid;
    bool isLoading;
    int count;
    private IEnumerable<Plan>? _forecasts;
    IList<Plan>? SelectedPlan { get; set; } = new List<Plan>();
    List<PlanDetails> SelectedPlanDetails = new List<PlanDetails>();
    List<DrugInfo> drugInfos;
     

    async Task LoadData(LoadDataArgs args)
    {
        isLoading = true;

        var result = await planDao.GetAllPlanInfo();
        // Update the Data property
        _forecasts = result.Desserts;
        count = result.TotalDesserts;
        SelectedPlan = new List<Plan>() { _forecasts.FirstOrDefault() };

        isLoading = false;
        drugInfos = result.Other;
    }
    // async Task LoadDetailDate(LoadDataArgs args)
    // {
    //     // SelectedPlan = new List<Plan>() { await planDao.GetPlanById(SelectedPlan.FirstOrDefault().Id) };
    // }
    async Task reloadGrid()
    {
        await grid.Reload();
    }
    void OnUpdatePlanRow(Plan dl)
    {
        // Reset(dl);

        // 数据库更新
        planDao.UpdatePlanInfo(dl);
        grid.Reload();
    }
    async Task OnCreatePlanRow(Plan dl)
    {
        // 数据库添加套餐
        bool bFlag = await planDao.InsertPlanInfo(dl);
        if (!bFlag)
        {
            SelectedPlan.Remove(dl);
        }
        grid.Reload();
    }
    //新增套餐
    async Task InsertPlanRow()
    {
        var planInfo = new Plan();
        if (_forecasts.Count() <= 0)
        {
            _forecasts = new List<Plan>
            {
                new Plan()
            };
            await grid.InsertRow(_forecasts.FirstOrDefault());
        }
        else
        {
            await grid.InsertRow(planInfo);
        }
    }
    //修改套餐
    async Task EditPlanRow(Plan planInfo)
    {
        await grid.EditRow(planInfo);
    }
    //删除套餐
    async Task DeletePlanRow(Plan planInfo)
    {
        if (planInfo.Id > 0)
        {
            //弹出确认提示框
            var b = await dialogService.OpenAsync<ConfirmDialog>(
               $"删除确认",
             new Dictionary<string, object>() { { "confirmInfo", "确认要删除套餐：" + planInfo.Name + "吗？" } },
             new DialogOptions() { Width = "45vw", Resizable = true, Draggable = true, ShowClose = false });
            if (b)
            {
                //查询要删除的套餐下是否有绑定，且绑定有库存
                if (!(await planDao.CheckPlanBind(planInfo.Id)))
                {
                    _message.Notify
                  (
                      new NotificationMessage
                      {
                          Severity = NotificationSeverity.Error,
                          Summary = "提示",
                          Detail = $"该套餐还有库存绑定且有库存，请先清库存",
                          Duration = 4000
                      }
                  );
                    return;
                }


                // 数据库删除
                if (await planDao.DeletePlanInfo(planInfo.Id))
                {
                    _message.Notify
                    (
                        new NotificationMessage
                        {
                            Severity = NotificationSeverity.Success,
                            Summary = "提示",
                            Detail = $"删除成功",
                            Duration = 4000
                        }
                    );
                }
                else
                {
                    _message.Notify
                    (
                        new NotificationMessage
                        {
                            Severity = NotificationSeverity.Error,
                            Summary = "提示",
                            Detail = "删除失败",
                            Duration = 4000
                        }
                    );
                }
            }
            await grid.Reload();
        }
        else
        {
            grid.CancelEditRow(planInfo);
            await grid.Reload();
        }
    }
    //保存套餐信息
    async Task SavePlanRow(Plan planInfo)
    {
        await grid.UpdateRow(planInfo);
    }
    async Task CancelPlanEdit(Plan planInfo)
    {
        grid.CancelEditRow(planInfo);
        await grid.Reload();
        await PlanDetailsGrid.Reload();
    }



    void Reset(PlanDetails pd)
    {
        SelectedPlanDetails.Remove(pd);
    }
    //修改药品
    async Task EditRow(PlanDetails planDetail)
    {
        // planDetail.DrugId = null;
        //查询要删除的药品是否有绑定且库存大于0
        if (!(await planDao.CheckPlanDetailBind(planDetail)))
        {
            _message.Notify(new NotificationMessage
            {
                Severity = NotificationSeverity.Error,
                Summary = "提示",
                Detail = "该药品有绑定且库存不为0，请先清库存",
                Duration = 4000
            });
            return;
        }
        await PlanDetailsGrid.EditRow(planDetail);
    }
    //保存修改药品
    async Task InsertRow(PlanDetails planDetail)
    {
        await PlanDetailsGrid.UpdateRow(planDetail);
    }
    //取消修改药品
    async Task CancelEdit(PlanDetails planDetail)
    {
        PlanDetailsGrid.CancelEditRow(planDetail);
        SelectedPlan.FirstOrDefault()._PlanDetails.RemoveAll(pd => pd.Id == 0);
        await PlanDetailsGrid.Reload();
    }
    //删除药品
    async Task DeleteRow(PlanDetails planDetail)
    {
        // Reset(planDetail);

        if (planDetail.Id > 0)
        {
            //弹出确认提示框
            var b = await dialogService.OpenAsync<ConfirmDialog>(
               $"确认删除",
             new Dictionary<string, object>() { { "confirmInfo", "确认要删除药品：" + planDetail._DrugInfo.DrugName + "吗？" } },
             new DialogOptions() { Width = "45vw", Resizable = true, Draggable = true, ShowClose = false }
           );
            if (b)
            {
                //查询要删除的药品是否有绑定且库存大于0
                if (!(await planDao.CheckPlanDetailBind(planDetail)))
                {
                    _message.Notify(new NotificationMessage
                    {
                        Severity = NotificationSeverity.Error,
                        Summary = "提示",
                        Detail = "该药品有绑定且库存不为0，请先清库存",
                        Duration = 4000
                    });
                    return;
                }

                // 数据库删除
                if (await planDao.DeletePlanDetail(planDetail))
                {
                    _message.Notify(new NotificationMessage
                    {
                        Severity = NotificationSeverity.Success,
                        Summary = "提示",
                        Detail = "删除成功",
                        Duration = 4000
                    }
                    );
                    SelectedPlan.FirstOrDefault()._PlanDetails.Remove(planDetail);
                }
                else
                {
                    _message.Notify(new NotificationMessage
                    {
                        Severity = NotificationSeverity.Error,
                        Summary = "提示",
                        Detail = "删除失败",
                        Duration = 4000
                    }
                    );
                }
                await PlanDetailsGrid.Reload();
            }
        }
        else
        {
            PlanDetailsGrid.CancelEditRow(planDetail);
        }
        SelectedPlan.FirstOrDefault()._PlanDetails.RemoveAll(pd => pd.Id == 0);
    }
    async void OnUpdateRow(PlanDetails planDetail)
    {
        // Reset(planDetail);

        SelectedPlanDetails.Add(planDetail);
        // 数据库更新
        if (await planDao.UpdatePlanDetail(planDetail))
        {
            _message.Notify(new NotificationMessage
            {
                Severity = NotificationSeverity.Success,
                Summary = "提示",
                Detail = "修改成功",
                Duration = 4000
            }
               );
        }
        else
        {
            _message.Notify(new NotificationMessage
            {
                Severity = NotificationSeverity.Error,
                Summary = "提示",
                Detail = "修改失败",
                Duration = 4000
            }
               );
        }

        await PlanDetailsGrid.Reload();
    }
    //保存套餐下添加的药品
    async void OnCreateRow(PlanDetails planDetail)
    {
        if (SelectedPlan.FirstOrDefault() != null)
        {

            planDetail.PlanId = SelectedPlan.FirstOrDefault().Id;
            planDetail.DrugId = planDetail.DrugId == null ? planDetail._DrugInfo.DrugId : planDetail.DrugId;
            planDetail.UseState = 1;
            planDetail.OperatorUser = globalStateService.Operator?.Username;
            planDetail.ReviewerUser = globalStateService.Reviewer?.Username;
            if (await planDao.AddPlanDetail(planDetail))
            {
                _message.Notify(new NotificationMessage
                {
                    Severity = NotificationSeverity.Success,
                    Summary = "提示",
                    Detail = "保存成功",
                    Duration = 4000
                }
                );


            }
            else
            {
                _message.Notify(new NotificationMessage
                {
                    Severity = NotificationSeverity.Error,
                    Summary = "提示",
                    Detail = "保存失败",
                    Duration = 4000
                }
                );
            }
        }
        // await grid.Reload();
        await PlanDetailsGrid.Reload();


    }
    //新增药品
    async Task InsertRow()
    {
        //查询要删除的套餐下是否有绑定，且绑定有库存
        if (SelectedPlan.FirstOrDefault()!=null)
        {
            if (!(await planDao.CheckPlanBind((int)SelectedPlan.FirstOrDefault().Id)))
            {
                _message.Notify(new NotificationMessage
                    {
                        Severity = NotificationSeverity.Error,
                        Summary = "提示",
                        Detail = "该药品有绑定且库存不为0，请先清库存",
                        Duration = 4000
                    });
                return;
            }
        }
        var detail = new Pojo.PlanDetails()
        {
            PlanId = SelectedPlan.FirstOrDefault().Id
        };
        SelectedPlan.FirstOrDefault()._PlanDetails.Add(detail);
        await PlanDetailsGrid.InsertRow(detail);

    }
    //验证药品是否已存在套餐中
    bool ValidatroDrug(PlanDetails planDetail)
    {
        if (planDetail.PlanId == 0)
        {
            //新增的
            planDetail.PlanId = SelectedPlan.FirstOrDefault().Id;
        }
        return planDao.CheckDrugById(planDetail);
    }
}