@page "/attribute/predefined/list/{AttributeId:long}"

@inject ILogger<PredefinedAttributeList> 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.Value" 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">
			@productAttribute.Name 属性预设值列表
				<div>
					<Button Class="me-3" OnClick="OnCreateClick" Type="ButtonType.Primary">新增</Button>
				</div>
			</Flex>
		</TitleTemplate>
		<ColumnDefinitions>
			<PropertyColumn Property="c=>c.Value" Title="名称"></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)=>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='($"设置{productAttribute.Name}属性预设值")' OnClose="_=>CloseDrawer()">
    <Form LabelColSpan="4" @ref="@editform" Model="@model" OnFinish="OnFormFinish">
        <FluentValidationValidator />
        <FormItem Label="名称">
            <Input @bind-Value="model.Value" For="(()=>model.Value)" />
        </FormItem>
        <FormItem Label="排序">
            <Input @bind-Value="model.DisplayOrder" For="(()=>model.DisplayOrder)" />
        </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 {
    [Parameter]
    public long AttributeId { get; set; }

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

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

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

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

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


    bool drawerVisible;

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

    protected override void OnParametersSet()
    {

        loadQueryString();
        LoadList();
        LoadAttribute();
        base.OnParametersSet();
    }

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

    private async void LoadAttribute()
    {
        var url = $"/api/productattribute/{AttributeId}";
        var apiResult = await HttpService.Get<ApiResult<ProductAttribute>>(url);
        if (apiResult.Success)
        {
            if (apiResult.Data != null)
            {
                productAttribute = apiResult.Data;
            }
        }
    }


    private async void LoadList()
    {

        loading = true;
        var url = "/api/productattributeoption/search";
        var apiResult = await HttpService.GetPagingList<ProductAttributeOption>(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 OnSearch(int page)
    {
        var queryString = search.BuildQueryString();
        if (string.IsNullOrEmpty(queryString))
        {
            if (page > 1)
            {
                Navigation.NavigateTo($"/attribute/predefined/list/{AttributeId}?page={page}");
            }
            else
            {
                Navigation.NavigateTo($"/attribute/predefined/list/{AttributeId}");
            }
        }
        else
        {
            if (page > 1)
            {
                Navigation.NavigateTo($"/attribute/predefined/list/{AttributeId}?page={page}&{queryString}");
            }
            else
            {
                Navigation.NavigateTo($"/attribute/predefined/list/{AttributeId}?{queryString}");
            }
        }
    }

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

    


    async Task HandleDeleteConfirmAsync(MouseEventArgs e, long id)
    {

        var url = $"/api/productattributeoption/delete/{model.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()
    {
        if (editform.Validate())
        {

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


    void OnEditClick(ProductAttributeOption option)
    {
        this.model = option.Adapt<ProductAttributeOptionModel>();
        drawerVisible = true;
    }

    void OnCreateClick()
    {
        model = new();
        drawerVisible = true;
    }

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