@page "/Box/BoxBindings"

<style>
    .mycol {
    width: calc(100%/8);
    margin: 4px !important;
    }
</style>
<div class="container-fluid">

    <div class="row">
        <div class="col-12 mb-4">
            @*  <RadzenFieldset Text="查询">
                <RadzenStack Orientation="Orientation.Horizontal" AlignItems="AlignItems.Center">
                    <RadzenText TextStyle="TextStyle.Overline" class="rz-display-flex rz-mt-2 rz-my-0">选择套餐</RadzenText>

                    <RadzenDropDownDataGrid AllowVirtualization="true" Name="planName" TValue="Plan" Data="@plans" Value="@selectedPlan" ValueChanged="@OnPlanSelected"
                                            Style="width:100%; display: block;" AllowFilteringByAllStringColumns="true" TextProperty="Name">

                        <Columns>
                            <RadzenDropDownDataGridColumn Property="Name" Title="套餐名称" Sortable="false" />
                        </Columns>
                    </RadzenDropDownDataGrid>
                    <RadzenButton ButtonStyle="ButtonStyle.Secondary" Variant="Variant.Outlined" Size="ButtonSize.Small" Click="@EditChannel" Text="绑定/解绑" />
                </RadzenStack>
            </RadzenFieldset> *@
            <form onsubmit="@(() => EditChannel())">
                <RadzenFieldset Text="选择套餐">
                    <RadzenStack Orientation="Orientation.Horizontal" Gap="1rem">
                        <RadzenRow AlignItems="AlignItems.Center">
                            <RadzenDropDownDataGrid AllowVirtualization="true" Name="planName" TValue="Plan" Data="@plans" Value="@selectedPlan" ValueChanged="@OnPlanSelected"
                            Style="width:100%; display: block;" AllowFilteringByAllStringColumns="true" TextProperty="Name">

                                <Columns>
                                    <RadzenDropDownDataGridColumn Property="Name" Title="套餐名称" Sortable="false" />
                                </Columns>
                            </RadzenDropDownDataGrid>
                        </RadzenRow>
                        <RadzenRow AlignItems="AlignItems.Center">
                            <RadzenColumn Size="12">
                                <RadzenButton ButtonType="ButtonType.Submit" Size="ButtonSize.Medium" Text="绑定/解绑" />
                                @* <RadzenButton Size="ButtonSize.Medium" Click="@EditChannel" IsBusy="isLoading" Text="解绑" ButtonStyle="ButtonStyle.Warning" /> *@
                            </RadzenColumn>
                        </RadzenRow>
                    </RadzenStack>
                </RadzenFieldset>
            </form>
        </div>
    </div>
    <div class="row">
        <div class="col-12 mb-4">

            <RadzenDataList @ref="grid" LoadData="@LoadData" WrapItems="true" Count="@count" IsLoading="@isLoading" Data="@_forecasts" PageSize="56" style="height:61vh; overflow:auto">
                <Template Context="channel">
                    <RadzenCard class="mycol" onclick="@(() => CardClick(channel))">
                        <RadzenRow>
                            <RadzenColumn Size="8" Class="rz-text-truncate">
                                @if (channel.DrawerNo == 99)
                                {
                                    <b class="rz-pr-3">@($"急诊药盒")</b>
                                }
                                else if(channel.DrawerNo==111)
                                {
                                    <b class="rz-pr-3">@($"恢复室药盒")</b>
                                }
                                else if (channel.DrawerNo == 31)
                                {
                                    <b class="rz-pr-3">@($"胃镜药盒")</b>
                                }
                                else if(channel.DrawerNo==32)
                                {
                                    <b class="rz-pr-3">@($"导管药盒")</b>
                                }
                                else if (channel.DrawerNo == 33)
                                {
                                    <b class="rz-pr-3">@($"生殖药盒")</b>
                                }
                                else if(channel.DrawerNo==34)
                                {
                                    <b class="rz-pr-3">@($"妇门药盒")</b>
                                }
                                else
                                {
                                    <b class="rz-pr-3">@($"{channel.DrawerNo}-{(channel.ColNo == 1 ? '白':'绿')}")</b>
                                }
                               @*  <b>号药盒</b> *@

                            </RadzenColumn>
                            <RadzenColumn Size="4" class="rz-text-align-end">
                                <RadzenCheckBox TValue="bool" Disabled=@channel.BoxDisabled @bind-Value=@channel.IsChecked />
                            </RadzenColumn>
                        </RadzenRow>
                        <hr style="border: none; background-color: rgba(0,0,0,.2); height: 1px; margin: 1rem 0;" />
                        <RadzenStack Orientation="Orientation.Horizontal" AlignItems="AlignItems.Center">
                            <RadzenStack Gap="0">
                                <RadzenText TextStyle="TextStyle.Overline" class="rz-display-flex rz-mt-2 rz-my-0">套餐</RadzenText>
                                <RadzenText TextStyle="TextStyle.Body1"><b>@(channel.PlanInfo.Name)</b></RadzenText>
                                <RadzenText TextStyle="TextStyle.Overline" class="rz-display-flex rz-mt-4 rz-mb-0">总库存</RadzenText>
                                <RadzenText TextStyle="TextStyle.Body1"><b>@(channel.TotalQuantity)</b></RadzenText>
                            </RadzenStack>
                        </RadzenStack>
                    </RadzenCard>
                </Template>
            </RadzenDataList>
        </div>
    </div>
