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

<div class="container-fluid">
    <div class="row">
        <div class="col-12  mb-4">

            <form onsubmit="@(() => grid.Reload())">
                <RadzenFieldset Text="查询">
                    <RadzenStack Orientation="Orientation.Horizontal" Gap="1rem">
                        <RadzenRow AlignItems="AlignItems.Center">
                            <RadzenColumn Size="4">
                                <RadzenLabel Text="药品编码" Component="DrugId" />
                            </RadzenColumn>
                            <RadzenColumn Size="8">
                                <RadzenTextBox @bind-Value="DrugId" Style="width: 100%;" Name="DrugId"></RadzenTextBox>
                            </RadzenColumn>
                        </RadzenRow>
                        <RadzenRow AlignItems="AlignItems.Center">
                            <RadzenColumn Size="4">
                                <RadzenLabel Text="药品名称" Component="DrugName" />
                            </RadzenColumn>
                            <RadzenColumn Size="8">
                                <RadzenTextBox @bind-Value="DrugName" Style="width: 100%;" Name="DrugName"></RadzenTextBox>
                            </RadzenColumn>
                        </RadzenRow>

                        <RadzenRow AlignItems="AlignItems.Center">
                            <RadzenColumn Size="12">
                                <RadzenButton Size="ButtonSize.Large" ButtonType="ButtonType.Submit" IsBusy="isLoading" Icon="search" Text="查询" />
                                <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="@InsertDrugRow" Text="新增药品" />
                            </RadzenColumn>
                        </RadzenRow>
                    </RadzenStack>
                </RadzenFieldset>
            </form>
        </div>
        <div class="col-6  mb-4" style="height:55vh;overflow:auto;">
            <RadzenDataGrid @ref="grid"
                            LoadData="@LoadData"
                            @bind-Value="@SelectedDrugs"
                            IsLoading="@isLoading"
                            Count="@count"
                            EmptyText="无数据"
                            Data="@_forecasts"
                            AllowColumnResize="true" AllowAlternatingRows="false"
                            SelectionMode="DataGridSelectionMode.Single" RowUpdate="@((DrugInfo di)=>{OnDrugUpdateRow(di);})" RowCreate="@((DrugInfo di)=>{OnDrugCreateRow(di);})"
                            AllowPaging="true" PageSize="5" PagerHorizontalAlign="HorizontalAlign.Left" ColumnWidth="100px" ShowPagingSummary="true" PagingSummaryFormat="{0}/{1} 共{2}条数据">
                <Columns>
                    <RadzenDataGridColumn Title="编码" Property="DrugId">
                        <EditTemplate Context="drugInfo">
                            <RadzenTextBox Name="DrugId" @bind-Value="drugInfo.DrugId" Style="width:100%; display: block;" />
                            <RadzenRequiredValidator Text="请填写编码" Component="DrugId" Popup="true" />
                        </EditTemplate>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Width="200px" Title="药品名称" Property="DrugName">
                        <EditTemplate Context="drugInfo">
                            <RadzenTextBox Name="DrugName" @bind-Value="drugInfo.DrugName" Style="width:100%;display:block;" />
                            <RadzenRequiredValidator Text="请填写药品名称" Component="DrugName" Popup="true" />
                        </EditTemplate>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Title="规格" Property="DrugSpec">
                        <EditTemplate Context="drugInfo">
                            <RadzenTextBox Name="DrugSpec" @bind-Value="drugInfo.DrugSpec" Style="width:100%;display:block;" />
                            <RadzenRequiredValidator Text="请填写规格" Component="DrugSpec" Popup="true" />
                        </EditTemplate>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Width="150px" Title="厂家" Property="Manufactory">
                        <EditTemplate Context="drugInfo">
                            <RadzenTextBox Name="Manufactory" @bind-Value="drugInfo.Manufactory" Style="width:100%;display:block;" />
                            <RadzenRequiredValidator Text="请填写厂家" Component="Manufactory" Popup="true" />
                        </EditTemplate>
                    </RadzenDataGridColumn>
                    <RadzenDataGridColumn Title="导出使用报表" Property="PackH">
                        <EditTemplate Context="drugInfo">
                            <RadzenTextBox Name="PackH" @bind-Value="drugInfo.PackH" Style="width:100%;display:block;" />
                        </EditTemplate>
                    </RadzenDataGridColumn>

                    <RadzenDataGridColumn Context="drugInfo" Title="操作" Filterable="false" Sortable="false" TextAlign="TextAlign.Left" Frozen="true" FrozenPosition="FrozenColumnPosition.Right">
                        <Template Context="drugInfo">
                            <RadzenButton Icon="edit" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@(args => EditDrugRow(drugInfo))" @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 => DeleteDrugRow(drugInfo))" @onclick:stopPropagation="true">
                            </RadzenButton>
                        </Template>
                        <EditTemplate Context="drugInfo">
                            <RadzenButton Icon="check" ButtonStyle="ButtonStyle.Success" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@((args) => SaveDrugRow(drugInfo))" aria-label="Save">
                            </RadzenButton>
                            <RadzenButton Icon="close" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@((args) => CancelDrugEdit(drugInfo))" 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 => DeleteDrugRow(drugInfo))" aria-label="Delete">
                            </RadzenButton>
                        </EditTemplate>
                    </RadzenDataGridColumn>
                </Columns>
            </RadzenDataGrid>
        </div>
        <div class="col-6  mb-4">
            @*     <RadzenCard Style="margin-bottom:20px">
                批次列表
            </RadzenCard> *@
            @if (SelectedDrugs.Count > 0)
            {

                <div class="col-6  mb-4" style="height:55vh;width:550px;overflow:auto;">
                    <RadzenDataGrid @ref="ManusGrid" EmptyText="无数据"  ColumnWidth="100px" Style="width:445px"
                                    Data="@(SelectedDrugs.FirstOrDefault()?.Manus)"
                                    RowUpdate="@((DrugManuNo dm) => { OnUpdateRow(dm); })" RowCreate="@((DrugManuNo dm) => { OnCreateRow(dm); })"
                                    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="25px" Visible=false>
                                <Template Context="data">
                                    @(SelectedDrugs.FirstOrDefault()?.Manus.IndexOf(data) + 1)
                                </Template>
                            </RadzenDataGridColumn>
                            <RadzenDataGridColumn Title="批次" Property="ManuNo" Width="150px">
                                <EditTemplate Context="drugManuNo">
                                    <RadzenTextBox Name="ManuNo" @bind-Value="drugManuNo.ManuNo" Style="width:100%; display: block;" />
                                    <RadzenRequiredValidator Text="请填写批次" Component="ManuNo" Popup="true" />
                                </EditTemplate>
                            </RadzenDataGridColumn>
                            <RadzenDataGridColumn Title="效期" Property="EffDate" Width="150px">
                                <EditTemplate Context="drugManuNo">
                                    <RadzenDatePicker DateFormat="yyyy-MM-dd" @bind-Value="drugManuNo.EffDate" Style="width: 100%;" Name="EffDate" />
                                    <RadzenRequiredValidator Text="请填写效期" Component="EffDate" Popup="true" />
                                </EditTemplate>
                            </RadzenDataGridColumn>

                            <RadzenDataGridColumn Context="drugManuNo" Title="操作" Width="160px" Filterable="false" Sortable="false" TextAlign="TextAlign.Left" Frozen="true" FrozenPosition="FrozenColumnPosition.Right">
                                <Template Context="drugManuNo">
                                    <RadzenButton Icon="edit" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@(args => EditRow(drugManuNo))" @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(drugManuNo))" @onclick:stopPropagation="true">
                                    </RadzenButton>
                                </Template>
                                <EditTemplate Context="drugManuNo">
                                    <RadzenButton Icon="check" ButtonStyle="ButtonStyle.Success" Variant="Variant.Flat" Size="ButtonSize.Medium" Click="@((args) => SaveRow(drugManuNo))" aria-label="Save">
                                    </RadzenButton>
                                    <RadzenButton Icon="close" ButtonStyle="ButtonStyle.Light" Variant="Variant.Flat" Size="ButtonSize.Medium" class="my-1 ms-1" Click="@((args) => CancelEdit(drugManuNo))" 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(drugManuNo))" aria-label="Delete">
                                    </RadzenButton>
                                </EditTemplate>
                            </RadzenDataGridColumn>
                        </Columns>
                    </RadzenDataGrid>
                </div>
                <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 IDrugInfoDao drugInfoDao;
    @inject DialogService dialogService;
    @inject IDrugManuNoDao drugManuNoDao;
    RadzenDataGrid<DrugInfo> grid;
    RadzenDataGrid<DrugManuNo> ManusGrid;


    List<DrugManuNo> manuNoToInsert = new List<DrugManuNo>();
    List<DrugManuNo> manuNoToUpdate = new List<DrugManuNo>();

    bool isLoading;
    int count;
    private IEnumerable<DrugInfo>? _forecasts;

    IList<DrugInfo> SelectedDrugs { get; set; } = new List<DrugInfo>();
    string DrugId;
    string DrugName;

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

        var result = await drugInfoDao.GetAllDrug(DrugId, DrugName, args.Top, args.Skip);
        // Update the Data property
        _forecasts = result.Desserts;
        count = result.TotalDesserts;
        SelectedDrugs = new List<DrugInfo>() { _forecasts.FirstOrDefault() };

        isLoading = false;
    }

    async Task reloadGrid()
    {
        DrugId = String.Empty;
        DrugName = String.Empty;
        await grid.Reload();
    }

    void Reset()
    {
        manuNoToInsert.Clear();
        manuNoToUpdate.Clear();
    }
    void Reset(DrugManuNo drugManuNo)
    {
        manuNoToInsert.Remove(drugManuNo);
        manuNoToUpdate.Remove(drugManuNo);
    }
    /// 新增药品
    async Task InsertDrugRow()
    {
        var drugInfo = new DrugInfo();
        drugInfo.Manus.Add(new DrugManuNo());
        SelectedDrugs.Add(drugInfo);
        await grid.InsertRow(drugInfo);
    }
    // //更新药品数据信息
    async Task OnDrugUpdateRow(DrugInfo drugInfo)
    {
        // 数据库更新药品
        drugInfoDao.UpdateDrugInfo(drugInfo);
        grid.Reload();
    }
    //新增药品数据信息
    async Task OnDrugCreateRow(DrugInfo drugInfo)
    {
        // 数据库添加药品
        drugInfoDao.AddDrugInfo(drugInfo);
        grid.Reload();
    }
    async Task EditDrugRow(DrugInfo drugInfo)
    {
        drugInfoDao.UpdateDrugInfo(drugInfo);
        await grid.EditRow(drugInfo);
    }
    async Task SaveDrugRow(DrugInfo drugInfo)
    {
        await grid.UpdateRow(drugInfo);
    }
    void CancelDrugEdit(DrugInfo drugInfo)
    {
        Reset();
        grid.CancelEditRow(drugInfo);
        grid.Reload();
    }
    async Task DeleteDrugRow(DrugInfo drugInfo)
    {
        Reset();
        if (!string.IsNullOrEmpty(drugInfo.DrugId))
        {
            //弹出确认提示框
            var b = await dialogService.OpenAsync<ConfirmDialog>(
               $"删除确认",
             new Dictionary<string, object>() { { "confirmInfo", "确认要删除药品：" + drugInfo.DrugName + "吗？" } },
             new DialogOptions() { Width = "45vw", Resizable = true, Draggable = true, ShowClose = false });
            if (b)
            {
                // 数据库删除
                drugInfoDao.DeleteDrugInfo(drugInfo.DrugId);
            }
            grid.Reload();
        }
    }

    /// 新增批次
    async Task InsertRow()
    {
        var drugManuNo = new Pojo.DrugManuNo()
            {
                // Id = Guid.NewGuid().ToString(),
                DrugId = SelectedDrugs.FirstOrDefault().DrugId
            };
        SelectedDrugs.FirstOrDefault().Manus.Add(drugManuNo);
        await ManusGrid.InsertRow(drugManuNo);
    }

    async Task EditRow(DrugManuNo drugManuNo)
    {

        Reset();

        manuNoToUpdate.Add(drugManuNo);
        await ManusGrid.EditRow(drugManuNo);
    }
    async Task SaveRow(DrugManuNo drugManuNo)
    {
        drugManuNo.Id = string.IsNullOrEmpty(drugManuNo.Id) ? Guid.NewGuid().ToString() : drugManuNo.Id;
        await ManusGrid.UpdateRow(drugManuNo);
    }

    void CancelEdit(DrugManuNo drugManuNo)
    {
        Reset(drugManuNo);
        // SelectedDrugs.FirstOrDefault().Manus.Remove(drugManuNo);
        SelectedDrugs.FirstOrDefault().Manus.RemoveAll(mn=>string.IsNullOrEmpty(mn.Id));
        ManusGrid.CancelEditRow(drugManuNo);
        ManusGrid.Reload();
    }

    async Task DeleteRow(DrugManuNo drugManuNo)
    {
        Reset(drugManuNo);

        if (SelectedDrugs.FirstOrDefault().Manus.Contains(drugManuNo))
        {
            //弹出确认提示框
            var b = await dialogService.OpenAsync<ConfirmDialog>(
               $"确认删除",
             new Dictionary<string, object>() { { "confirmInfo", "确认要删除批次：" + drugManuNo.ManuNo + "吗？" } },
             new DialogOptions() { Width = "45vw", Resizable = true, Draggable = true, ShowClose = false }
           );
            if (b)
            {
                SelectedDrugs.FirstOrDefault().Manus.Remove(drugManuNo);
                // 数据库删除
                drugManuNoDao.DeleteDrugManuNo(drugManuNo.Id);
                await ManusGrid.Reload();
            }
        }
        else
        {
            ManusGrid.CancelEditRow(drugManuNo);
            await ManusGrid.Reload();
        }
    }
    void OnUpdateRow(DrugManuNo dm)
    {
        dm.Id = string.IsNullOrEmpty(dm.Id) ? Guid.NewGuid().ToString() : dm.Id;
        Reset(dm);

        // 数据库更新
        drugManuNoDao.UpdateDrugManuNo(dm);
        ManusGrid.Reload();
    }
    void OnCreateRow(DrugManuNo dm)
    {
        // 数据库添加批次
        drugManuNoDao.AddDrugManuNo(dm);
        manuNoToInsert.Remove(dm);
        ManusGrid.Reload();
    }

}
