@using AyCode.Core.Loggers
@using FruitBank.Common.Dtos
@using FruitBank.Common.Entities
@using FruitBank.Common.Helpers
@using FruitBank.Common.Interfaces
@using FruitBank.Common.Models
@using FruitBank.Common.SignalRs
@using FruitBankHybrid.Shared.Extensions
@using FruitBankHybrid.Shared.Services
@using FruitBankHybrid.Shared.Services.SignalRs

@typeparam TPalletItem where TPalletItem : class, IMeasuringItemPalletBase

<DxFormLayout Context="ctxFromLayoutPallet" Data="@PalletItem" CaptionPosition="CaptionPosition.Vertical" CssClass="w-100 measuring-form-layout"
			  ItemUpdating="@((pair) => OnItemUpdating(pair.Key, pair.Value, PalletItem))" Enabled="Editable">

	<DxFormLayoutItem Context="ctxFromLayoutItemPallet" ColSpanMd="1" BeginRow="true">
		<b>@(MeasuringIndex). MÉRÉS</b>
	</DxFormLayoutItem>


	<DxFormLayoutItem Context="ctxFromLayoutItemPallet" CaptionCssClass="@(GetOrderItemPalletsCssClassNames(nameof(IMeasuringItemPalletBase.PalletWeight)))"
					  Field="@nameof(ShippingItemPallet.PalletWeight)"
					  Enabled="@(Editable && IsMeasurable && ProductId > 0)" Visible="@(IsMeasurable)"
					  Caption="Rakl.súly(kg)" ColSpanMd="2" />

	<DxFormLayoutItem Context="ctxFromLayoutItemPallet" CaptionCssClass="@(GetOrderItemPalletsCssClassNames(nameof(IMeasuringItemPalletBase.TareWeight)))"
					  Field="@nameof(ShippingItemPallet.TareWeight)"
					  Enabled="@(Editable && IsMeasurable && ProductId > 0)" Visible="@(IsMeasurable)"
					  Caption="Tára(kg)" ColSpanMd="2" />

	@* <DxFormLayoutItem Context="ctxFromLayoutItemPallet" ColSpanMd="1" /> *@

	<DxFormLayoutItem Context="ctxFromLayoutItemPallet" CaptionCssClass="@(GetOrderItemPalletsCssClassNames(nameof(IMeasuringItemPalletBase.TrayQuantity)))"
					  Field="@nameof(ShippingItemPallet.TrayQuantity)"
					  Enabled="@(Editable && ProductId > 0)"
					  Caption="Rekesz/csomag" ColSpanMd="2" />

	<DxFormLayoutItem Context="ctxFromLayoutItemPallet" CaptionCssClass="@(GetOrderItemPalletsCssClassNames(nameof(IMeasuringItemPalletBase.GrossWeight)))"
					  Field="@nameof(ShippingItemPallet.GrossWeight)"
					  Enabled="@(Editable && IsMeasurable && ProductId > 0)" Visible="@(IsMeasurable)"
					  Caption="Br.súly(kg)" ColSpanMd="2">
	</DxFormLayoutItem>

	<DxFormLayoutItem Context="ctxFromLayoutItemPallet" Caption="Net(kg)" ColSpanMd="1" Visible="@(IsMeasurable)"
	                  CaptionCssClass="@(GetOrderItemPalletsCssClassNames(nameof(IMeasuringItemPalletBase.NetWeight)))">
		<text>@(PalletItem.NetWeight) kg.</text>
	</DxFormLayoutItem>

	<DxFormLayoutItem Context="ctxFromLayoutItemPallet" ColSpanMd="@(HasAuditButton ? 1 : 2)">
		<DxButton Enabled="@(Editable && BtnSaveEnabled)" Text="@(PalletItem.Id == 0 ? "Mentés" : "Módosít")" Click="() => PalletItemSaveClick()" CssClass="w-100" />
	</DxFormLayoutItem>

	@if (HasAuditButton)
	{
		<DxFormLayoutItem Context="ctxFromLayoutItemPallet" ColSpanMd="1">
			<DxButton Enabled="@(Editable && OrderItemPallet!.IsMeasuredAndValid(IsMeasurable) && !OrderItemPallet.IsAudited && IsMaxTrayQuantityValid)"
					  Text="@(OrderItemPallet!.IsAudited ? "Jóváhagyva" : "Jóváhagy")" Click="() => PalletItemAuditedClick()" CssClass="w-100" />
		</DxFormLayoutItem>
	}
