@page "/product/stock/list"

@inject ILogger<ProductStockList> Logger
@attribute [Authorize]

<PageTitle>产品库存列表</PageTitle>
<Card Class="mt-3">
	<Table DataSource="PagingList.Items" PageSize="100" HidePagination="true" Resizable>
		<TitleTemplate>
			<Flex Justify="FlexJustify.SpaceBetween">
				产品库存列表
			</Flex>
		</TitleTemplate>
		<ColumnDefinitions>
			<PropertyColumn Property="c=>c.Title" Title="名称"></PropertyColumn>
			<ActionColumn Title="规格">
				@foreach (var item in context.Sku)
				{
					<AntDesign.Text>
						@item.ValueName
						@if (item.Weight > 0)
						{
							<AntDesign.Text>（@($"{item.Weight}{@GetWeightUnit(item.WeightUnit)}")）</AntDesign.Text>
						}
					</AntDesign.Text>
				}
			</ActionColumn>
			<PropertyColumn Property="c=>c.Weight" Title="重量" Width="150px" Align="ColumnAlign.Center">
				@context.Weight.RemoveTrailingZeros()
			</PropertyColumn>
			<PropertyColumn Property="c=>c.StockQuantity" Title="库存" Width="80px" Align="ColumnAlign.Center">
			</PropertyColumn>
			<PropertyColumn Property="c=>c.UpdateTime" Title="更新时间" Width="200px" />
			<ActionColumn Title="操作" Align="ColumnAlign.Right" Width="180px">
				<Space>
					<SpaceItem>
						<a @onclick="(e)=>OnClickAddStock(context)">入库</a>
					</SpaceItem>
				</Space>
			</ActionColumn>
		</ColumnDefinitions>
	</Table>
	<br />
	<Row Justify="RowJustify.End">
		<Pagination Current="PagingList.Index" Total="PagingList.Count" PageSize="PagingList.Size" ShowSizeChanger="false" OnChange="OnPageChanged"></Pagination>
	</Row>
</Card>


<Drawer Closable="true" Width="520" Visible="drawerVisible" Title='("规格库存入库")' OnClose="_=>CloseDrawer()">
	<Form LabelColSpan="4" @ref="@editform" Model="@model" OnFinish="OnFormFinish">
		<FluentValidationValidator />
		<FormItem Label="产品标题">
			@model.Title
		</FormItem>
		<FormItem Label="规格">
			@if (model.Sku != null)
			{
				@foreach (var item in model.Sku)
				{
					<GridRow>
						<GridCol>@item.AttributeName</GridCol>
						<GridCol>
							@item.ValueName
							@if (item.Weight > 0)
							{
								<AntDesign.Text>（@($"{item.Weight}{@GetWeightUnit(item.WeightUnit)}")）</AntDesign.Text>
							}
						</GridCol>
					</GridRow>
				}
			}
		</FormItem>
		<FormItem Label="新增库存">
			<Input @bind-Value="@model.AddStockQuantity"></Input>
		</FormItem>
		<FormItem WrapperColOffset="4">
			<Button Type="ButtonType.Primary" HtmlType="submit" Style="width: 100%;">保存</Button>
		</FormItem>
	</Form>
</Drawer>

@code {
	[SupplyParameterFromQuery]
	int? Page { get; set; }

	[SupplyParameterFromQuery(Name = "size")]
	int? PageSize { get; set; }

	[SupplyParameterFromForm]
	ProductStockUnitSearch search { get; set; } = new();
	Form<ProductStockUnitSearch> searchForm = null!;

	PagingList<ProductStockUnitModel> PagingList = new();

	[SupplyParameterFromForm]
	ProductStockModel model { get; set; } = new();
	Form<ProductStockModel> editform = null!;

	bool loading { get; set; } = true;
	bool searchExpand { get; set; } = false;
	private bool drawerVisible;

	protected override void OnInitialized()
	{
		base.OnInitialized();
	}

	protected override void OnParametersSet()
	{

		loadQueryString();
		LoadList();

		base.OnParametersSet();
	}

	void loadQueryString()
	{
		var uri = new Uri(Navigation.Uri);
		var query = uri.Query;
		search.Key = query.GetQueryString("Key");
		search.Type = query.GetQueryString("Type").ToInt();
	}

	void OnSearchFinish()
	{
		Page = Page.GetValueOrDefault(1) - 1;

		OnSearch(Page.Value);
	}


	private void OnSearchReset()
	{
		search = new();
		LoadList();
	}

	private async void LoadList()
	{

		loading = true;
		var url = "/api/product/stock/search";
		var apiResult = await HttpService.GetPagingList<ProductStockUnitModel>(url, search, Page.GetValueOrDefault(1), PageSize.GetValueOrDefault(20));
		if (apiResult.Success)
		{
			if (apiResult.Data != null)
			{
				PagingList = apiResult.Data;
			}
		}
		loading = false;
		StateHasChanged();
	}


	private void OnReset()
	{
		search = new();
		LoadList();
	}

	private void OnSearch(int page)
	{
		var queryString = search.BuildQueryString();
		if (string.IsNullOrEmpty(queryString))
		{
			if (page > 1)
			{
				Navigation.NavigateTo($"/product/stock/list?page={page}");
			}
			else
			{
				Navigation.NavigateTo($"/product/stock/list");
			}
		}
		else
		{
			if (page > 1)
			{
				Navigation.NavigateTo($"/product/stock/list?page={page}&{queryString}");
			}
			else
			{
				Navigation.NavigateTo($"/product/stock/list?{queryString}");
			}
		}
	}



	void OnPageChanged(PaginationEventArgs args)
	{
		OnSearch(args.Page);
	}

	string PriceFormat(decimal value)
	{
		return value.ToString("G");
	}

	void CloseDrawer()
	{
		drawerVisible = false;
		editform.Reset();
	}

	void OnClickAddStock(ProductStockUnitModel item)
	{
		model = item.Adapt<ProductStockModel>();
		drawerVisible = true;
	}

	async Task OnFormFinish()
	{
		if (editform.Validate())
		{
			var result = new ApiResult<string>();



			var url = $"api/product/skustock/add";
			result = await HttpService.Post<ApiResult<string>>(url, model);
			if (result.Code == (int)ResultCode.Success)
			{

				CloseDrawer();
				LoadList();
				await ModalService.InfoAsync(new ConfirmOptions() { Title = "提示", Content = "数据提交成功!" });
			}
			else
			{
				await ModalService.ErrorAsync(new ConfirmOptions() { Title = "服务异常", Content = result.Message });
			}
		}
	}

	string GetWeightUnit(int weightUnit)
	{

		switch (weightUnit)
		{
			case 1:
				return $"mg";
			case 3:
				return $"kg";
			case 4:
				return $"t";
			case 5:
				return $"lb";
			case 6:
				return $"oz";
			default:
				return $"g";
		}
	}
} 