@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>
            <RadzenDropDown @bind-Value="SelectedDrawerNo" Data="@DrawerNos" Style="display: block;" Change="@(args => SelectedDrawerChange(args))" Name="DropDownChangeEvent">
              
                    <RadzenText TextStyle="TextStyle.Subtitle2" class="mb-0">@(SelectedDrawerNo)</RadzenText>
           
            </RadzenDropDown>

        </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="药盒号">
                </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 NotificationService _message
    @inject PortUtil PortUtil;
    private readonly ILog logger = LogManager.GetLogger(typeof(OrderDetailDialog));

    int status;
    bool isLoading;
    int count;
    string[] DrawerNos;
    string SelectedDrawerNo="";

    [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>();

    protected override async Task OnInitializedAsync()
    {
        DrawerNos = await channelListDao.GetDrawerNum(channelStock);
        base.OnInitializedAsync();
    }
    async Task LoadData(LoadDataArgs args)
    {
        isLoading = true;

        if (DrawerNos != null && DrawerNos.Count() > 0)
        {
            SelectedDrawerNo = DrawerNos[0];
            var result = await channelListDao.GetChannelStockByDrug(channelStock, SelectedDrawerNo, args.Top, args.Skip);
            selectedDrawerData = result.Desserts;
        count = result.TotalDesserts;
        }
        isLoading = false;
    }
    void RestData()
    {
        // PortUtil.speechSynthesizer.SpeakAsyncCancelAll();
        // this.status = 0;
        // data.ForEach(it =>
        // {
        //     it.Status = 0;
        //     it.BeforeQuantity = new int[9];
        //     it.AfterQuantity = new int[9];
        // });
        // this.WeightFinnalQuantity = new int[9];
        // DrawerNoColNoList.Clear();
    }
    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.Quantity) > 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)
    {
        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);
    }
}