@using AyCode.Blazor.Components.Components.Grids
@using AyCode.Utils.Extensions
@using FruitBank.Common
@using FruitBank.Common.Dtos
@using FruitBank.Common.Entities
@using FruitBank.Common.Models
@using FruitBankHybrid.Shared.Databases
@using FruitBankHybrid.Shared.Services.SignalRs

@inject LoggedInModel LoggedInModel;
@inject FruitBankSignalRClient FruitBankSignalRClient

<MgGridBase @ref="gridOrderItemPallet" Data="OrderItemPallets" IsMasterGrid="IsMasterGrid" AutoSaveLayoutName="GridDetailOrderItemPallets"
			PageSize="@(IsMasterGrid ? 15 : 50)" ShowFilterRow="IsMasterGrid" ShowGroupPanel="IsMasterGrid"
			AutoExpandAllGroupRows="false"
			CssClass="@GridCss"
			ColumnResizeMode="GridColumnResizeMode.NextColumn"
			FilterMenuButtonDisplayMode="@(IsMasterGrid ? GridFilterMenuButtonDisplayMode.Never : GridFilterMenuButtonDisplayMode.Always)">
	<Columns>
		<DxGridDataColumn FieldName="Id" Width="125" />
		<DxGridDataColumn FieldName="OrderItemId" Caption="oiId" Width="125" />
		<DxGridDataColumn FieldName="OrderItemDto.OrderId" Caption="oId" Width="125" />
		<DxGridDataColumn Name="ProductId" FieldName="OrderItemDto.ProductId" Caption="pId" Width="125" Visible="false" />
		<DxGridDataColumn Name="ProductName" FieldName="OrderItemDto.ProductDto.Name" Caption="ProductName" Visible="false" />

		<DxGridDataColumn FieldName="PalletWeight" />
		<DxGridDataColumn FieldName="TareWeight" />

		<DxGridDataColumn FieldName="TrayQuantity" />
		<DxGridDataColumn FieldName="GrossWeight" />
		<DxGridDataColumn FieldName="NetWeight" />
		<DxGridDataColumn FieldName="AverageWeight" ReadOnly="true" Caption="AvgWeight" />

		<DxGridDataColumn FieldName="IsMeasured" ReadOnly="true" />
		<DxGridDataColumn FieldName="IsAudited" ReadOnly="true" />

		<MgGridDataColumn FieldName="@nameof(OrderItemPallet.ModifierId)" ReadOnly="true" UrlLink=@(FruitBankConstClient.BaseUrl + "/Admin/Customer/Edit/{ModifierId}") />
		<DxGridDataColumn FieldName="@nameof(OrderItemPallet.Modified)" ReadOnly="true" DisplayFormat="yyyy.MM.dd hh:mm" />

		<DxGridCommandColumn Visible="!IsMasterGrid" Width="120"></DxGridCommandColumn>
	</Columns>
	<ToolbarTemplate>
		@if (IsMasterGrid)
		{
			<MgGridToolbarTemplate Grid="gridOrderItemPallet" OnReloadDataClick="() => ReloadDataFromDb(true)" />
		}
	</ToolbarTemplate>
	<GroupSummary>
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
						   FieldName="TrayQuantity"
						   FooterColumnName="TrayQuantity" />
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
						   FieldName="NetWeight"
						   FooterColumnName="NetWeight" />
	</GroupSummary>
</MgGridBase>

@code {
	MgGridBase gridOrderItemPallet;

	[Parameter] public bool IsMasterGrid { get; set; } = false;
	[Parameter] public List<OrderItemPallet>? OrderItemPallets { get; set; }

	string GridCss => !IsMasterGrid ? "hide-toolbar" : string.Empty;

	protected override async Task OnInitializedAsync()
	{
		await ReloadDataFromDb(false);
	}

	public async Task ReloadDataFromDb(bool forceReload)
	{
		if (!IsMasterGrid) return;

		LoadingPanelVisibility.Visible = true;
		using (await ObjectLock.GetSemaphore<OrderItemPallet>().UseWaitAsync())
		{
			if (OrderItemPallets == null) OrderItemPallets = await FruitBankSignalRClient.GetAllOrderItemPallets() ?? [];
			else if (OrderItemPallets.Count == 0 || forceReload)
			{
				OrderItemPallets.Clear();
				OrderItemPallets.AddRange(await FruitBankSignalRClient.GetAllOrderItemPallets() ?? []);
			}
		}

		if (OrderItemPallets != null && OrderItemPallets.Any(oip => oip.OrderItemDto?.ProductDto != null))
		{
			gridOrderItemPallet.BeginUpdate();

			gridOrderItemPallet.GetColumns().FirstOrDefault(x => x.Name == "ProductId")!.Visible = true;
			gridOrderItemPallet.GetColumns().FirstOrDefault(x => x.Name == "ProductName")!.Visible = true;

			gridOrderItemPallet.EndUpdate();
		}

		if (forceReload)
			gridOrderItemPallet?.Reload();

		LoadingPanelVisibility.Visible = false;
	}

	protected override Task OnAfterRenderAsync(bool firstRender)
	{
		if (firstRender)
		{
			// if (OrderItemPallets != null && OrderItemPallets.Any(oip => oip.OrderItemDto?.ProductDto != null))
			// {
			// 	gridOrderItemPallet.BeginUpdate();

			// 	gridOrderItemPallet.GetColumns().FirstOrDefault(x => x.Name == "ProductId")!.Visible = true;
			// 	gridOrderItemPallet.GetColumns().FirstOrDefault(x => x.Name == "ProductName")!.Visible = true;

			// 	gridOrderItemPallet.EndUpdate();
			// }
		}

		return base.OnAfterRenderAsync(firstRender);
	}

}

@*     List<GenericAttribute> GenericAttributes { get; set; }
    List<OrderItemPallet> OrderItemPallets { get; set; }
    OrderDto OrderDto { get; set; }
    bool IsMeasured
    bool IsMeasurable
    int TrayQuantity
    double NetWeight
    double GrossWeight

        public Guid OrderItemGuid { get; set; }
        public int OrderId { get; set; }
        public int ProductId { get; set; }
        public int Quantity { get; set; }

        public decimal UnitPriceInclTax { get; set; }
        public decimal UnitPriceExclTax { get; set; }

        public decimal PriceInclTax { get; set; }
        public decimal PriceExclTax { get; set; }

        public string AttributesXml { get; set; }
        public decimal? ItemWeight { get; set; }

        public string ProductName => ProductDto?.Name ?? "ProductDto is null!!!";

        public TProductDto? ProductDto { get; set; }
 *@