@page "/Box/BoxReplace"
@using MasaBlazorApp3.Pojo.Config;
@using MasaBlazorApp3.Pojo.Vo;
@using MasaBlazorApp3.Util;
@using Microsoft.Extensions.Options;
@using Newtonsoft.Json;
@using log4net;

<RadzenStack Gap="1rem" Orientation="Orientation.Vertical" Style="height: 100%;">
    <RadzenStack>
        <RadzenStack class="rz-p-4 rz-border-radius-1" Style="border: var(--rz-grid-cell-border)" Orientation="Orientation.Horizontal" Gap="1rem">
            @*<RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">药名:</RadzenText> 
            <RadzenText  Class="rz-text-truncate"><b>@(channelStock.Drug.DrugName)</b></RadzenText>
            <RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">规格:</RadzenText>
            <RadzenText TextStyle="TextStyle.Body1" Class="rz-text-truncate"><b>@(channelStock.Drug.DrugSpec)</b></RadzenText>
            <RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">批次:</RadzenText>
            <RadzenText TextStyle="TextStyle.Body1" Class="rz-text-truncate"><b>@(channelStock.ManuNo)</b></RadzenText>
            <RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">效期:</RadzenText>
            <RadzenText TextStyle="TextStyle.Body1" Class="rz-text-truncate"><b>@(channelStock.EffDate)</b></RadzenText>
            <RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">库存:</RadzenText>
            <RadzenText TextStyle="TextStyle.Body1" Class="rz-text-truncate"><b>@(channelStock.Quantity)</b></RadzenText>
            <RadzenText Class="rz-mt-2 rz-my-0" Style="color: var(--rz-text-tertiary-color);">交换药盒:</RadzenText> *@
            <div style="text-align: left;width:15vw">
                <div class="rz-text-h6 rz-mb-0">药品名称</div>
                @(channelStock.Drug.DrugName)
            </div>
            <div style="text-align: left;width:6vw">
                <div class="rz-text-h6 rz-mb-0">规格</div>
                @(channelStock.Drug.DrugSpec)
            </div>
            <div style="text-align: left;width:8vw;">
                <div class="rz-text-h6 rz-mb-0">批次</div>
                @(channelStock.ManuNo)
            </div>
            <div style="text-align: left;width:8vw;">
                <div class="rz-text-h6 rz-mb-0">效期</div>
                @(channelStock.EffDate)
            </div>
            <div style="text-align: left;width:4vw;">
                <div class="rz-text-h6 rz-mb-0">库存</div>
                @(channelStock.Quantity)
            </div>
            <div class="rz-text-h6 rz-mb-0;width:10vw">
                交换药盒
                <RadzenDropDownDataGrid AllowVirtualization="true" Name="BoxColorList" TValue="BoxModel" Data="@BoxColorList" Value="BoxColor" Style="width: 8vw;"
                                        ValueChanged="@((args) => OnColorChanged(args))" AllowFiltering="false"
                                        AllowFilteringByAllStringColumns="true" TextProperty="药箱号">
                    <Template>
                        @((context as BoxModel).BoxNo == 1 ? "白" : (context as BoxModel).BoxNo == 2 ? "绿" : "非常规")
                    </Template>
                    <Columns>
                        <RadzenDropDownDataGridColumn Property="BoxNo" Title="药箱颜色" Sortable="false" />
                    </Columns>
                </RadzenDropDownDataGrid>
                <RadzenDropDown @bind-Value="SelectedDrawerNo" Data="@DrawerNos" Style="width:10vw" Change="@(args => SelectedDrawerChange(args))" Name="DropDownChangeEvent">

                    <RadzenText TextStyle="TextStyle.Subtitle2" class="mb-0">@(SelectedDrawerNo)</RadzenText>

                </RadzenDropDown>
            </div>
        </RadzenStack>
        <RadzenDataGrid @ref="grid" Data="@selectedDrawerData" AllowAlternatingRows="true" LoadData="@LoadData" IsLoading="@isLoading" Count="@count" EmptyText="无数据"
                        CellClick="@((DataGridCellMouseEventArgs<ChannelStock> args) => OnCellClick(args))"
                        AllowPaging="true" PageSize="10" PagerHorizontalAlign="HorizontalAlign.Left" ShowPagingSummary="true" PagingSummaryFormat="{0}/{1} 共{2}条数据">
            <Columns>
                <RadzenDataGridColumn Property="DrawerNo" Title="药盒号">
                    <Template Context="DrawerNo">
                        @(DrawerNo.DrawerNo == 99 ? "急诊药盒" : DrawerNo.DrawerNo == 111 ? "恢复室药盒" :
                            DrawerNo.DrawerNo == 31 ? "胃镜药盒" :
                            DrawerNo.DrawerNo == 32 ? "导管药盒" :
                            DrawerNo.DrawerNo == 33 ? "生殖药盒" :
                            DrawerNo.DrawerNo == 34 ? "妇门药盒" : $"{DrawerNo.DrawerNo}-{(DrawerNo.ColNo == 1 ? '白' : '绿')}")
                    </Template>
                </RadzenDataGridColumn>
                <RadzenDataGridColumn Property="Drug.DrugName" Title="药品" />
                <RadzenDataGridColumn Property="Drug.DrugSpec" Title="规格" />
                <RadzenDataGridColumn Property="ChannelStock.ManuNo" Title="批次" />
                <RadzenDataGridColumn Property="ChannelStock.EffDate" Title="效期" />
                <RadzenDataGridColumn Property="Quantity" Title="库存" />
                <RadzenDataGridColumn MinWidth="100px" Title="交换数量" Property="AddQuantity">
                    <EditTemplate Context="cs">
                        <RadzenNumeric Min="0" Style="display: block" Max=@cs.Quantity Name="Quantity" @bind-Value=@cs.AddQuantity />
                        <RadzenNumericRangeValidator Style="position: absolute;z-index: 9999;" Min="0" Text="请填写正确的交换数量" Component="Quantity" Popup="true" />
                    </EditTemplate>
                </RadzenDataGridColumn>
            </Columns>
        </RadzenDataGrid>

    </RadzenStack>
    <RadzenStack Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.Center" Gap="0.5rem">

        <RadzenButton Click="@Save" ButtonStyle="ButtonStyle.Success" Variant="Variant.Flat" Text="完成" Style="width: 120px" />

        <RadzenButton Click="@Cancel" Variant="Variant.Flat" Text="取消" Style="width: 120px" />

    </RadzenStack>