</DxFormLayout>

	@code {
	[Inject] public required IEnumerable<IAcLogWriterClientBase> LogWriters { get; set; }
	[Inject] public required FruitBankSignalRClient FruitBankSignalRClient { get; set; }
	[Inject] public required LoggedInModel LoggedInModel { get; set; }
	[Inject] private IDialogService DialogService { get; set; } = null!;

	[Parameter] public required TPalletItem PalletItem { get; set; }
	[Parameter] public required bool IsMeasurable { get; set; }
	[Parameter] public required int ProductId { get; set; }
	[Parameter] public required int MeasuringIndex { get; set; }
	[Parameter] public int? AddOrUpdateSignalRTag { get; set; } = null;

	[Parameter] public int? MaxTrayQuantity { get; set; } = null;
	[Parameter] public bool Editable { get; set; } = true;

	[Parameter] public Func<TPalletItem?, Task>? OnPalletItemSaved { get; set; }
	[Parameter] public Func<TPalletItem, Task>? OnPalletItemValueChanged { get; set; }
	[Parameter] public Func<TPalletItem?, Task>? OnPalletItemAudited { get; set; }

	/// <summary>
	/// Before Save or Audit
	/// </summary>
	[Parameter] public Func<TPalletItem?, Task>? OnPalletItemSaveOrAuditClick { get; set; }

	//public bool LoadingPanelVisible { get; set; } = false;
	//public bool Editable => !HasAuditButton || (OrderItemPallet.IsAudited);
	public bool BtnSaveEnabled { get; set; }


	bool HasAuditButton => LoggedInModel.IsRevisor && IsOrderItemPallet;


	public bool IsOrderItemPallet => OrderItemPallet != null;
	public OrderItemPallet? OrderItemPallet => (PalletItem as OrderItemPallet);

	private bool GetBtnSaveEnabled()
	{
		return Editable && PalletItem.IsValidMeasuringValues(IsMeasurable) && !PalletItem.IsMeasured && IsMaxTrayQuantityValid;
	}

	private bool IsMaxTrayQuantityValid => (!MaxTrayQuantity.HasValue || PalletItem.TrayQuantity <= MaxTrayQuantity.Value);

	protected override async Task OnInitializedAsync()
	{
		BtnSaveEnabled = GetBtnSaveEnabled();// PalletItem.IsValidMeasuringValues(IsMeasurable) && !PalletItem.IsMeasured;

		//((DxSpinEdit<double>)_weightFormLayoutItem.Template.Target).DisplayFormat = "N3";
		await base.OnInitializedAsync();
	}


	private string GetOrderItemPalletsCssClassNames(string fieldName)
		=> MeasurementService.GetCustomItemPalletsCssClassNames(fieldName, PalletItem, IsMeasurable, MaxTrayQuantity);

	private async Task PalletItemSaveClick()
	{
		BtnSaveEnabled = false;
		//LoadingPanelVisible = true;

		if (AddOrUpdateSignalRTag == null) throw new Exception($"PalletItemComponent->PalletItemSaveClick(); AddOrUpdateSignalRTag == null");

		PalletItem.ModifierId = LoggedInModel.CustomerDto?.Id;

		if (OnPalletItemSaveOrAuditClick != null) await OnPalletItemSaveOrAuditClick.Invoke(PalletItem);

		var responseShippingItemPallet = await FruitBankSignalRClient.PostDataAsync(AddOrUpdateSignalRTag!.Value, PalletItem);
		if (responseShippingItemPallet != null) PalletItem.Id = responseShippingItemPallet.Id; //Az UpdateCollection miatt kell, hogy megtalálja mit kell kicserélni! - J.
		//else _logger.Error($"Sikertelen volt a raklap adatainak mentése!");

		if (OnPalletItemSaved != null) await OnPalletItemSaved.Invoke(responseShippingItemPallet);
		//LoadingPanelVisible = false;

		await InvokeAsync(StateHasChanged);
	}

	protected async Task OnItemUpdating(string fieldName, object newValue, TPalletItem palletItem)
	{
		BtnSaveEnabled = false;
		// if (SelectedOrderItem == null) return;

		switch (fieldName)
		{
			case nameof(IMeasuringItemPalletBase.PalletWeight):
				palletItem.PalletWeight = double.Round((double)newValue, 0);

				if (palletItem.PalletWeight < 0) palletItem.PalletWeight = 0;
				break;

			case nameof(IMeasuringItemPalletBase.TareWeight):
				palletItem.TareWeight = double.Round((double)newValue, 1);

				if (palletItem.TareWeight < 0) palletItem.TareWeight = 0;
				break;
			case nameof(IMeasuringItemPalletBase.TrayQuantity):
				palletItem.TrayQuantity = (int)newValue;

				if (palletItem.TrayQuantity < 0) palletItem.TrayQuantity = 0;
				//else if (!IsMaxTrayQuantityValid) palletItem.TrayQuantity = MaxTrayQuantity!.Value;

				break;
			case nameof(IMeasuringItemPalletBase.GrossWeight):
				palletItem.GrossWeight = double.Round((double)newValue, 1);

				if (palletItem.GrossWeight < 0) palletItem.GrossWeight = 0;
				break;
		}

		palletItem.IsMeasured = false;
		//MeasuringValuesHelper.SetShippingItemTotalMeasuringValues(palletItem);
		//BtnSaveEnabled = SelectedShippingItem.IsValidMeasuringValues() && shippingItemPallet.IsValidMeasuringValues(SelectedShippingItem.IsMeasurable);

		BtnSaveEnabled = GetBtnSaveEnabled();// palletItem.IsValidMeasuringValues(IsMeasurable) && !palletItem.IsMeasured && (MaxTrayQuantity.HasValue && palletItem.TrayQuantity <= MaxTrayQuantity.Value);

		if (OnPalletItemValueChanged != null) await OnPalletItemValueChanged.Invoke(palletItem);
	}

	private async Task PalletItemAuditedClick()
	{
		if (OnPalletItemAudited != null)
		{
			if (OrderItemPallet == null) throw new Exception($"PalletItemComponent->PalletItemAuditedClick(); OrderItemPallet == null");

			if (await DialogService.ShowConfirmBoxAsync("Megerősítés", "Biztoan jóváhagyja a mérést? Jóváhagyás után a mérés nem módosítható!", MessageBoxRenderStyle.Info))
			{
				if (OnPalletItemSaveOrAuditClick != null) await OnPalletItemSaveOrAuditClick.Invoke(PalletItem);

				OrderItemPallet.RevisorId = LoggedInModel.CustomerDto!.Id;

				await InvokeAsync(StateHasChanged); //Az Audit button miatt kell a StateHasChanged(), most már van RevisorId és emiatt disabled lesz...

				PalletItem.SetParentPropToNull();

				var responseShippingItemPallet = await FruitBankSignalRClient.PostDataAsync(AddOrUpdateSignalRTag!.Value, PalletItem);
				if (responseShippingItemPallet == null)
				{
					OrderItemPallet.RevisorId = 0; //Sikertelen volt a mentés...
					await DialogService.ShowMessageBoxAsync("Hiba", "Adatok mentése sikertelen volt, ellenőrizze a mérés adatait!", MessageBoxRenderStyle.Danger);
				}

				await OnPalletItemAudited.Invoke(responseShippingItemPallet);
			}
		}
	}

}
