@page "/product/create"
@page "/product/edit/{id:long?}"

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

<PageTitle>编辑产品</PageTitle>
<Spin Spinning="loading">
    <Title Level="4">编辑产品信息</Title>
    <Card>
        <Form @ref="editForm" Model="model" LabelColSpan="3" WrapperColSpan="20" Class="search-form" OnFinish="OnFormFinish">
            <FluentValidationValidator />
            <FormItem>
                <Title Level="4">商品类目</Title>
            </FormItem>
            <FormItem Label="产品名称">
                <Text Type="TextElementType.Secondary">标题内容需包含商品名称，建议添加材质、功能、特征或商品描述</Text>
                <Input @bind-Value="model.Title" Placeholder="产品名称" AllowClear />
            </FormItem>
            <FormItem Label="导购标题">
                <Input @bind-Value="model.Feature" Placeholder="导购标题" AllowClear />
            </FormItem>
            @if (editCategory)
            {
                <FormItem Label="选择商品类目">
                    <Flex>
                        <Select @bind-Value="@level1CategoryId" TItemValue="long" TItem="long" Placeholder="请选择商品分类" OnSelectedItemChanged="Level1CategoryValueChanged">
                            <SelectOptions>
                                <SelectOption Value="0L" Label="无" />
                                @foreach (var item in Level1Categories)
                                {
                                    <SelectOption Value="@item.Id" Label="@item.Name" />
                                }
                            </SelectOptions>
                        </Select>
                        @if (showLevel2Category)
                        {
                            <Select @bind-Value="@level2CategoryId" TItemValue="long" TItem="long" Placeholder="请选择商品分类" OnSelectedItemChanged="Level2CategoryValueChanged" Class="ps-3">
                                <SelectOptions>
                                    @foreach (var item in Level2Categories)
                                    {
                                        <SelectOption Value="@item.Id" Label="@item.Name" />
                                    }

                                </SelectOptions>
                            </Select>
                        }
                        @if (showLevel3Category)
                        {
                            <Select @bind-Value="@level3CategoryId" TItemValue="long" TItem="long" Placeholder="请选择商品分类" OnSelectedItemChanged="Level3CategoryValueChanged" Class="ps-3">
                                <SelectOptions>
                                    @foreach (var item in Level3Categories)
                                    {
                                        <SelectOption Value="@item.Id" Label="@item.Name" />
                                    }

                                </SelectOptions>
                            </Select>
                        }
                        @if (showLevel4Category)
                        {
                            <Select @bind-Value="@level4CategoryId" TItemValue="long" TItem="long" Placeholder="请选择商品分类" OnSelectedItemChanged="Level4CategoryValueChanged" Class="ps-3">
                                <SelectOptions>
                                    @foreach (var item in Level4Categories)
                                    {
                                        <SelectOption Value="@item.Id" Label="@item.Name" />
                                    }

                                </SelectOptions>
                            </Select>
                        }
                    </Flex>
                </FormItem>
                <FormItem WrapperColSpan="4" WrapperColOffset="3">
                    <Button Type="ButtonType.Primary" Class="mt-3" OnClick="OnClickNext">下一步</Button>
                </FormItem>
            }
            else
            {
                <FormItem Label="商品类目">
                    <Text>@CategoryPath</Text><Button Type="ButtonType.Text" OnClick="OnClickEditCategory">修改</Button>
                </FormItem>
                <FormItem Label="主图">

                </FormItem>
                <FormItem Label="规格属性">

                </FormItem>
                <FormItem Label="简介">

                </FormItem>
                <FormItem Label="详情">

                </FormItem>
                @if (model.ProductSaleAttributes.Count > 0)
                {
                    <FormItem Label="商品规格">
                        @foreach (var item in model.ProductSaleAttributes)
                        {
                            if (item.AttributeId > 0)
                            {
                                <GridRow Class="mb-3">
                                    <GridCol Span="24">
                                        <GridRow Justify="RowJustify.SpaceBetween" Align="RowAlign.Middle">
                                            <GridCol>
                                                <Text>@item.Name</Text><Text>@item.DisplayOrder</Text>
                                            </GridCol>
                                            <GridCol Span="8" Style="text-align:right">
                                                <Button Type="ButtonType.Text" OnClick="()=>OnClickAttributeDisplayMoveDown(item)" Disabled="DisableMoveDownState(item)">下移</Button>
                                                <Button Type="ButtonType.Text" OnClick="()=>OnClickAttributeDisplayMoveUp(item)" Disabled="DisableMoveUpState(item)">上移</Button>
                                                @if (!item.IsRequired)
                                                {
                                                    <Button Type="ButtonType.Text" Icon="@IconType.Fill.Delete" OnClick="()=>OnClickDeleteSaleAttribute(item)"></Button>
                                                }
                                            </GridCol>
                                        </GridRow>
                                        <GridRow Gutter="(5,10)">
                                            @foreach (var value in item.ProductAttributeValues)
                                            {
                                                @if (item.ControlType == 0)
                                                {
                                                    @if (value.IsEdit)
                                                    {
                                                        <GridCol Span="12">
                                                            <Input @bind-Value="@value.Name" Placeholder="请输入规格" Style="width:160px;"></Input>
                                                            @if (CurrentProductAttribute.WeightIsRequired)
                                                            {
                                                                <AntDesign.Input Type="InputType.Number" @bind-Value="@value.Weight" Placeholder="重量" WrapperStyle="width:80px">
                                                                    <Suffix>@GetWeightUnit(CurrentProductAttribute.WeightUnit)</Suffix>
                                                                </AntDesign.Input>
                                                            }
                                                            <Button Type="@ButtonType.Link" OnClick="() => OnClickEditAttributeValueForSave(item,value)">确认</Button>
                                                            <Button Type="@ButtonType.Link" OnClick="() => OnClickEditAttributeValueForCancel(item,value)">取消</Button>
                                                        </GridCol>
                                                    }
                                                    else
                                                    {
                                                        <GridCol Span="8">
                                                            <Input @bind-Value="@value.Name" Placeholder="请输入规格" Style="width:160px;" Disabled></Input>
                                                            @if (item.WeightIsRequired)
                                                            {
                                                                <AntDesign.Input Type="InputType.Number" @bind-Value="@value.Weight" Placeholder="重量" WrapperStyle="width:80px" Disabled>
                                                                    <Suffix>克</Suffix>
                                                                </AntDesign.Input>
                                                            }
                                                            @value.DisplayOrder
                                                            <Popconfirm Title="修改规格属性值会影响商品SKU组合，确定要修改吗？"
                                                            OnConfirm="() => OnClickEditAttributeValue(item, value)"
                                                            OkText="Yes"
                                                            CancelText="No">
                                                                <Button Type="ButtonType.Text" Icon="@IconType.Fill.Edit"></Button>
                                                            </Popconfirm>
                                                            <Popconfirm Title="删除规格属性值会影响商品SKU组合，确定要删除吗？"
                                                            OnConfirm="() => HandleRemoveAttributeValue(item.AttributeId, value)"
                                                            OkText="Yes"
                                                            CancelText="No">
                                                                <Button Type="ButtonType.Text" Icon="@IconType.Fill.Delete"></Button>
                                                            </Popconfirm>
                                                        </GridCol>
                                                    }
                                                }
                                                else
                                                {

                                                }
                                            }
                                            @if (item.AddAttribute)
                                            {
                                                <GridCol Span="12">
                                                    <Input @bind-Value="@editAttributeValue.Name" Placeholder="请输入规格" Style="width:160px;"></Input>
                                                    @if (CurrentProductAttribute.WeightIsRequired)
                                                    {
                                                        <AntDesign.Input Type="InputType.Number" @bind-Value="@editAttributeValue.Weight" Placeholder="重量" WrapperStyle="width:80px">
                                                            <Suffix>@GetWeightUnit(CurrentProductAttribute.WeightUnit)</Suffix>
                                                        </AntDesign.Input>
                                                    }
                                                    <Button Type="@ButtonType.Link" OnClick="() => HandleSaveAttributeValueAsync(item.AttributeId)">确认</Button>
                                                    <Button Type="@ButtonType.Link" OnClick="() => HandleCancelAttribute(item.AttributeId)">取消</Button>
                                                </GridCol>
                                            }
                                            else
                                            {
                                                <GridCol Span="8">
                                                    <Button OnClick="()=>OnClickAddAttributeValue(item)">新增@(item.Name)值</Button>
                                                </GridCol>
                                            }
                                        </GridRow>
                                    </GridCol>
                                </GridRow>
                            }
                            else
                            {
                                <GridRow Class="mb-3">
                                    <GridCol Span="24">
                                        <GridRow Justify="RowJustify.SpaceBetween" Align="RowAlign.Middle">
                                            <GridCol>
                                                <AutoComplete Placeholder="输选择属性值" @bind-Value="@item.SelectOption"
                                                Options="productAttributes"
                                                OnSelectionChange="(e) => ProductAttributeChanged(e, item)">
                                                    <OptionTemplate Context="option">
                                                        <AutoCompleteOption Value="@option.Value.Id" Label="@option.Value.Name">
                                                        </AutoCompleteOption>
                                                    </OptionTemplate>
                                                </AutoComplete>
                                            </GridCol>
                                            <GridCol Span="8" Style="text-align:right">
                                                <Button Type="ButtonType.Text" OnClick="()=>OnClickAttributeDisplayMoveDown(item)" Disabled="DisableMoveDownState(item)">下移</Button>
                                                <Button Type="ButtonType.Text" OnClick="()=>OnClickAttributeDisplayMoveUp(item)" Disabled="DisableMoveUpState(item)">上移</Button>
                                                <Button Type="ButtonType.Text" Icon="@IconType.Fill.Delete" OnClick="()=>OnClickDeleteSaleAttribute(item)"></Button>
                                            </GridCol>
                                        </GridRow>
                                    </GridCol>
                                </GridRow>
                            }
                        }
                    </FormItem>
                }
                @if (model.ProductSaleAttributes.Count < 3)
                {
                    <FormItem WrapperColOffset="3">
                        <Button Type="ButtonType.Default" Icon="@IconType.Outline.Plus" OnClick="OnAddAttributeClick">添加规格属性类型(@(model.ProductSaleAttributes.Count)/3)</Button>
                    </FormItem>
                }

                @if (ProductAttributeCombinationsForEdit.Count() > 0)
                {
                    <FormItem Label="规格库存">
                        <div style="overflow-x:auto">
                            <table style="min-width:956px">
                                <colgroup>
                                    @foreach (var item in model.ProductSaleAttributes)
                                    {
                                        <col style="width:92px;min-width:92px;" />
                                    }
                                    <col style="width:50px;min-width:50px;" />
                                    <col style="width:92px;min-width:92px;" />
                                    <col style="width:92px;min-width:92px;" />
                                    <col style="width:92px;min-width:92px;" />
                                    <col style="width:92px;min-width:92px;" />
                                </colgroup>
                                <thead>
                                    <tr>
                                        @foreach (var item in model.ProductSaleAttributes)
                                        {
                                            if (item.ProductAttributeValues.Any())
                                            {
                                                <td>
                                                    @item.Name
                                                </td>
                                            }
                                        }
                                        <td>上架</td>

                                        <td>市场价</td>
                                        <td>销售价</td>
                                        <td>库存</td>
                                        <td>规格编码</td>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach (var item in ProductAttributeCombinationsForEdit)
                                    {
                                        <tr>
                                            @foreach (var sku in item.SkuAttributes)
                                            {
                                                <td>
                                                    @sku.ValueName
                                                    @if (sku.Weight > 0)
                                                    {
                                                        <AntDesign.Text>（@($"{sku.Weight}{@GetWeightUnit(sku.WeightUnit)}")）</AntDesign.Text>
                                                    }
                                                </td>

                                            }

                                            <td>
                                                <AntDesign.Checkbox @bind-Value="item.Enabled"></AntDesign.Checkbox>
                                            </td>
                                            <td>
                                                <AntDesign.InputNumber Value="item.MarketPrice" ValueChanged="(decimal val)=>UpdateMarketPrice(item,val)" Formatter="PriceFormat"></AntDesign.InputNumber>
                                            </td>
                                            <td>
                                                <AntDesign.InputNumber Value="item.Price" ValueChanged="(decimal val)=>UpdatePrice(item,val)" Formatter="PriceFormat"></AntDesign.InputNumber>
                                            </td>
                                            <td>
                                                <AntDesign.InputNumber Value="item.StockQuantity" ValueChanged="(int val)=>UpdateStockQuantity(item,val)"></AntDesign.InputNumber>
                                            </td>
                                            <td>
                                                <AntDesign.Input @bind-Value="item.SkuNumber"></AntDesign.Input>
                                            </td>
                                        </tr>
                                    }
                                </tbody>
                            </table>
                        </div>
                    </FormItem>
                }
                <FormItem Label="售价">
                    <Input @bind-Value="model.Price" Placeholder="销售价格" AllowClear />
                </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="3">
                    <Button Type="ButtonType.Primary" Icon="@IconType.Fill.Save" HtmlType="submit">保存</Button>
                </FormItem>
            }

        </Form>
    </Card>