</RadzenStack>

@code {
    @inject Radzen.DialogService dialogService;
    @inject IChannelListDao channelListDao;
    @inject IOptions<SettingConfig> setting;
    @inject IOptions<DrawerConfig> drawerSetting;
    @inject NotificationService _message
    @inject PortUtil PortUtil;
    private readonly ILog logger = LogManager.GetLogger(typeof(OrderDetailDialog));

    bool CompleteIsEnable = true;
    bool CancleIsEnable = true;

    int status;
    bool isLoading;
    int count;

    [Parameter] public ChannelStock channelStock { get; set; }
    private bool CanTakeDrug = true;

    // public List<BoxTakeVo> data { get; set; }

    public List<ChannelStock> selectedDrawerData { get; set; }

    //称重取药数量
    int[] WeightFinnalQuantity { get; set; } = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 };

    //开抽屉前操作标识
    List<string> DrawerNoColNoList = new List<string>();

    //药盒集合
    List<BoxModel> BoxList = new List<BoxModel>();
    BoxModel BoxColor = new BoxModel { BoxNo = 1, BoxName = 1 };
    string[] AllDrawerNos;
    string[] DrawerNos;
    string SelectedDrawerNo = "1-1";
    //药盒颜色集合
    List<BoxModel> BoxColorList = new List<BoxModel>()
        {
            new  BoxModel{BoxNo=1,BoxName=1 },
            new  BoxModel{BoxNo=2 ,BoxName=1},
            new  BoxModel{BoxNo=3 ,BoxName=1}
        };
    protected override async Task OnInitializedAsync()
    {
        // AllDrawerNos = await channelListDao.GetDrawerNum(channelStock);
        // if (AllDrawerNos != null && AllDrawerNos.Count() > 0)
        // {
        //     if (DrawerNos == null || DrawerNos.Length <= 0)
        //     {
        //         DrawerNos = new string[] { "无库位" };
        //     }
        // }
        AllDrawerNos = await channelListDao.GetDrawerNumForRemove(channelStock);
        if (AllDrawerNos != null && AllDrawerNos.Count() > 0)
        {
            DrawerNos = AllDrawerNos.Where(d => d.EndsWith('白')).ToArray();
            if (DrawerNos != null && DrawerNos.Length > 0)
                SelectedDrawerNo = DrawerNos[0];
        }
        else
        {
            DrawerNos = new string[] { "无库位" };
        }
        base.OnInitializedAsync();
    }
    async Task LoadData(LoadDataArgs args)
    {
        isLoading = true;

        if (DrawerNos != null && !DrawerNos.Contains("无库位") && DrawerNos.Count() > 0)
        {
            SelectedDrawerNo = DrawerNos[0];
            var result = await channelListDao.GetChannelStockByDrug(channelStock, SelectedDrawerNo, args.Top, args.Skip);
            selectedDrawerData = result.Desserts;
            if (selectedDrawerData != null && selectedDrawerData.Count > 0)
            {
                if (selectedDrawerData[0].DrawerNo <= 30)
                {
                    if (selectedDrawerData[0].ColNo == 1)
                    {
                        BoxColor = BoxColorList[0];
                    }
                    else
                    {
                        BoxColor = BoxColorList[1];
                    }
                }
                else
                {
                    BoxColor = BoxColorList[2];
                }
            }
            count = result.TotalDesserts;
        }
        isLoading = false;
    }

    private async Task OnColorChanged(object value)
    {
        BoxColor = (BoxModel)value;
        if (AllDrawerNos != null && AllDrawerNos.Length > 0 && AllDrawerNos[0] != "无库位")
        {
            if (BoxColor.BoxNo == 3)
            {
                DrawerNos = AllDrawerNos.Where(d => !(d.EndsWith('白')) && !(d.EndsWith('绿')) && !(d.Contains('-'))).ToArray();
                if (DrawerNos != null && DrawerNos.Length > 0 && DrawerNos[0] != "无库位")
                {
                    SelectedDrawerNo = DrawerNos[0];
                    await SelectedDrawerChange(SelectedDrawerNo);
                }
                else
                {
                    SelectedDrawerNo = "无库位";
                }
                await InvokeAsync(StateHasChanged);
            }
            else
            {
                if (BoxColor.BoxNo == 1)
                {
                    DrawerNos = AllDrawerNos.Where(d => d.EndsWith('白')).ToArray();
                    if (DrawerNos != null && DrawerNos.Length > 0 && DrawerNos[0] != "无库位")
                    {
                        SelectedDrawerNo = DrawerNos[0];
                        await SelectedDrawerChange(SelectedDrawerNo);
                    }
                    else
                    {
                        SelectedDrawerNo = "无库位";
                    }
                    await InvokeAsync(StateHasChanged);
                }
                else if (BoxColor.BoxNo == 2)
                {
                    DrawerNos = AllDrawerNos.Where(d => d.EndsWith('绿')).ToArray();
                    if (DrawerNos != null && DrawerNos.Length > 0 && DrawerNos[0] != "无库位")
                    {
                        SelectedDrawerNo = DrawerNos[0];
                        await SelectedDrawerChange(SelectedDrawerNo);
                    }
                    else
                    {
                        SelectedDrawerNo = "无库位";
                    }
                    await InvokeAsync(StateHasChanged);
                }
                // else if (BoxColor.BoxNo == 4)
                // {
                //     DrawerNos = AllDrawerNos.Where(d => !(d.EndsWith('绿')) && !(d.EndsWith('白')) && d.Contains('-')).ToArray();
                //     if (DrawerNos != null && DrawerNos.Length > 0 && DrawerNos[0] != "无库位")
                //     {
                //         SelectedDrawerNo = DrawerNos[0];
                //         await SelectedDrawerChange(SelectedDrawerNo);
                //     }
                //     else
                //     {
                //         SelectedDrawerNo = "无库位";
                //     }
                //     await InvokeAsync(StateHasChanged);

                // }
            }
        }

    }
    void Cancel()
    {
        RestData();
        // 关闭弹窗
        dialogService.Close(false);
    }
    async Task Save()
    {
        if (selectedDrawerData != null && selectedDrawerData.Any(cl => cl.AddQuantity != 0 && cl.DrugId != null && cl.ManuNo != null))
        {
            if (selectedDrawerData.Where(cs => cs.AddQuantity != 0).Sum(cs => cs.AddQuantity) > channelStock.Quantity)
            {
                _message.Notify(new NotificationMessage { Severity = NotificationSeverity.Warning, Summary = "提示", Detail = $"交换总数量不能大于库存", Duration = 4000 });
                return;
            }
            var b = await channelListDao.BoxReplaceFinish(channelStock, selectedDrawerData.Where(cl => cl.AddQuantity != 0).ToList());
            if (!b)
            {
                _message.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "提示", Detail = $"数据保存失败", Duration = 4000 });
                logger.Error($"药盒药品替换保存数据库失败，数据{JsonConvert.SerializeObject(selectedDrawerData.Where(cl => cl.AddQuantity != 0).ToList())}");
            }
            else
            {
                _message.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = "提示", Detail = $"交换完成", Duration = 4000 });
                // 关闭弹窗
                dialogService.Close(true);

            }
            //重置状态
            this.RestData();
        }
        else
        {
            _message.Notify(new NotificationMessage { Severity = NotificationSeverity.Warning, Summary = "提示", Detail = $"无可交换数据或未输入交换数量", Duration = 4000 });
            return;
        }
    }

    async Task SelectedDrawerChange(object drawerNo)
    {
        if (drawerNo == "无库位")
        {
            return;
        }
        drawerNo = drawerNo == "急诊药盒" ? "99-1" : drawerNo == "恢复室药盒" ? "111-1" : drawerNo == "胃镜药盒" ? "31-1" : drawerNo == "导管药盒" ? "32-1" : drawerNo == "生殖药盒" ? "33-1" : drawerNo == "妇门药盒" ? "34-1" : drawerNo;

        var result = await channelListDao.GetChannelStockByDrug(channelStock, drawerNo.ToString(), 8, 0);
        selectedDrawerData = result.Desserts;
    }
    int currentCol = 0;

    RadzenDataGrid<ChannelStock> grid;
    void OnCellClick(DataGridCellMouseEventArgs<ChannelStock> args)
    {
        currentCol = args.Data.ColNo;
        grid.EditRow(args.Data);
    }

    void RestData()
    {
        PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
        this.status = 0;
        // this.BeforeQuantity = new int[9];
        // this.AfterQuantity = new int[9];
        // currentCol = 0;
        // ColNos.Clear();
    }
}