| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577 |
-
- using System.Data.Common;
- using System.Drawing.Imaging;
- using System.Xml.Linq;
- using AntDesign;
- using AntDesign.TableModels;
- using EasyTemplate.Tool;
- using Microsoft.AspNetCore.Components;
- using Microsoft.AspNetCore.Components.Web;
- using Microsoft.JSInterop;
- using Org.BouncyCastle.Crypto;
- using SqlSugar;
- namespace EasyTemplate.Page.Pages;
- public partial class Product
- {
- protected override async Task OnInitializedAsync()
- {
- }
- protected override async Task OnAfterRenderAsync(bool firstRender)
- {
- if (firstRender)
- {
- await NavigationManager.RedirectLogin(IJSRuntime);
- tProperties = _TProperty.AsQueryable().ToTree(it => it.Children, it => it.ParentId, 0);
- }
- }
- #region 表格
- /// <summary>
- /// 查
- /// </summary>
- /// <returns></returns>
- private async Task Query()
- {
- Loading = true;
- RefAsync<int> total = 0;
- var products = await _Repository.AsQueryable()
- .Where(x => !x.IsDelete)
- .WhereIF(!string.IsNullOrWhiteSpace(Q_Name), x => x.Name.Contains(Q_Name))
- .WhereIF(!string.IsNullOrWhiteSpace(Q_Code), x => x.Code.Contains(Q_Code))
- .ToPageListAsync(Pi, Ps, total);
- products?.ForEach(item => {
- item.Skus = _Sku.AsQueryable().Where(x => x.ProductId == item.Id).ToList();
- });
- DataSource = products;
- Total = total.Value;
- Loading = false;
- }
- /// <summary>
- /// 增/改
- /// </summary>
- /// <param name="data"></param>
- /// <returns></returns>
- private bool InsertOrUpdate(TProduct data)
- {
- try
- {
- _Repository.Context.Ado.BeginTran();
- tProduct.Preview = string.Join(",", FileList.Select(x => x.Url).ToList());
- tProduct.TotalStock = tProduct.Skus.Sum(x => x.Stock);
- if (data.Id == 0)
- {
- if (_Repository.AsQueryable().Any(x => x.Name.ToLower() == data.Name.ToLower() || x.Code.ToLower() == data.Code.ToLower()))
- {
- throw new Exception("该商品已存在");
- }
- if (string.IsNullOrWhiteSpace(data.Code))
- {
- data.Code = $"TP{DateTime.Now.ToString("yyyyMMddHHmmssfff")}{new Random().Next(1000, 9999)}";
- }
- //新增商品
- var id = _Repository.AsInsertable(data).ExecuteReturnBigIdentity();
- //新增规格
- _Sku.AsDeleteable().Where(x => x.ProductId == id).ExecuteCommand();
- data.Skus.ForEach(item => { item.ProductId = id; });
- _Sku.AsInsertable(data.Skus).ExecuteCommand();
- }
- else
- {
- if (_Repository.AsQueryable().Any(x => x.Name.ToLower() == data.Name.ToLower() && x.Id != data.Id))
- {
- throw new Exception("该商品已存在");
- }
- //更新商品
- _Repository.AsUpdateable()
- .SetColumns(x => x.Name == data.Name)
- .SetColumns(x => x.Description == data.Description)
- .SetColumns(x => x.Preview == data.Preview)
- .SetColumns(x => x.Content == data.Content)
- .Where(x => x.Id == data.Id)
- .ExecuteCommand();
- //新增规格
- _Sku.AsDeleteable().Where(x => x.ProductId == data.Id).ExecuteCommand();
- data.Skus.ForEach(item => { item.ProductId = data.Id; });
- _Sku.AsInsertable(data.Skus).ExecuteCommand();
- }
- _Repository.Context.Ado.CommitTran();
- return true;
- }
- catch (Exception ex)
- {
- Log.Error($"商品增改失败:{ex}");
- _Repository.Context.Ado.RollbackTran();
- return false;
- }
- }
- /// <summary>
- /// 重置查询
- /// </summary>
- private async Task ResetQuery()
- {
- Q_Name = Q_Code = string.Empty;
- Pi = 1;
- await Query();
- }
- /// <summary>
- /// 表格使用它来初始化,不要在页面初始化时调用,否则会导致重复加载
- /// </summary>
- /// <param name="query"></param>
- /// <returns></returns>
- private async Task OnChange(QueryModel<TProduct> query)
- => await Query();
- private async Task Search()
- {
- Pi = 1;
- await Query();
- }
- private void CheckedChanged(TProduct row)
- {
- _Repository.AsUpdateable()
- .SetColumns(x => x.Available == row.Available)
- .Where(x => x.Id == row.Id)
- .ExecuteCommand();
- }
- /// <summary>
- /// 名称
- /// </summary>
- private string Q_Name { get; set; }
- /// <summary>
- /// 编码
- /// </summary>
- private string Q_Code { get; set; }
- private TProduct tProduct = new();
- /// <summary>
- ///
- /// </summary>
- private ITable _Table;
- /// <summary>
- ///
- /// </summary>
- private IEnumerable<TProduct> SelectedRows = [];
- /// <summary>
- ///
- /// </summary>
- private List<TProduct> DataSource;
- /// <summary>
- ///
- /// </summary>
- private int Pi = 1;
- /// <summary>
- ///
- /// </summary>
- private int Ps = 20;
- /// <summary>
- ///
- /// </summary>
- private int Total;
- /// <summary>
- ///
- /// </summary>
- private bool Loading = false;
- /// <summary>
- ///
- /// </summary>
- private string imgUrl = string.Empty;
- /// <summary>
- ///
- /// </summary>
- private bool previewVisible = false;
- #endregion
- #region 表单方法
- /// <summary>
- /// 初始化表单
- /// </summary>
- /// <param name="row"></param>
- private void InitFormData(TProduct row)
- {
- IsControlByUser = false;
- UsingTPropertyItems.Clear();
- TPropertyItems.Clear();
- if (row != null)
- {
- //获取规格id并去重
- var ids = row.Skus
- .SelectMany(x => x.PropertyIds.Split(',', StringSplitOptions.RemoveEmptyEntries))
- .Select(idStr => long.TryParse(idStr, out var id) ? id : (long?)null)
- .Where(id => id.HasValue)
- .Select(id => id!.Value)
- .Distinct()
- .ToList();
- var Main = tProperties.Where(x => x.Children is null ? false : x.Children.Any(y => ids.Contains(y.Id))).ToList();
- for (int index = 0; index < Main.Count; index++)
- {
- var arr = Main[index].Children.Where(x => ids.Contains(x.Id)).Select(x => x.Id).ToArray();
- var newlist = tProperties.Except(Main).ToList();
- newlist.Add(Main[index]);
- TPropertyItems.Add(new SkuSet()
- {
- Index = (index + 1),
- MainProperties = newlist.OrderBy(x=>x.Id).ToList(),
- MainSelectedValue = Main[index].Id,
- ChildProperties = Main[index].Children,
- ChildSelectedValues = arr?.OfType<long?>() ?? Enumerable.Empty<long?>()
- });
- UsingTPropertyItems.Add(Main[index]);
- }
- }
- else
- {
- TPropertyItems.Add(new SkuSet() { Index = 1, MainProperties = tProperties });
- }
- IsDisabled = TPropertyItems.Count >= tProperties.Count;
- FileList.Clear();
- if (!string.IsNullOrWhiteSpace(tProduct.Preview))
- {
- var imgs = tProduct.Preview.Split(",").ToList();
- for (int index = 0; index < imgs.Count; index++)
- {
- FileList.Add(new UploadFileItem { Id = (index + 1).ToString(), State = UploadState.Success, Url = imgs[index], FileName = Path.GetFileName(imgs[index]) });
- }
- }
- }
- /// <summary>
- /// 更新规格表
- /// </summary>
- private void GenerateSkuTable()
- {
- if (TPropertyItems?.Count > 0)
- {
- tProduct.Skus = new();
- var selectedValuesLists = TPropertyItems
- .Where(item => item.ChildSelectedValues != null && item.ChildSelectedValues.Any())
- .Select(item => item.ChildSelectedValues.ToList())
- .ToList();
- var res = GenerateCartesianProduct(selectedValuesLists)
- .Select(combination => string.Join(",", combination))
- .ToList();
- var skus = new List<TProductSku>();
- for (int index = 0; index < res.Count; index++)
- {
- var names = _TProperty.AsQueryable()
- .Where(x => SqlFunc.SplitIn(res[index], x.Id.ToString()))
- .Select(x => x.Name)
- .ToList();
- skus.Add(new TProductSku()
- {
- PropertyIds = res[index],
- PropertyName = string.Join(",", names),
- Code = $"S{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-{(index + 1)}",
- });
- }
- tProduct.Skus = skus;
- }
- IsDisabled = TPropertyItems?.Count >= tProperties.Count;
- modalRef.UpdateConfigAsync();
- }
- private static IEnumerable<IEnumerable<T>> GenerateCartesianProduct<T>(IEnumerable<IEnumerable<T>> sequences)
- {
- IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
- return sequences.Aggregate(
- emptyProduct,
- (accumulator, sequence) =>
- from acc in accumulator
- from item in sequence
- select acc.Concat(new[] { item }));
- }
- /// <summary>
- /// 新增规格选择框
- /// </summary>
- private void AddProperty()
- {
- if (TPropertyItems[TPropertyItems.Count - 1].MainSelect?.Value == null)
- {
- MessageService.Warning("还未选择规格");
- return;
- }
- if (TPropertyItems[TPropertyItems.Count - 1].ChildSelectedValues?.Count() == 0)
- {
- MessageService.Warning("还未选择规格");
- return;
- }
- var prop = tProperties.Except(UsingTPropertyItems).ToList();
- TPropertyItems.Add(new SkuSet() { Index = TPropertyItems.Count + 1, MainProperties = prop });
- if (prop.Count == 1)
- {
- IsDisabled = true;
- }
- modalRef.UpdateConfigAsync();
- }
- /// <summary>
- /// 删除规格选择框
- /// </summary>
- /// <param name="selectedValue"></param>
- /// <param name="args"></param>
- private void DeleteProperty(SkuSet? selectedValue, MouseEventArgs args)
- {
- TPropertyItems.Remove(selectedValue);
- var current = selectedValue.MainProperties.Where(x => x.Id == selectedValue.MainSelectedValue).FirstOrDefault();
- UsingTPropertyItems.Remove(current);
- UpdatePropertyItems();
- GenerateSkuTable();
- }
- /// <summary>
- /// 触发点击说明用户开始操作
- /// </summary>
- private void OnClick()
- {
- IsControlByUser = true;
- }
- /// <summary>
- /// 主规格被选
- /// </summary>
- /// <param name="value"></param>
- private void OnMainSelectedItemChanged(SkuSet? selectedValue, TProductProperty value)
- {
- if (!IsControlByUser) return;
- TProductProperty old = null;
- if (UsingTPropertyItems.Count >= selectedValue.Index && UsingTPropertyItems[selectedValue.Index - 1].Id != value.Id)
- {
- old = UsingTPropertyItems[selectedValue.Index - 1];
- UsingTPropertyItems[selectedValue.Index - 1] = value;
- }
- if (!UsingTPropertyItems.Any(x => x.Id == value.Id))
- {
- UsingTPropertyItems.Add(value);
- }
- UpdatePropertyItems(old, value);
- modalRef.UpdateConfigAsync();
- }
- private void UpdatePropertyItems(TProductProperty oldValue = null, TProductProperty newValue = null)
- {
- foreach (var TPropertyItem in TPropertyItems)
- {
- var newlist = tProperties.Except(UsingTPropertyItems).ToList() ?? new();
- var current = tProperties.Where(x => x.Id == TPropertyItem.MainSelectedValue).FirstOrDefault();
- newlist.Add(current);
- TPropertyItem.MainProperties = newlist.OrderBy(x => x.Id).ToList();
- TPropertyItem.ChildProperties = _TProperty.AsQueryable().Where(x => x.ParentId == TPropertyItem.MainSelectedValue).ToList();
- if (oldValue != null
- && newValue != null
- && oldValue.Id != TPropertyItem.MainSelectedValue
- && newValue.Id == TPropertyItem.MainSelectedValue)
- {
- TPropertyItem.ChildSelectedValues = default;
- }
- }
- }
- /// <summary>
- /// 子规格被选
- /// </summary>
- /// <param name="value"></param>
- private void OnChildSelectedItemsChanged(IEnumerable<TProductProperty> value)
- {
- if (!IsControlByUser) return;
- GenerateSkuTable();
- }
- /// <summary>
- /// 新增规格
- /// </summary>
- /// <param name="args"></param>
- private void AddNewMainProperty(MouseEventArgs args)
- {
- if (!string.IsNullOrWhiteSpace(_name))
- {
- if (!_TProperty.IsAny(x => x.Name == _name))
- {
- _TProperty.AsInsertable(new TProductProperty() { Name = _name }).ExecuteCommand();
- var MainProperties = _TProperty.AsQueryable().Where(x => x.ParentId == 0).ToList();
- foreach (var item in TPropertyItems)
- {
- item.MainProperties = MainProperties;
- }
- _name = string.Empty;
- modalRef.UpdateConfigAsync();
- }
- else
- {
- MessageService.Warning("已存在该规格");
- }
- }
- }
- /// <summary>
- /// 新增子规格
- /// </summary>
- /// <param name="args"></param>
- /// <returns></returns>
- private async Task AddNewChildProperty(SkuSet? selectedValue, MouseEventArgs args)
- {
- var MainSelectedValue = selectedValue.MainSelect?.Value;
- if (!string.IsNullOrWhiteSpace(_name) && MainSelectedValue.HasValue && MainSelectedValue.Value > 0)
- {
- if (!_TProperty.IsAny(x => x.ParentId == MainSelectedValue && x.Name == _name))
- {
- await _TProperty.AsInsertable(new TProductProperty() { Name = _name, ParentId = MainSelectedValue.Value }).ExecuteCommandAsync();
- var child = TPropertyItems.Where(x => x.MainSelect?.Value == MainSelectedValue).First();
- child.ChildProperties = _TProperty.AsQueryable().Where(x => x.ParentId == MainSelectedValue).ToList();
- _name = string.Empty;
- modalRef?.UpdateConfigAsync();
- }
- else
- {
- MessageService.Warning("已存在该属性");
- }
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="file"></param>
- /// <returns></returns>
- private bool BeforeUpload(UploadFileItem file)
- {
- var isLt2M = file.Size / 1024 / 1024 <= 4;
- if (!isLt2M)
- {
- MessageService.Error("图片必须小于4M");
- return false;
- }
- return true;
- }
- /// <summary>
- /// Sku属性设置
- /// </summary>
- internal class SkuSet
- {
- /// <summary>
- /// 索引
- /// </summary>
- public int Index { get; set; }
- /// <summary>
- /// 主要属性列表
- /// </summary>
- public List<TProductProperty> MainProperties { get; set; }
- /// <summary>
- /// 被选主要属性
- /// </summary>
- public Select<long?, TProductProperty> MainSelect { get; set; }
- /// <summary>
- /// 被选中的主要值
- /// </summary>
- public long? MainSelectedValue { get; set; }
- /// <summary>
- /// 子属性列表
- /// </summary>
- public Select<long?, TProductProperty> ChildSelect { get; set; }
- /// <summary>
- /// 子属性值
- /// </summary>
- public List<TProductProperty> ChildProperties { get; set; }
- /// <summary>
- /// 子属性值
- /// </summary>
- public IEnumerable<long?> ChildSelectedValues { get; set; }
- }
- /// <summary>
- /// 是否初始化表单
- /// </summary>
- private bool IsControlByUser { get; set; } = false;
- /// <summary>
- ///
- /// </summary>
- private bool ImageLoading { get; set; } = false;
- /// <summary>
- ///
- /// </summary>
- private bool IsDisabled { get; set; } = false;
- /// <summary>
- ///
- /// </summary>
- private List<SkuSet> TPropertyItems = new();
- /// <summary>
- /// 正在被使用的属性
- /// </summary>
- private List<TProductProperty> UsingTPropertyItems { get; set; } = new();
- /// <summary>
- ///
- /// </summary>
- private List<UploadFileItem> FileList { get; set; } = new();
- /// <summary>
- ///
- /// </summary>
- private ModalRef<bool> modalRef = default;
- /// <summary>
- ///
- /// </summary>
- private string _name = string.Empty;
- /// <summary>
- ///
- /// </summary>
- private ITable SkuTable;
- #endregion
- /// <summary>
- /// 注入实例
- /// </summary>
- [Inject] private SqlSugarRepository<TProduct> _Repository { get; set; }
- /// <summary>
- ///
- /// </summary>
- [Inject] private SqlSugarRepository<TProductSku> _Sku { get; set; }
- /// <summary>
- ///
- /// </summary>
- [Inject] private SqlSugarRepository<TProductProperty> _TProperty { get; set; }
- /// <summary>
- ///
- /// </summary>
- private List<TProductProperty> tProperties { get; set; }
- /// <summary>
- ///
- /// </summary>
- [Inject] NavigationManager NavigationManager { get; set; }
- /// <summary>
- ///
- /// </summary>
- [Inject] IJSRuntime IJSRuntime { get; set; }
- }
|