@page "/attribute/list"

@rendermode InteractiveAuto
@inject ILogger<ProductAttributeList> Logger
@inject HttpService HttpService
@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.Name" 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.Name" Title="名称"></PropertyColumn>
			<PropertyColumn Property="c=>c.ControlType" Title="控件">
				@if (context.ControlType == 1)
				{
					<Tag Color="TagColor.Green">选项</Tag>
				}
				else
				{
					<Tag>文本框</Tag>
				}
			</PropertyColumn>
			<PropertyColumn Property="c=>c.CategoryName" Title="分类"></PropertyColumn>
			<PropertyColumn Property="c=>c.WeightIsRequired" Title="重量" Width="100px">
				@if (context.WeightIsRequired)
				{
					<Tag>必填</Tag>
				}
			</PropertyColumn>
			<PropertyColumn Property="c=>c.IsRequired" Title="默认" Width="100px">
				@if (context.IsRequired)
				{
					<Tag>必选</Tag>
				}
			</PropertyColumn>
			<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)=>OnViewPredefinedListClick(context.Id)">预设值</a>
					</SpaceItem>
					<SpaceItem>
						<a @onclick="(e)=>OnEditClick(context)">编辑</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="4" @ref="@editform" Model="@model" OnFinish="OnFormFinish">
		<FluentValidationValidator />
		<FormItem Label="名称">
			<Input @bind-Value="model.Name" For="(()=>model.Name)" />

		</FormItem>
		<FormItem Label="控件">
			<RadioGroup @bind-Value="@model.ControlType" ButtonStyle="RadioButtonStyle.Solid">
				<Radio RadioButton Value="0">默认（文本）</Radio>
				<Radio RadioButton Value="1">选项</Radio>
			</RadioGroup>
		</FormItem>
		<FormItem Label="重量">
			<Checkbox @bind-Value="model.WeightIsRequired">必填</Checkbox>
		</FormItem>
		<FormItem Label="默认">
			<Checkbox @bind-Value="model.IsRequired">默认属性</Checkbox>
		</FormItem>
		<FormItem Label="状态">
			<RadioGroup @bind-Value="@model.Status" ButtonStyle="RadioButtonStyle.Solid">
				<Radio RadioButton Value="1">启用</Radio>
				<Radio RadioButton Value="2">禁用</Radio>
			</RadioGroup>
		</FormItem>
		<FormItem WrapperColOffset="4">
			<Button Type="ButtonType.Primary" HtmlType="submit" Style="width: 100%;">保存</Button>
		</FormItem>
	</Form>
</Drawer>

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

	[SupplyParameterFromQuery]
	long CategoryId { get; set; }

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

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

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

	PagingList<ProductAttributeItemModel> PagingList = new();
	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();
		model.CategoryId = CategoryId;
		base.OnParametersSet();
	}

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


	private async void LoadList()
	{

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

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

		OnSearch(Page.Value);
	}


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

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

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

	void OnPageChanged(PaginationEventArgs args)
	{

		var queryString = search.BuildQueryString();
		if (string.IsNullOrEmpty(queryString))
		{
			Navigation.NavigateTo($"/attribute/list?page={args.Page}");
		}
		else
		{
			Navigation.NavigateTo($"/attribute/list?page={Page}&{queryString}");
		}
	}


	void OnEditClick(ProductAttribute productAttribute)
	{
		this.model = productAttribute.Adapt<ProductAttributeModel>();
		drawerVisible = true;
	}

	async Task HandleDeleteConfirmAsync(MouseEventArgs e, long id)
	{
		var url = $"/api/productattribute/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}" });
		}
	}

	async Task OnFormFinish()
	{
		Console.WriteLine("run on from finish ");
		if (CategoryId > 0)
		{
			model.CategoryId = CategoryId;
		}

		if (editform.Validate())
		{
			var result = new ApiResult<string>();
			if (model.Id > 0)
			{
				var url = $"api/productattribute/edit";
				result = await HttpService.Post<ApiResult<string>>(url, model);
			}
			else
			{
				var url = $"api/productattribute/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 });
			}
		}
	}

	private void OnPageChanged(int args)
	{
		OnSearch(args);
	}


	void OnCreateClick()
	{
		drawerVisible = true;
	}

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

	void OnViewPredefinedListClick(long id)
	{
		Navigation.NavigateTo($"/attribute/Predefined/list/{id}");
	}
}  