</div>

@code {
    @inject IChannelListDao channelListDao;
    @inject IDrugInfoDao drugInfoDao;
    @inject DialogService dialogService;
    @inject NotificationService _message
    @inject IPlanDao planDao;
    RadzenDataList<ChannelList> grid;
    bool isLoading;
    int count;
    private IEnumerable<ChannelList>? _forecasts;

    List<DrugInfo> drugInfos;
    List<DrugManuNo> drugManuNos;

    DrugInfo drugInfo;

    DrugManuNo drugManuNo;


    List<Plan> plans;
    int firstFlag = 0;
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        var resultPlan = await planDao.GetAllPlanInfo();
        plans = resultPlan.Desserts.Where(p => p._PlanDetails.Count > 0).ToList();
        firstFlag = 0;

    }

    async Task LoadData(LoadDataArgs args)
    {

        isLoading = true;

        var result = await channelListDao.GetAllChannelListWithPlan(args.Top, args.Skip);

        // Update the Data property
        _forecasts = result.Desserts;

        // Update the count
        count = result.TotalDesserts;

        isLoading = false;

        plans = result.Other;
    }

    async Task reloadGrid()
    {
        await grid.Reload();
    }




    // 默认选中的项
    private Plan selectedPlan = new();
    // 处理选择变更（可选）
    private void OnPlanSelected(Plan plan)
    {
        selectedPlan = plan;
    }
    //绑定
    async Task EditChannel()
    {
        List<ChannelList> bindList = _forecasts.Where(b => b.IsChecked).ToList();
        if (bindList == null || bindList.Count <= 0)
        {
            _message.Notify(
                      new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"请先选择药箱号再点击按钮", Duration = 4000 }
                  );
            return;
        }
        if (!string.IsNullOrEmpty(bindList[0].DrugId))
        {
            //之前有绑定，在进行解绑
            foreach (var item in bindList)
            {
                var b = await channelListDao.UnBindBox(item);
                if (b)
                {
                    _message.Notify(
                        new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "提示", Detail = $"解除绑定成功", Duration = 4000 }
                    );
                }
                await grid.Reload();
            }
        }
        else
        {// 否则是进行解绑
            if (selectedPlan != null && selectedPlan.Id > 0)
            {
                foreach (var item in bindList)
                {
                    var b = await channelListDao.BindBox(item, selectedPlan);
                    if (b)
                    {
                        _message.Notify(
                            new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "提示", Detail = $"绑定成功", Duration = 4000 }
                        );
                    }
                }
                await grid.Reload();
            }
            else
            {
                _message.Notify(
                            new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"请选择套餐", Duration = 4000 }
                        );

            }
        }
    }


    async Task CardClick(ChannelList list)
    {
        if (firstFlag == 0 && !(list.BoxDisabled))
        {
            firstFlag = 1;
            if (!string.IsNullOrEmpty(list.DrugId))
            {
                list.IsChecked = !list.IsChecked;
                //已绑药品需要解绑,未绑定的不可选
                if (list.IsChecked)
                {
                    _forecasts.Where(it => it.DrugId != list.DrugId || it.TotalQuantity > 0).ToList().ForEach(it => it.BoxDisabled = true);
                    selectedPlan = await planDao.GetPlanById(Convert.ToInt32(list.DrugId));
                }
                else
                {
                    _forecasts.Where(it => it.TotalQuantity <= 0).ToList().ForEach(it => it.BoxDisabled = false);
                    firstFlag = 0;
                }

            }
            else
            {
                list.IsChecked = !list.IsChecked;
                //未绑定药品则已绑定的不可选
                if (list.IsChecked)
                {
                    _forecasts.Where(it => !string.IsNullOrEmpty(it.DrugId) || it.TotalQuantity > 0).ToList().ForEach(it => it.BoxDisabled = true);
                }
                else
                {
                    _forecasts.ToList().Where(it => it.TotalQuantity <= 0).ToList().ForEach(it => it.BoxDisabled = false);
                    firstFlag = 0;
                }

            }

        }
        else
        {
            if (!list.BoxDisabled)
            {
                list.IsChecked = !list.IsChecked;
            }
            //isChecked==false 1)是否全部是false，是则将所有isChecked==true，不是则不做改变
            if (!_forecasts.Any(b => b.IsChecked == true))
            {
                _forecasts.Where(it => it.TotalQuantity <= 0).ToList().ForEach(it => it.BoxDisabled = false);
                firstFlag = 0;
            }
        }
        await InvokeAsync(StateHasChanged);
    }
}
