@page "/product/list"
@inject ILogger<ProductList> Logger
@attribute [Authorize]

<PageTitle>产品管理</PageTitle>

<Title Level="4">产品列表</Title>
<Card>
	<Form @ref="searchForm" Model="search" Layout="FormLayout.Inline" Class="search-form" OnFinish="OnSearchFinish">
		<Row Justify="RowJustify.Start" Gutter="16">
			<Col>
			<FormItem Label="名称">
				<Input @bind-Value="search.Title" Placeholder="名称" AllowClear />
			</FormItem>
			</Col>

			<Col>
			<div class="ant-form-item" style="width:200px;display:flex;">
				<Button Type="ButtonType.Primary" HtmlType="submit">查询</Button>
				<Button Style="margin: 0 8px;" OnClick="OnSearchReset">重置</Button>
			</div>
			</Col>
		</Row>
	</Form>
</Card>

<Card Class="mt-3">
	<Table DataSource="PagingList.Items" PageSize="100" HidePagination="true" Resizable>
		<TitleTemplate>
			<Flex Justify="FlexJustify.SpaceBetween">
				产品列表
				<div>
					<Button Class="me-3" OnClick="OnCreateClick" Type="ButtonType.Primary">新增</Button>
				</div>
			</Flex>
		</TitleTemplate>
		<ColumnDefinitions>
			<PropertyColumn Property="c=>c.Title" Title="名称">
				<div>@context.Title</div>
				<Text Copyable Type="TextElementType.Secondary" CopyConfig="CopyHint">@context.Id</Text>
			</PropertyColumn>
			<PropertyColumn Property="c=>c.StockQuantity" Title="库存" Width="150px" Align="ColumnAlign.Center" />
			<PropertyColumn Property="c=>c.DisplayOrder" Title="排序" Width="150px" Align="ColumnAlign.Center" />
			<PropertyColumn Property="c=>c.Status" Title="状态" Width="80px" Align="ColumnAlign.Center">
				@if (context.Status == 1)
				{
					<AntDesign.Text Type="TextElementType.Success"><Icon Type="check" Theme=" IconThemeType.Outline" Width="1.3em" Height="1.3em" /></AntDesign.Text>

				}
				else
				{
					<Icon Type="close" Theme="IconThemeType.Outline" Width="1.3em" Height="1.3em" />
				}
			</PropertyColumn>
			<PropertyColumn Property="c=>c.CreateTime" Title="时间" Width="200px" />
			<ActionColumn Title="操作" Align="ColumnAlign.Right" Width="180px">
				<Space>
					<SpaceItem>
						<a @onclick="(e)=>OnClickAddStock(context)">入库</a>
					</SpaceItem>
					<SpaceItem>
						<a @onclick="(e)=>OnEditClick(context.Id)">编辑</a>
					</SpaceItem>
					<SpaceItem>
						<Popconfirm Placement="@Placement.Left" Title="@("删除这条数据无法恢复，您确定要删除吗?")"
									OnConfirm="@(e=>HandleDeleteConfirmAsync(e,context.Id))"
									OkText="确定"
									CancelText="取消">
							<a>删除</a>
						</Popconfirm>
					</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="5" @ref="@stockForm" Model="@stockModel" OnFinish="OnStockFormFinish">
		<FluentValidationValidator />
		<FormItem Label="产品名称">
			@stockModel.Title
		</FormItem>
		@if (!stockModel.AddAttribute)
		{
			@foreach (var item in stockModel.ProductStockAttributes)
			{
				<FormItem Label="@item.Name">
					<Select @bind-Value="@item.AttributeValue.OptionId" TItemValue="long" TItem="long">
						<SelectOptions>
							@foreach (var value in item.ProductAttributeValues)
							{
								<SelectOption Value="@value.Id" Label="@GetAttributeValue(value)" />
							}

						</SelectOptions>
					</Select>
				</FormItem>
			}

		}
		<FormItem Label="规格">
			<Checkbox @bind-Value="@stockModel.AddAttribute" Disabled=false>
				设置新规格
			</Checkbox>
		</FormItem>
		@if (stockModel.AddAttribute)
		{
			@foreach (var item in stockModel.ProductStockAttributes)
			{
				<FormItem Label="@item.Name">
					<Input @bind-Value="@item.AttributeValue.Name" Placeholder="请输入规格" Style="width:160px;"></Input>
					@if (item.WeightIsRequired)
					{
						<AntDesign.Input Type="InputType.Text" @bind-Value="@item.AttributeValue.Weight" Placeholder="重量" WrapperStyle="width:80px">
							<Suffix>@GetWeightUnit(item.WeightUnit)</Suffix>
						</AntDesign.Input>
					}
				</FormItem>
			}
		}
		<FormItem Label="SKU编码">
			<Input @bind-Value="stockModel.ProductAttributeCombination.SkuNumber" For="(()=>stockModel.ProductAttributeCombination.SkuNumber)" />
		</FormItem>
		<FormItem Label="存放仓库">
			<AutoComplete TOption="SelectItem" Placeholder="输入或选择仓储" @bind-Value="@stockModel.WarehouseId"
						  OnInput="(e) => OnWarehouseInput(e)"
						  Options="warehouseSelectItems">
				<OptionTemplate Context="option">
					<AutoCompleteOption Value="@option.Value.Id" Label="@option.Value.Name">
					</AutoCompleteOption>
				</OptionTemplate>
			</AutoComplete>
		</FormItem>
		<FormItem Label="新增库存">
			<Input Type="InputType.Number" @bind-Value="stockModel.AddStockQuantity" For="(()=>stockModel.AddStockQuantity)" />
		</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]
	ProductSearch search { get; set; } = new();
	Form<ProductSearch> searchForm = null!;

	PagingList<Product> PagingList = new();
	bool loading { get; set; } = true;
	bool searchExpand { get; set; } = false;

	[SupplyParameterFromForm]
	ProductAddStockModel stockModel { get; set; } = new();
	Form<ProductAddStockModel> stockForm = null!;
	bool drawerVisible;
	string WarehouseName = string.Empty;
	List<SelectItem> warehouseSelectItems = new();

	public TypographyCopyableConfig CopyHint { get; set; } = null!;

	protected override void OnInitialized()
	{
		CopyHint = new() { OnCopy = () => MessageService.Success("复制成功") };
		base.OnInitialized();
	}

	protected override void OnParametersSet()
	{

		loadQueryString();
		LoadList();

		base.OnParametersSet();
	}

	void loadQueryString()
	{
		var uri = new Uri(Navigation.Uri);
		var query = uri.Query;
		search.Title = query.GetQueryString("Title");
		search.CategoryId = query.GetQueryString("CategoryId");

		var data = query.GetQueryString("RangeTime");
		if (!string.IsNullOrEmpty(data))
		{
			var rangetime = data.Split("-");
			if (rangetime != null && rangetime.Length > 0)
			{
				searchExpand = true;
				search.RangeTime[0] = rangetime[0].NumberToDateTime();
				search.RangeTime[1] = rangetime[1].NumberToDateTime();
				StateHasChanged();
			}
		}

	}

	void OnSearchFinish()
	{
		Page = Page.GetValueOrDefault(1) - 1;
		MessageService.Info("正在查询数据...");
		OnSearch(Page.Value);
	}


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

	private async void LoadList()
	{

		loading = true;
		var url = "/api/product/search";
		var apiResult = await HttpService.GetPagingList<Product>(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/list?page={page}");
			}
			else
			{
				Navigation.NavigateTo($"/product/list");
			}
		}
		else
		{
			if (page > 1)
			{
				Navigation.NavigateTo($"/product/list?page={page}&{queryString}");
			}
			else
			{
				Navigation.NavigateTo($"/product/list?{queryString}");
			}
		}
	}

	async Task HandleDeleteConfirmAsync(MouseEventArgs e, long id)
	{
		var url = $"/api/product/delete/{id}";
		var apiResult = await HttpService.Post<ApiResult<string>>(url, new());
		if (apiResult.Success)
		{
			LoadList();
			await ModalService.InfoAsync(new ConfirmOptions() { Title = "操作提示", Content = "删除数据成功" });
		}
		else
		{
			await ModalService.ErrorAsync(new ConfirmOptions() { Title = "操作提示", Content = $"数据删除失败.{apiResult.Message}" });
		}
	}



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




	void OnCreateClick()
	{
		Navigation.NavigateTo($"/product/create");
	}

	void OnEditClick(long id)
	{
		Navigation.NavigateTo($"/product/edit/{id}");
	}

	async Task OnClickAddStock(Product product)
	{
		drawerVisible = true;
		stockModel = product.Adapt<ProductAddStockModel>();
		stockModel.ProductId = product.Id;

		var url = $"/api/product/attributes/{product.Id}";
		var apiResult = await HttpService.Post<ApiResult<List<ProductStockAttributeModel>>>(url, new());
		if (apiResult.Success)
		{
			stockModel.ProductStockAttributes = apiResult.Data ?? new();
		}

		WarehouseSearch warehouseSearch = new()
			{
				CorporationId = product.CorporationId
			};
		url = $"/api/warehouse/select";
		var selectResult = await HttpService.Post<ApiResult<List<SelectItem>>>(url, warehouseSearch);
		if (selectResult.Success)
		{
			warehouseSelectItems = selectResult.Data ?? new();
		}
	}

	async void OnWarehouseInput(ChangeEventArgs e)
	{
		WarehouseSearch warehouseSearch = new()
			{
				CorporationId = stockModel.CorporationId,
				Name = e.Value?.ToString()
			};
		var url = $"/api/warehouse/select";
		var selectResult = await HttpService.Post<ApiResult<List<SelectItem>>>(url, warehouseSearch);
		if (selectResult.Success)
		{
			warehouseSelectItems = selectResult.Data ?? new();
		}
	}

	Func<object, object, bool> CompareWith = (a, b) =>
	{
		if (a is SelectItem o1 && b is SelectItem o2)
		{
			return o1.Name == o2.Name;
		}
		else
		{
			return false;
		}
	};

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

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

			Console.WriteLine(stockModel.ToJson());

			var url = $"api/product/stock/add";
			result = await HttpService.Post<ApiResult<string>>(url, stockModel);


			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 GetAttributeValue(ProductAttributeValueModel value)
	{

		if (value.Weight > 0)
		{
			return $"{value.Name}（{value.Weight.RemoveTrailingZeros()}{GetWeightUnit(value.WeightUnit)}）";
		}
		else
		{
			return value.Name;
		}
	}

	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";
		}
	}
} 