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

@inject LoggedInModel LoggedInModel;
@inject FruitBankSignalRClient FruitBankSignalRClient

<MgGridBase @ref="@Grid" Data="OrderDtos" IsMasterGrid="IsMasterGrid" AutoSaveLayoutName="GridDetailOrderDto"
			ShowFilterRow="IsMasterGrid" ShowGroupPanel="IsMasterGrid"
			AutoExpandAllGroupRows="false" 
			CssClass="@GridCss"
			ColumnResizeMode="GridColumnResizeMode.NextColumn" 
			FilterMenuButtonDisplayMode="@(IsMasterGrid ? GridFilterMenuButtonDisplayMode.Never : GridFilterMenuButtonDisplayMode.Always)">
	<Columns>
		<MgGridDataColumn FieldName="Id" SortIndex="0" SortOrder="GridColumnSortOrder.Descending" 
						  UrlLink=@(FruitBankConstClient.BaseUrl+"/Admin/Order/Edit/{Id}") />
		<MgGridDataColumn FieldName="CustomerId" UrlLink=@(FruitBankConstClient.BaseUrl + "/Admin/Customer/Edit/{CustomerId}") />
		<DxGridDataColumn FieldName="@("Customer.Company")" Caption="Company" ReadOnly="true" />
		<DxGridDataColumn FieldName="OrderStatus" />
		<DxGridDataColumn FieldName="IsMeasurable" ReadOnly="true" />
		<DxGridDataColumn FieldName="MeasuringStatus" ReadOnly="true" />
		@* <DxGridDataColumn FieldName="IsMeasured" ReadOnly="true" /> *@
		
		<DxGridDataColumn FieldName="OrderTotal" Caption="Végösszeg (br.)"/>

		<DxGridDataColumn FieldName="IsAllOrderItemAvgWeightValid" ReadOnly="true" Caption="AvgWeightValid" />
		
		<MgGridDataColumn FieldName="RevisorId" ReadOnly="true" UrlLink=@(FruitBankConstClient.BaseUrl + "/Admin/Customer/Edit/{RevisorId}") />
		<MgGridDataColumn FieldName="MeasurementOwnerId" ReadOnly="true" UrlLink=@(FruitBankConstClient.BaseUrl + "/Admin/Customer/Edit/{MeasurementOwnerId}") />
		<DxGridDataColumn FieldName="DateOfReceipt" DisplayFormat="yyyy.MM.dd hh:mm" />
		<DxGridDataColumn FieldName="CreatedOnUtc" ReadOnly="true" DisplayFormat="yyyy.MM.dd hh:mm" />
		<DxGridCommandColumn Visible="!IsMasterGrid" Width="120"></DxGridCommandColumn>
	</Columns>
	<DetailRowTemplate>
		@if (IsMasterGrid && LoggedInModel.IsAdministrator)
		{
			var orderDto = ((OrderDto)context.DataItem);

			<DxTabs ActiveTabIndexChanged="(i) => OnActiveTabChanged(i)">
				<DxTabPage Text="Rendelés tételek">
					<GridDetailOrderItemDto OrderItemDtos="orderDto.OrderItemDtos" IsMasterGrid="false" />
				</DxTabPage>
				<DxTabPage Text="Mérések" Visible="@LoggedInModel.IsAdministrator">
					@{
						var orderItemPalletDtos = orderDto?.OrderItemDtos.SelectMany(oi => oi.OrderItemPallets).ToList() ?? [];
						<GridDetailOrderItemPallets OrderItemPallets="orderItemPalletDtos"  IsMasterGrid="false"/>
					}
				</DxTabPage>
				<DxTabPage Text="Rendelés jegyzetek" Visible="@LoggedInModel.IsAdministrator">
					@{
						// var orderItemPalletDtos = orderDto?.OrderItemDtos.SelectMany(oi => oi.OrderItemPallets).ToList() ?? [];
						// <GridDetailOrderItemPallets OrderItemPallets="orderItemPalletDtos" IsMasterGrid="false" />
					}
				</DxTabPage>
				<DxTabPage Text="Speciális jellemzők" Visible="@LoggedInModel.IsAdministrator">
					@{
						var genericAttributeDtos = new AcObservableCollection<GenericAttributeDto>(orderDto.GenericAttributes);
						<GridGenericAttribute ParentDataItem="@orderDto" GenericAttributes="@genericAttributeDtos" />
					}
				</DxTabPage>

			</DxTabs>
		}
	</DetailRowTemplate>
	<ToolbarTemplate>
		@if (IsMasterGrid)
		{
			<MgGridToolbarTemplate Grid="Grid" OnReloadDataClick="() => ReloadDataFromDb(true)"/>
		}
	</ToolbarTemplate>
	@* <GroupSummary>
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
						   FieldName="Quantity"
						   FooterColumnName="Quantity" />
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
						   FieldName="NetWeight"
						   FooterColumnName="NetWeight" />
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
						   FieldName="PriceInclTax"
						   FooterColumnName="PriceInclTax" />
	</GroupSummary> *@
	<GroupSummary>
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Count"
						   FieldName="Id" 
						   ValueDisplayFormat="'{0} rendelés'" />
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Count"
						   FieldName="Id"
						   FooterColumnName="Id" />
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Sum"
						   FieldName="OrderTotal"
						   FooterColumnName="OrderTotal" />
	</GroupSummary>
	<TotalSummary>
		<DxGridSummaryItem SummaryType="GridSummaryItemType.Count"
						   FieldName="Id"
						   FooterColumnName="Id" />
	</TotalSummary>