</Spin>

@code {
    [Parameter]
    public long Id { get; set; }

    /// <summary>
    /// 产品表单model
    /// </summary>
    [SupplyParameterFromForm]
    ProductModel model { get; set; } = new();
    Form<ProductModel> editForm = null!;

    /// <summary>
    /// 分类下可用的产品属性集
    /// </summary>
    List<ProductAttribute> productAttributes = new();
    /// <summary>
    /// 当前编辑中的产品属性
    /// </summary>
    ProductAttribute CurrentProductAttribute = new();

    bool editCategory;
    bool loading = false;

    /// <summary>
    /// 当前编辑中的属性值对象
    /// </summary>
    ProductAttributeValueModel editAttributeValue = new();

    /// <summary>
    /// 分类信息
    /// </summary>
    List<CategoryItem> Categories = new();
    CategoryItem? Category = new();
    List<CategoryItem> Level1Categories = new();
    long level1CategoryId;
    List<CategoryItem> Level2Categories = new();
    long level2CategoryId;
    bool showLevel2Category;
    List<CategoryItem> Level3Categories = new();
    long level3CategoryId;
    bool showLevel3Category;
    List<CategoryItem> Level4Categories = new();
    long level4CategoryId;
    bool showLevel4Category;


    string CategoryPath = string.Empty;

    ProductSaleAttributeModel editAttribute = new();
    List<ProductAttributeOption> attributeOptions = new();

    List<SpecificationAttribute> SpecificationAttributes = new(); //分类规则属性

    /// <summary>
    /// 编辑的属性组合SKU信息
    /// </summary>
    List<ProductAttributeCombinationModel> ProductAttributeCombinationsForEdit = new();


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

    protected override async Task OnParametersSetAsync()
    {
        loading = true;
        await LoadCategories();
        if (Id > 0)
        {
            await LoadData();
            await SearchAttribute(string.Empty);
        }
        else
        {
            editCategory = true;
            CategoryPath = string.Empty;
        }
        if (Categories.Any())
        {
            BindCategory();
        }
        loading = false;
        base.OnParametersSet();
    }



    async Task LoadData()
    {
        var url = $"/api/product/detail/{Id}";
        var apiResult = await HttpService.Get<ApiResult<ProductModel>>(url);
        if (apiResult.Success)
        {
            if (apiResult.Data == null)
            {
                Navigation.NavigateTo($"/product/list");
            }
            else
            {
                model = apiResult.Data.Adapt<ProductModel>();
                model.IsEdit = true;
                RebuildSkuCombinations();
            }
        }
        else
        {
            Navigation.NavigateTo($"/product/list");
        }

        StateHasChanged();
    }


    async void OnFormFinish()
    {
        if (editForm.Validate())
        {

            var result = new ApiResult<string>();
            model.ProductAttributeCombinations = ProductAttributeCombinationsForEdit;

            Console.WriteLine("提交数据：");
            Console.WriteLine(model.ToJson());

            if (model.Id > 0)
            {
                var url = $"api/product/edit";
                result = await HttpService.Post<ApiResult<string>>(url, model);
            }
            else
            {
                var url = $"api/product/add";
                result = await HttpService.Post<ApiResult<string>>(url, model);
            }

            if (result.Code == (int)ResultCode.Success)
            {
                await ModalService.InfoAsync(new ConfirmOptions() { Title = "操作提示", Content = "数据提交成功" });
                Navigation.NavigateTo($"/product/list");
            }
            else
            {
                await ModalService.ErrorAsync(new ConfirmOptions() { Title = "操作提示", Content = result.Message });
            }
        }
    }

    void OnClickEditCategory()
    {
        ModalService.Confirm(new ConfirmOptions()
            {

                Title = "操作提示",
                Content = "修改类目可能会导致部分内容丢失，确认修改？",
                OkText = "修改类目",
                OnOk = (e) => { editCategory = true; CategoryPath = string.Empty; StateHasChanged(); return Task.CompletedTask; },
                CancelText = "取消"
            });
    }

    void OnAddAttributeClick()
    {
        int count = model.ProductSaleAttributes.Count();
        model.ProductSaleAttributes.Add(new ProductSaleAttributeModel() { DisplayOrder = count + 1 });
    }

    async Task SearchAttribute(string value)
    {
        ProductAttributeSearch attributeSearch = new()
            {
                Name = value,
                CategoryId = model.CategoryId
            };

        var url = $"/api/productattribute/search";
        var apiResult = await HttpService.GetPagingList<ProductAttribute>(url, attributeSearch, 1, 50);
        if (apiResult.Success)
        {
            if (apiResult.Data != null)
            {
                productAttributes = apiResult.Data.Items;

                if (Id == 0)
                {

                    var requiredAttributes = productAttributes.Where(p => p.IsRequired).ToList();
                    foreach (var item in requiredAttributes)
                    {

                        var attribute = new ProductSaleAttributeModel()
                            {
                                AttributeId = item.Id,
                                Name = item.Name,
                                ControlType = item.ControlType,
                                WeightIsRequired = item.WeightIsRequired,
                                IsRequired = item.IsRequired
                            };

                        model.ProductSaleAttributes.Add(attribute);
                    }
                }
                return;
            }
        }
        productAttributes = new List<ProductAttribute>();
    }

    /// <summary>
    /// 在Select中选中了要添加的属性对象
    /// </summary>
    /// <param name="item"></param>
    /// <param name="saleAttributeModel"></param>
    void ProductAttributeChanged(AutoCompleteOption item, ProductSaleAttributeModel saleAttributeModel)
    {
        Console.WriteLine($"选中了{item.Value}");
        var id = (long)item.Value;
        var attribute = productAttributes.FirstOrDefault(x => x.Id == id);
        if (attribute != null)
        {
            if (model.ProductSaleAttributes.Any(x => x.AttributeId == attribute.Id))
            {
                ModalService.Info(new ConfirmOptions() { Title = "提示", Content = "该属性已经添加过了" });
                return;
            }

            saleAttributeModel.AttributeId = attribute.Id;
            saleAttributeModel.Name = attribute.Name;
            saleAttributeModel.ControlType = attribute.ControlType;
            saleAttributeModel.WeightIsRequired = attribute.WeightIsRequired;
            saleAttributeModel.IsRequired = attribute.IsRequired;
        }
        StateHasChanged();
    }

    /// <summary>
    /// 点击添加属性值按钮
    /// </summary>
    /// <param name="attribute"></param>
    void OnClickAddAttributeValue(ProductSaleAttributeModel attribute)
    {
        foreach (var item in model.ProductSaleAttributes)
        {
            Console.WriteLine(item.ToJson());
            Console.WriteLine(attribute.ToJson());
            if (item.AttributeId == attribute.AttributeId)
            {
                attribute.AddAttribute = true;
                editAttribute = attribute;
                CurrentProductAttribute = productAttributes.FirstOrDefault(x => x.Id == attribute.AttributeId);
            }
            else
            {
                item.AddAttribute = false;
            }
        }
        StateHasChanged();
    }

    void OnClickEditAttributeValue(ProductSaleAttributeModel attribute, ProductAttributeValueModel value)
    {
        value.IsEdit = true;
        attribute.AddAttribute = false;
        CurrentProductAttribute = productAttributes.FirstOrDefault(x => x.Id == attribute.AttributeId);
        editAttributeValue = value;
        Console.WriteLine($"编辑属性值：{value.ToJson()}");
        Console.WriteLine($"编辑属性值：{editAttributeValue.ToJson()}");
    }

    /// <summary>
    /// 保存新的属性值
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    void OnClickEditAttributeValueForSave(ProductSaleAttributeModel attribute, ProductAttributeValueModel value)
    {

        if (CurrentProductAttribute.ControlType == 0)
        {
            if (string.IsNullOrEmpty(value.Name))
            {
                MessageService.Error("请输入规格值");
                return;
            }
        }
        if (CurrentProductAttribute.WeightIsRequired)
        {
            if (value.Weight <= 0)
            {
                MessageService.Error("请输入重量");
                return;
            }
        }
        var attributeValue = attribute.ProductAttributeValues.Where(p => p.Name == value.Name && p.Weight == value.Weight && p.DisplayOrder != value.DisplayOrder).SingleOrDefault();
        if (attributeValue != null)
        {
            MessageService.Error("已经设置了一个相同的属性值");
            return;
        }
        Console.WriteLine($"编辑属性值之后：{value.ToJson()}");
        value.IsEdit = false;
        RebuildSkuCombinations();
    }

    void OnClickEditAttributeValueForCancel(ProductSaleAttributeModel attribute, ProductAttributeValueModel value)
    {
        value.IsEdit = false;
        attribute.AddAttribute = false;
        CurrentProductAttribute = new();
    }

    /// <summary>
    /// 保存新的属性值
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    void HandleSaveAttributeValueAsync(long id)
    {
        var data = model.ProductSaleAttributes.SingleOrDefault(p => p.AttributeId == id);
        if (data != null)
        {
            if (CurrentProductAttribute.ControlType == 0)
            {
                if (string.IsNullOrEmpty(editAttributeValue.Name))
                {
                    MessageService.Error("请输入规格值");
                    return;
                }
            }
            if (CurrentProductAttribute.WeightIsRequired)
            {
                if (editAttributeValue.Weight <= 0)
                {
                    MessageService.Error("请输入重量");
                    return;
                }
            }
            var attributeValue = data.ProductAttributeValues.Where(p => p.Name == editAttributeValue.Name && p.Weight == editAttributeValue.Weight).SingleOrDefault();
            if (attributeValue != null)
            {
                MessageService.Error("已经设置了一个相同的属性值");
                return;
            }
            data.ProductAttributeValues.Add(new ProductAttributeValueModel() { Id = editAttributeValue.Id, Name = editAttributeValue.Name, Weight = editAttributeValue.Weight, WeightUnit = editAttributeValue.WeightUnit, DisplayOrder = data.ProductAttributeValues.Count });
            editAttributeValue = new();
            RebuildSkuCombinations();
        }
    }

    void HandleCancelAttribute(long id)
    {
        var data = model.ProductSaleAttributes.SingleOrDefault(p => p.AttributeId == id);
        if (data != null)
        {
            data.AddAttribute = false;
        }
    }

    void HandleRemoveAttributeValue(long attributeId, ProductAttributeValueModel value)
    {
        var data = model.ProductSaleAttributes.SingleOrDefault(p => p.AttributeId == attributeId);
        data.ProductAttributeValues.Remove(value);
        if (data.ProductAttributeValues.Count == 0)
        {

            var attribute = model.PhotoSalesAttribute.SingleOrDefault(p => p.Id == data.AttributeId);
            if (attribute != null)
            {
                model.PhotoSalesAttribute.Remove(attribute);
            }
        }
        RebuildSkuCombinations();
        UpdateSkuPrices();
    }

    bool DisableMoveUpState(ProductSaleAttributeModel saleAttributeModel)
    {
        var index = saleAttributeModel.DisplayOrder;
        if (index > 1)
        {
            if (model.ProductSaleAttributes.Count > 1)
            {
                return false;
            }
        }
        return true;
    }

    bool DisableMoveDownState(ProductSaleAttributeModel saleAttributeModel)
    {
        var index = saleAttributeModel.DisplayOrder;
        if (index < 3 && index != model.ProductSaleAttributes.Count)
        {
            if (model.ProductSaleAttributes.Count > 1)
            {
                return false;
            }
        }
        return true;
    }

    void OnClickAttributeDisplayMoveUp(ProductSaleAttributeModel saleAttributeModel)
    {
        var index = saleAttributeModel.DisplayOrder;
        if (index != 1)
        {
            var prev = model.ProductSaleAttributes.SingleOrDefault(p => p.DisplayOrder == index - 1);
            if (prev == null)
            {
                return;
            }
            prev.DisplayOrder = prev.DisplayOrder + 1;
            saleAttributeModel.DisplayOrder = saleAttributeModel.DisplayOrder - 1;
            model.ProductSaleAttributes = model.ProductSaleAttributes.OrderBy(p => p.DisplayOrder).ToList();
            StateHasChanged();
        }
        RebuildSkuCombinations();
    }

    void OnClickAttributeDisplayMoveDown(ProductSaleAttributeModel saleAttributeModel)
    {
        var index = saleAttributeModel.DisplayOrder;
        if (index < 3 && index != model.ProductSaleAttributes.Count)
        {
            var next = model.ProductSaleAttributes.SingleOrDefault(p => p.DisplayOrder == index + 1);
            if (next == null)
            {
                return;
            }
            next.DisplayOrder--;
            saleAttributeModel.DisplayOrder++;
            model.ProductSaleAttributes = model.ProductSaleAttributes.OrderBy(p => p.DisplayOrder).ToList();
            StateHasChanged();
        }
        RebuildSkuCombinations();
    }

    void OnClickDeleteSaleAttribute(ProductSaleAttributeModel saleAttributeModel)
    {
        model.ProductSaleAttributes.Remove(saleAttributeModel);
        var index = 1;
        foreach (var item in model.ProductSaleAttributes)
        {
            item.DisplayOrder = index;
            index++;
        }
        RebuildSkuCombinations();
    }

    void UploadFiles(IReadOnlyList<IBrowserFile> files)
    {

    }

    #region 分类相关

    void BindCategory()
    {
        Category = Categories.SingleOrDefault(p => p.Id == model.CategoryId);
        var path = Category?.Path.Split(",") ?? [];
        if (path.Length > 0)
        {
            for (var i = 0; i < path.Length; i++)
            {
                if (i == 0)
                {
                    level1CategoryId = path[i].ToLong();
                }
                else if (i == 1)
                {
                    level2CategoryId = path[i].ToLong();
                }
                else if (i == 2)
                {
                    level3CategoryId = path[i].ToLong();
                }
                else
                {
                    level4CategoryId = path[i].ToLong();
                }
            }
        }
        Level1Categories = Categories.Where(p => p.ParentId == 0).ToList();

        if (level1CategoryId > 0)
        {
            Level2Categories = Categories.Where(p => p.ParentId == level1CategoryId).ToList();
        }
        if (level2CategoryId > 0)
        {
            Level3Categories = Categories.Where(p => p.ParentId == level2CategoryId).ToList();
        }
        if (level3CategoryId > 0)
        {
            Level4Categories = Categories.Where(p => p.ParentId == level3CategoryId).ToList();
        }

        if (Category != null)
        {
            BuildCategoryPath(Category);
        }
    }

    async Task LoadCategories()
    {
        var url = $"/api/category/items";
        var apiResult = await HttpService.Get<ApiResult<List<CategoryItem>>>(url);
        if (apiResult.Success)
        {
            Categories = apiResult.Data ?? new();
        }
    }

    private void Level1CategoryValueChanged(long id)
    {
        level1CategoryId = id;
        if (level1CategoryId > 0)
        {
            level2CategoryId = 0;
            Level2Categories = Categories.Where(p => p.ParentId == id).ToList();
        }
        else
        {
            Level2Categories = new();
        }
        if (Level2Categories.Any())
        {
            model.CategoryId = 0;
            showLevel2Category = true;
            showLevel3Category = false;
            showLevel4Category = false;
            level3CategoryId = 0;
            level4CategoryId = 0;
            Level3Categories = new();
            Level4Categories = new();
        }
        else
        {
            model.CategoryId = level1CategoryId;
            showLevel2Category = false;
            showLevel3Category = false;
            showLevel4Category = false;
            level2CategoryId = 0;
            level3CategoryId = 0;
            level4CategoryId = 0;
            Level3Categories = new();
            Level4Categories = new();
        }
    }

    private void Level2CategoryValueChanged(long id)
    {
        level2CategoryId = id;
        Level3Categories = Categories.Where(p => p.ParentId == id).ToList();
        if (Level3Categories.Any())
        {
            model.CategoryId = 0;
            showLevel3Category = true;
            showLevel4Category = false;
            level4CategoryId = 0;
            Level4Categories = new();
        }
        else
        {
            model.CategoryId = level2CategoryId;
            showLevel3Category = false;
            showLevel4Category = false;
            level3CategoryId = 0;
            level4CategoryId = 0;
            Level4Categories = new();
        }

    }

    private void Level3CategoryValueChanged(long id)
    {
        level3CategoryId = id;
        Level4Categories = Categories.Where(p => p.ParentId == id).ToList();
        if (Level4Categories.Any())
        {
            model.CategoryId = 0;
            showLevel4Category = true;
            level4CategoryId = 0;
        }
        else
        {
            model.CategoryId = level3CategoryId;
            showLevel4Category = false;
            level4CategoryId = 0;
        }

    }

    private void Level4CategoryValueChanged(long id)
    {
        level4CategoryId = id;
        model.CategoryId = level4CategoryId;
    }

    async Task OnClickNext()
    {
        if (model.CategoryId == 0)
        {
            ModalService.Info(new ConfirmOptions() { Title = "操作提示", Content = "请确认产品归属分类" });
            return;
        }
        var category = Categories.Where(p => p.Id == model.CategoryId).SingleOrDefault();
        if (category == null)
        {
            ModalService.Info(new ConfirmOptions() { Title = "操作提示", Content = "请设置正确的产品归属分类" });
            return;
        }
        BuildCategoryPath(category);

        editCategory = false;
        await SearchAttribute(string.Empty);
    }
    #endregion

    void BuildCategoryPath(Category category)
    {
        Console.WriteLine(category.Name);
        Console.WriteLine(category.Path);
        var ids = category.Path.Split(",");
        foreach (var id in ids)
        {
            var item = Categories.Where(p => p.Id == id.ToLong()).SingleOrDefault();
            if (item != null)
            {
                if (string.IsNullOrEmpty(CategoryPath))
                {
                    CategoryPath = item.Name;
                }
                else
                {
                    CategoryPath = $"{CategoryPath} > {item.Name}";
                }
            }
        }
    }

    int runNumber = 0;

    /// <summary>
    /// 根据卡迪尔乘积构建UI表单
    /// </summary>
    void RebuildSkuCombinations()
    {
        List<List<ProductSkuModel>> result = new List<List<ProductSkuModel>>();
        List<ProductAttributeCombinationModel> TempSkuCombinations = new List<ProductAttributeCombinationModel>();
        if (model.ProductSaleAttributes.Count > 0)
        {
            var list = model.ProductSaleAttributes.Where(p => p.ProductAttributeValues.Count > 0).ToList();
            Descartes(list, 0, result, new List<ProductSkuModel>());
            //int count = result.Count();


            foreach (var item in result)
            {

                bool state = false;
                foreach (var comb in model.ProductAttributeCombinations)
                {

                    if (comb.SkuAttributes.SequenceEqual(item))
                    {
                        //新的SKU组合信息，原始SKU组合信息不能改动
                        var combinationModel = new ProductAttributeCombinationModel()
                            {
                                Enabled = comb.Enabled,
                                Id = comb.Id,
                                MarketPrice = comb.MarketPrice,
                                Price = comb.Price,
                                ProductId = comb.ProductId,
                                SalesQuantity = comb.SalesQuantity,
                                SkuNumber = comb.SkuNumber,
                                SkuAttributes = item,
                                StockQuantity = comb.StockQuantity,
                                Weight = comb.Weight,
                                ManufacturerId = comb.ManufacturerId,
                                ProcessCharge = comb.ProcessCharge,
                                ProcessCost = comb.ProcessCost,
                                Surcharge = comb.Surcharge,
                                SurchargeCost = comb.SurchargeCost
                            };

                        TempSkuCombinations.Add(combinationModel);
                        state = true;
                        break;
                    }
                }

                if (!state)
                {
                    var combinationModel = new ProductAttributeCombinationModel()
                        {
                            Enabled = false,
                            Id = 0,
                            MarketPrice = 0,
                            Price = 0,
                            ProductId = model.Id,
                            SalesQuantity = 0,
                            SkuNumber = "",
                            SkuAttributes = item,
                            StockQuantity = 0,
                            Weight = 0,
                        };
                    foreach (var sku in item)
                    {
                        if (sku.Weight > 0)
                        {
                            combinationModel.Weight = sku.Weight;
                        }
                    }
                    TempSkuCombinations.Add(combinationModel);
                }
            }
        }
        ProductAttributeCombinationsForEdit = TempSkuCombinations;

        Console.WriteLine($"执行步骤：{runNumber},RebuildSkuCombinations,数据：{model.ProductSaleAttributes.ToJson()}");
        runNumber++;
    }

    /// <summary>
    /// 笛卡尔乘积处理
    /// </summary>
    /// <param name="list"></param>
    /// <param name="count"></param>
    /// <param name="result"></param>
    /// <param name="data"></param>
    /// <returns></returns>
    List<ProductSkuModel> Descartes(List<ProductSaleAttributeModel> list, int count, List<List<ProductSkuModel>> result, List<ProductSkuModel> data)
    {
        List<ProductSkuModel> tempData = data.Clone();
        if (list.Count() > 0)
        {
            ProductSaleAttributeModel saleAttribute = list[count];
            List<ProductAttributeValueModel> attributeValues = saleAttribute.ProductAttributeValues;
            foreach (var item in attributeValues)
            {
                if (count + 1 < list.Count())
                {
                    var copy2 = data.Clone();
                    copy2.Add(new ProductSkuModel { AttributeId = saleAttribute.AttributeId, AttributeName = saleAttribute.Name, ValueId = item.Id, ValueName = item.Name, Weight = item.Weight.RemoveTrailingZeros().ToDecimal() });

                    var productSKu = Descartes(list, count + 1, result, copy2);
                    tempData.AddRange(productSKu);
                }
                else
                {
                    var copy = data.Clone();
                    var sku = new ProductSkuModel { AttributeId = saleAttribute.AttributeId, AttributeName = saleAttribute.Name, ValueId = item.Id, ValueName = item.Name, Weight = item.Weight.RemoveTrailingZeros().ToDecimal() };
                    copy.Add(sku);

                    result.Add(copy);
                }
            }
        }
        return tempData;
    }

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

    /// <summary>
    /// 根据SKU规格变化更新产品信息中的价格
    /// </summary>
    void UpdateSkuPrices()
    {
        if (ProductAttributeCombinationsForEdit.Any())
        {
            model.MarketPrice = ProductAttributeCombinationsForEdit.Max(p => p.MarketPrice);
            model.Price = ProductAttributeCombinationsForEdit.Max(p => p.Price);
            model.StockQuantity = ProductAttributeCombinationsForEdit.Sum(p => p.StockQuantity);
        }
        else
        {
            model.MarketPrice = 0;
            model.Price = 0;
            model.StockQuantity = 0;
        }
    }

    /// <summary>
    /// SKU市场价变化后更新商品市场价
    /// </summary>
    void UpdateMarketPrice(ProductAttributeCombinationModel data, decimal price)
    {
        var marketPrice = price;
        foreach (var item in ProductAttributeCombinationsForEdit)
        {
            if (item.SkuAttributes.SequenceEqual(data.SkuAttributes))
            {
                item.MarketPrice = price;
            }
            if (item.MarketPrice > marketPrice)
            {
                marketPrice = item.Price;
            }
        }
        model.MarketPrice = marketPrice;

    }

    /// <summary>
    /// SKU销售价格变化后更新商品销售价格
    /// </summary>
    void UpdatePrice(ProductAttributeCombinationModel data, decimal price)
    {
        var salePrice = price;

        foreach (var item in ProductAttributeCombinationsForEdit)
        {
            if (item.SkuAttributes.SequenceEqual(data.SkuAttributes))
            {
                item.Price = price;
            }
            if (item.Price > salePrice)
            {
                salePrice = item.Price;
            }
        }
        model.Price = salePrice;
    }

    /// <summary>
    /// SKU库存变化后更新库存
    /// </summary>
    void UpdateStockQuantity(ProductAttributeCombinationModel data, int num)
    {
        int quantity = 0;
        foreach (var item in ProductAttributeCombinationsForEdit)
        {
            if (item.SkuAttributes.SequenceEqual(data.SkuAttributes))
            {
                item.StockQuantity = num;
            }
            quantity = quantity + item.StockQuantity;
        }
        model.StockQuantity = quantity;
        StateHasChanged();
    }

    string GetWeightAndUnit(ProductSkuModel skuModel)
    {

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

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