@page "/Box/BoxBindings123"


<div class="container-fluid">
    <div class="row">
        <RadzenFieldset class="col-12 mb-4" Text="选择药盒">
            <div class="col-12 row justify-content-center align-items-center text-center">
                <div class="row justify-content-around align-items-center" style="overflow:auto">
                    @if (BoxList != null)
                    {
                        foreach (var item in BoxList)
                        {
                            <div class="col-2">
                                <RadzenCheckBox Style="width:40px;height:40px;margin:2px" TValue="bool" Disabled=@item.BoxDisabled @bind-Value=@item.IsChecked Name="@($"CheckBox_{item.DrawerNo}")" Change="@((bool isChecked) => OnCheckBoxChange(isChecked, item.DrawerNo))" />
                              @if(item.DrawerNo<51)
                                  {
                                    <RadzenLabel Text="@($"{(item.DrawerNo % 2 == 0 ? item.DrawerNo : item.DrawerNo+1)/2}-{(item.DrawerNo % 2 == 0 ? 2 : 1)}")" Component="@($"CheckBox_{item.DrawerNo}")" />
                                }
                                else
                                {

                                    <RadzenLabel Text="@($"{item.DrawerNo -25}")" Component="@($"CheckBox_{item.DrawerNo}")" />
                                }
                            </div>
                        }
                    }
                </div>
            </div>
        </RadzenFieldset>
        <RadzenCard class="col-12 mb-2">
            <RadzenButton ButtonStyle="ButtonStyle.Secondary" Variant="Variant.Outlined" Size="ButtonSize.Small" Click="@EditChannel" Text="绑定/解绑" />
            <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>

                    <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>
                </RadzenStack>
            </RadzenStack>
        </RadzenCard>
    </div>
</div>

@code {
    @inject IChannelListDao channelListDao;
    @inject IDrugInfoDao drugInfoDao;
    @inject DialogService dialogService;
    @inject NotificationService _message;
    @inject IPlanDao planDao;
    int count;
    private List<ChannelList>? _forecasts;
    private List<ChannelList>? BoxList;

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

    DrugInfo drugInfo;

    DrugManuNo drugManuNo;

    int firstFlag = 0;

    List<Plan> plans;
    // 默认选中的项
    private Plan selectedPlan = new();
    protected override async Task OnInitializedAsync()
    {
        await LoadData();
        await base.OnInitializedAsync();

        //drugInfos = await drugInfoDao.GetAllDrug();
    }

    async Task LoadData()
    {
        BoxList = await channelListDao.GetAllBox();
        var result = await planDao.GetAllPlanInfo();
        plans = result.Desserts.Where(p=>p._PlanDetails.Count>0).ToList();
        _forecasts = await channelListDao.GetAllChannelList();
        firstFlag = 0;
    }

    // 处理选择变更（可选）
    private void OnPlanSelected(Plan plan)
    {
        selectedPlan = plan;
    }

    //绑定
    async Task EditChannel()
    {
        List<ChannelList> bindList = BoxList.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 LoadData();
        }
        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 LoadData();
            }
            else
            {
                _message.Notify(
                            new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"请选择套餐", Duration = 4000 }
                        );
                
            }
        }
    }

    private async Task OnCheckBoxChange(bool isChecked, int DrawerNo)
    {
        //isChecked==true 1)当前选择的药箱已经绑药套餐且库存<=0，如果有库存则提示不能选择，如果无库存则列出与之绑定相同套餐且库存<=0的药箱号，其他药箱号不可选择
        //                2)当前选择的药箱未绑定套餐则将所有未绑定套餐的药箱号列出来，其他药箱不可操作
        if (firstFlag == 0)
        {
            if (isChecked)
            {
                firstFlag = 1;
                string drugId = BoxList.Where(b => b.DrawerNo == DrawerNo).Select(b => b.DrugId).FirstOrDefault();
                //所选药箱已绑定套餐
                if (!string.IsNullOrEmpty(drugId))
                {
                    //查询该药箱下的药品库存是否存在不为0的，存在则不让选择
                    List<ChannelStock> stockList = await channelListDao.GetChannelStockByBox(DrawerNo);
                    if (stockList != null && stockList.Count > 0)
                    {
                        //该药箱下存在库存不为0的药品
                        _message.Notify(
                                      new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"该药盒下的药品仍有库存，请清库存后再操作", Duration = 4000 }
                               );
                        BoxList.ForEach(it => it.IsChecked = false);
                        firstFlag = 0;
                        return;
                    }
                    else
                    {
                        //无库存则列出与之绑定相同套餐且库存 <= 0的药箱号，其他药箱号不可选择
                        // BoxList.Where(b => string.IsNullOrEmpty(b.DrugId)).ToList().ForEach(b => b.BoxDisabled = true);
                        //1)查询套餐下无库存的药箱号
                        List<ChannelStock>? lists = await channelListDao.GetChannelStockByPlan(drugId);
                        if (lists != null && lists.Count > 0)
                        {
                            int[] boxNum = lists.Select(l => l.DrawerNo).ToArray();
                            //不在该lists下的药箱号不可选择
                            BoxList.Where(b => !boxNum.Contains(b.DrawerNo)).ToList().ForEach(b => b.BoxDisabled = true);
                        }
                        selectedPlan = await planDao.GetPlanById(Convert.ToInt32(drugId));
                    }

                }
                else
                {

                    //未绑定套餐 ，列出所有未绑的药箱号，其他不可操作
                    BoxList.Where(b => !string.IsNullOrEmpty(b.DrugId)).ToList().ForEach(b => b.BoxDisabled = true);
                }

            }
        }
        else
        {
            if (!isChecked)
            {
                //isChecked==false 1)是否全部是false，是则将所有isChecked==true，不是则不做改变
                if (!BoxList.Any(b => b.IsChecked == true))
                {
                    BoxList.ForEach(b => b.BoxDisabled = false);
                    firstFlag = 0;
                }
            }
        }
    }


}