</MgGridBase>

@code {
	[Parameter] public bool IsMasterGrid { get; set; } = false;
	//[Parameter] public OrderDto? OrderDto { get; set; }
	[Parameter] public List<OrderDto>? OrderDtos { get; set; }

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

	MgGridBase Grid;
	int _activeTabIndex;
	protected override async Task OnInitializedAsync()
	{
		// if (OrderDto != null)
		// 	OrderItemDtos = OrderDto.OrderItemDtos;

		await ReloadDataFromDb(false);
	}

	private async Task ReloadDataFromDb(bool forceReload = false)
	{
		LoadingPanelVisibility.Visible = true;

		if (IsMasterGrid)
		{
			using (await ObjectLock.GetSemaphore<OrderDto>().UseWaitAsync())
			{
				if (OrderDtos == null) OrderDtos = await FruitBankSignalRClient.GetAllOrderDtos() ?? [];
				else if (OrderDtos.Count == 0 || forceReload)
				{
					OrderDtos.Clear();
					OrderDtos.AddRange(await FruitBankSignalRClient.GetAllOrderDtos() ?? []);
				}
			}

			//if (forceReload)
			Grid?.Reload();
		}
		LoadingPanelVisibility.Visible = false;
	}

	// void OnCustomizeElement(GridCustomizeElementEventArgs e)
	// {
	// 	if (e.ElementType == GridElementType.DataCell)
	// 	{
	// 		//if (some_condition)
	// 			e.Attributes["title"] = "some tooltip";
	// 	}
	// }

	// void Grid_CustomizeElement(GridCustomizeElementEventArgs e)
	// {
	// 	if (e.ElementType == GridElementType.DataCell)
	// 	{
	// 		var fieldName = ((DxGridDataColumn)e.Column).FieldName;
	// 		var cellIdentifier = e.VisibleIndex + ":" + fieldName;
            
	// 		e.Attributes["data-id"] = cellIdentifier;
	// 		e.Attributes["onmouseenter"] = EventCallback.Factory.Create<MouseEventArgs>(
	// 			this,
	// 			async _ =>
	// 			{
	// 				hoveredCellInfo = fieldName + ": " + e.Grid.GetRowValue(e.VisibleIndex, fieldName);
	// 				selector = "td[data-id=\"" + cellIdentifier + "\"]";
	// 				await Hint.ShowAsync();
	// 			});
	// 	}
	// }

	protected async Task OnActiveTabChanged(int activeTabIndex)
	{
		_activeTabIndex = activeTabIndex;
		return;

		// switch (_activeTabIndex)
		// {
		// 	case 0:
		// 		if(ProductDtos == null)
		// 			ProductDtos = (await FruitBankSignalRClient.GetProductDtos() ?? []); //.Where(o => o.HasMeasuringAccess(LoggedInModel.CustomerDto?.Id, LoggedInModel.IsRevisor)).OrderBy(o => o.DateOfReceipt).ToList();
		// 		break;
		// 	case 1:
		// 		if(OrderDtos == null)
		// 			OrderDtos = (await FruitBankSignalRClient.GetAllOrderDtos() ?? []).OrderByDescending(o => o.Id).ToList(); //.Where(o => o.HasMeasuringAccess(LoggedInModel.CustomerDto?.Id, LoggedInModel.IsRevisor)).OrderBy(o => o.DateOfReceipt).ToList();
		// 		break;
		// 	case 2:
		// 		if (OrderItemDtos == null)
		// 			OrderItemDtos = (await FruitBankSignalRClient.GetAllOrderItemDtos() ?? []).OrderByDescending(o => o.Id).ToList(); //.Where(o => o.HasMeasuringAccess(LoggedInModel.CustomerDto?.Id, LoggedInModel.IsRevisor)).OrderBy(o => o.DateOfReceipt).ToList();
		// 		break;
		// }
	}
}

