Product.razor.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. 
  2. using System.Data.Common;
  3. using System.Drawing.Imaging;
  4. using System.Xml.Linq;
  5. using AntDesign;
  6. using AntDesign.TableModels;
  7. using EasyTemplate.Tool;
  8. using Microsoft.AspNetCore.Components;
  9. using Microsoft.AspNetCore.Components.Web;
  10. using Microsoft.JSInterop;
  11. using Org.BouncyCastle.Crypto;
  12. using SqlSugar;
  13. namespace EasyTemplate.Page.Pages;
  14. public partial class Product
  15. {
  16. protected override async Task OnInitializedAsync()
  17. {
  18. }
  19. protected override async Task OnAfterRenderAsync(bool firstRender)
  20. {
  21. if (firstRender)
  22. {
  23. await NavigationManager.RedirectLogin(IJSRuntime);
  24. tProperties = _TProperty.AsQueryable().ToTree(it => it.Children, it => it.ParentId, 0);
  25. }
  26. }
  27. #region 表格
  28. /// <summary>
  29. /// 查
  30. /// </summary>
  31. /// <returns></returns>
  32. private async Task Query()
  33. {
  34. Loading = true;
  35. RefAsync<int> total = 0;
  36. var products = await _Repository.AsQueryable()
  37. .Where(x => !x.IsDelete)
  38. .WhereIF(!string.IsNullOrWhiteSpace(Q_Name), x => x.Name.Contains(Q_Name))
  39. .WhereIF(!string.IsNullOrWhiteSpace(Q_Code), x => x.Code.Contains(Q_Code))
  40. .ToPageListAsync(Pi, Ps, total);
  41. products?.ForEach(item => {
  42. item.Skus = _Sku.AsQueryable().Where(x => x.ProductId == item.Id).ToList();
  43. });
  44. DataSource = products;
  45. Total = total.Value;
  46. Loading = false;
  47. }
  48. /// <summary>
  49. /// 增/改
  50. /// </summary>
  51. /// <param name="data"></param>
  52. /// <returns></returns>
  53. private bool InsertOrUpdate(TProduct data)
  54. {
  55. try
  56. {
  57. _Repository.Context.Ado.BeginTran();
  58. tProduct.Preview = string.Join(",", FileList.Select(x => x.Url).ToList());
  59. tProduct.TotalStock = tProduct.Skus.Sum(x => x.Stock);
  60. if (data.Id == 0)
  61. {
  62. if (_Repository.AsQueryable().Any(x => x.Name.ToLower() == data.Name.ToLower() || x.Code.ToLower() == data.Code.ToLower()))
  63. {
  64. throw new Exception("该商品已存在");
  65. }
  66. if (string.IsNullOrWhiteSpace(data.Code))
  67. {
  68. data.Code = $"TP{DateTime.Now.ToString("yyyyMMddHHmmssfff")}{new Random().Next(1000, 9999)}";
  69. }
  70. //新增商品
  71. var id = _Repository.AsInsertable(data).ExecuteReturnBigIdentity();
  72. //新增规格
  73. _Sku.AsDeleteable().Where(x => x.ProductId == id).ExecuteCommand();
  74. data.Skus.ForEach(item => { item.ProductId = id; });
  75. _Sku.AsInsertable(data.Skus).ExecuteCommand();
  76. }
  77. else
  78. {
  79. if (_Repository.AsQueryable().Any(x => x.Name.ToLower() == data.Name.ToLower() && x.Id != data.Id))
  80. {
  81. throw new Exception("该商品已存在");
  82. }
  83. //更新商品
  84. _Repository.AsUpdateable()
  85. .SetColumns(x => x.Name == data.Name)
  86. .SetColumns(x => x.Description == data.Description)
  87. .SetColumns(x => x.Preview == data.Preview)
  88. .SetColumns(x => x.Content == data.Content)
  89. .Where(x => x.Id == data.Id)
  90. .ExecuteCommand();
  91. //新增规格
  92. _Sku.AsDeleteable().Where(x => x.ProductId == data.Id).ExecuteCommand();
  93. data.Skus.ForEach(item => { item.ProductId = data.Id; });
  94. _Sku.AsInsertable(data.Skus).ExecuteCommand();
  95. }
  96. _Repository.Context.Ado.CommitTran();
  97. return true;
  98. }
  99. catch (Exception ex)
  100. {
  101. Log.Error($"商品增改失败:{ex}");
  102. _Repository.Context.Ado.RollbackTran();
  103. return false;
  104. }
  105. }
  106. /// <summary>
  107. /// 重置查询
  108. /// </summary>
  109. private async Task ResetQuery()
  110. {
  111. Q_Name = Q_Code = string.Empty;
  112. Pi = 1;
  113. await Query();
  114. }
  115. /// <summary>
  116. /// 表格使用它来初始化,不要在页面初始化时调用,否则会导致重复加载
  117. /// </summary>
  118. /// <param name="query"></param>
  119. /// <returns></returns>
  120. private async Task OnChange(QueryModel<TProduct> query)
  121. => await Query();
  122. private async Task Search()
  123. {
  124. Pi = 1;
  125. await Query();
  126. }
  127. private void CheckedChanged(TProduct row)
  128. {
  129. _Repository.AsUpdateable()
  130. .SetColumns(x => x.Available == row.Available)
  131. .Where(x => x.Id == row.Id)
  132. .ExecuteCommand();
  133. }
  134. /// <summary>
  135. /// 名称
  136. /// </summary>
  137. private string Q_Name { get; set; }
  138. /// <summary>
  139. /// 编码
  140. /// </summary>
  141. private string Q_Code { get; set; }
  142. private TProduct tProduct = new();
  143. /// <summary>
  144. ///
  145. /// </summary>
  146. private ITable _Table;
  147. /// <summary>
  148. ///
  149. /// </summary>
  150. private IEnumerable<TProduct> SelectedRows = [];
  151. /// <summary>
  152. ///
  153. /// </summary>
  154. private List<TProduct> DataSource;
  155. /// <summary>
  156. ///
  157. /// </summary>
  158. private int Pi = 1;
  159. /// <summary>
  160. ///
  161. /// </summary>
  162. private int Ps = 20;
  163. /// <summary>
  164. ///
  165. /// </summary>
  166. private int Total;
  167. /// <summary>
  168. ///
  169. /// </summary>
  170. private bool Loading = false;
  171. /// <summary>
  172. ///
  173. /// </summary>
  174. private string imgUrl = string.Empty;
  175. /// <summary>
  176. ///
  177. /// </summary>
  178. private bool previewVisible = false;
  179. #endregion
  180. #region 表单方法
  181. /// <summary>
  182. /// 初始化表单
  183. /// </summary>
  184. /// <param name="row"></param>
  185. private void InitFormData(TProduct row)
  186. {
  187. IsControlByUser = false;
  188. UsingTPropertyItems.Clear();
  189. TPropertyItems.Clear();
  190. if (row != null)
  191. {
  192. //获取规格id并去重
  193. var ids = row.Skus
  194. .SelectMany(x => x.PropertyIds.Split(',', StringSplitOptions.RemoveEmptyEntries))
  195. .Select(idStr => long.TryParse(idStr, out var id) ? id : (long?)null)
  196. .Where(id => id.HasValue)
  197. .Select(id => id!.Value)
  198. .Distinct()
  199. .ToList();
  200. var Main = tProperties.Where(x => x.Children is null ? false : x.Children.Any(y => ids.Contains(y.Id))).ToList();
  201. for (int index = 0; index < Main.Count; index++)
  202. {
  203. var arr = Main[index].Children.Where(x => ids.Contains(x.Id)).Select(x => x.Id).ToArray();
  204. var newlist = tProperties.Except(Main).ToList();
  205. newlist.Add(Main[index]);
  206. TPropertyItems.Add(new SkuSet()
  207. {
  208. Index = (index + 1),
  209. MainProperties = newlist.OrderBy(x=>x.Id).ToList(),
  210. MainSelectedValue = Main[index].Id,
  211. ChildProperties = Main[index].Children,
  212. ChildSelectedValues = arr?.OfType<long?>() ?? Enumerable.Empty<long?>()
  213. });
  214. UsingTPropertyItems.Add(Main[index]);
  215. }
  216. }
  217. else
  218. {
  219. TPropertyItems.Add(new SkuSet() { Index = 1, MainProperties = tProperties });
  220. }
  221. IsDisabled = TPropertyItems.Count >= tProperties.Count;
  222. FileList.Clear();
  223. if (!string.IsNullOrWhiteSpace(tProduct.Preview))
  224. {
  225. var imgs = tProduct.Preview.Split(",").ToList();
  226. for (int index = 0; index < imgs.Count; index++)
  227. {
  228. FileList.Add(new UploadFileItem { Id = (index + 1).ToString(), State = UploadState.Success, Url = imgs[index], FileName = Path.GetFileName(imgs[index]) });
  229. }
  230. }
  231. }
  232. /// <summary>
  233. /// 更新规格表
  234. /// </summary>
  235. private void GenerateSkuTable()
  236. {
  237. if (TPropertyItems?.Count > 0)
  238. {
  239. tProduct.Skus = new();
  240. var selectedValuesLists = TPropertyItems
  241. .Where(item => item.ChildSelectedValues != null && item.ChildSelectedValues.Any())
  242. .Select(item => item.ChildSelectedValues.ToList())
  243. .ToList();
  244. var res = GenerateCartesianProduct(selectedValuesLists)
  245. .Select(combination => string.Join(",", combination))
  246. .ToList();
  247. var skus = new List<TProductSku>();
  248. for (int index = 0; index < res.Count; index++)
  249. {
  250. var names = _TProperty.AsQueryable()
  251. .Where(x => SqlFunc.SplitIn(res[index], x.Id.ToString()))
  252. .Select(x => x.Name)
  253. .ToList();
  254. skus.Add(new TProductSku()
  255. {
  256. PropertyIds = res[index],
  257. PropertyName = string.Join(",", names),
  258. Code = $"S{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-{(index + 1)}",
  259. });
  260. }
  261. tProduct.Skus = skus;
  262. }
  263. IsDisabled = TPropertyItems?.Count >= tProperties.Count;
  264. modalRef.UpdateConfigAsync();
  265. }
  266. private static IEnumerable<IEnumerable<T>> GenerateCartesianProduct<T>(IEnumerable<IEnumerable<T>> sequences)
  267. {
  268. IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
  269. return sequences.Aggregate(
  270. emptyProduct,
  271. (accumulator, sequence) =>
  272. from acc in accumulator
  273. from item in sequence
  274. select acc.Concat(new[] { item }));
  275. }
  276. /// <summary>
  277. /// 新增规格选择框
  278. /// </summary>
  279. private void AddProperty()
  280. {
  281. if (TPropertyItems[TPropertyItems.Count - 1].MainSelect?.Value == null)
  282. {
  283. MessageService.Warning("还未选择规格");
  284. return;
  285. }
  286. if (TPropertyItems[TPropertyItems.Count - 1].ChildSelectedValues?.Count() == 0)
  287. {
  288. MessageService.Warning("还未选择规格");
  289. return;
  290. }
  291. var prop = tProperties.Except(UsingTPropertyItems).ToList();
  292. TPropertyItems.Add(new SkuSet() { Index = TPropertyItems.Count + 1, MainProperties = prop });
  293. if (prop.Count == 1)
  294. {
  295. IsDisabled = true;
  296. }
  297. modalRef.UpdateConfigAsync();
  298. }
  299. /// <summary>
  300. /// 删除规格选择框
  301. /// </summary>
  302. /// <param name="selectedValue"></param>
  303. /// <param name="args"></param>
  304. private void DeleteProperty(SkuSet? selectedValue, MouseEventArgs args)
  305. {
  306. TPropertyItems.Remove(selectedValue);
  307. var current = selectedValue.MainProperties.Where(x => x.Id == selectedValue.MainSelectedValue).FirstOrDefault();
  308. UsingTPropertyItems.Remove(current);
  309. UpdatePropertyItems();
  310. GenerateSkuTable();
  311. }
  312. /// <summary>
  313. /// 触发点击说明用户开始操作
  314. /// </summary>
  315. private void OnClick()
  316. {
  317. IsControlByUser = true;
  318. }
  319. /// <summary>
  320. /// 主规格被选
  321. /// </summary>
  322. /// <param name="value"></param>
  323. private void OnMainSelectedItemChanged(SkuSet? selectedValue, TProductProperty value)
  324. {
  325. if (!IsControlByUser) return;
  326. TProductProperty old = null;
  327. if (UsingTPropertyItems.Count >= selectedValue.Index && UsingTPropertyItems[selectedValue.Index - 1].Id != value.Id)
  328. {
  329. old = UsingTPropertyItems[selectedValue.Index - 1];
  330. UsingTPropertyItems[selectedValue.Index - 1] = value;
  331. }
  332. if (!UsingTPropertyItems.Any(x => x.Id == value.Id))
  333. {
  334. UsingTPropertyItems.Add(value);
  335. }
  336. UpdatePropertyItems(old, value);
  337. modalRef.UpdateConfigAsync();
  338. }
  339. private void UpdatePropertyItems(TProductProperty oldValue = null, TProductProperty newValue = null)
  340. {
  341. foreach (var TPropertyItem in TPropertyItems)
  342. {
  343. var newlist = tProperties.Except(UsingTPropertyItems).ToList() ?? new();
  344. var current = tProperties.Where(x => x.Id == TPropertyItem.MainSelectedValue).FirstOrDefault();
  345. newlist.Add(current);
  346. TPropertyItem.MainProperties = newlist.OrderBy(x => x.Id).ToList();
  347. TPropertyItem.ChildProperties = _TProperty.AsQueryable().Where(x => x.ParentId == TPropertyItem.MainSelectedValue).ToList();
  348. if (oldValue != null
  349. && newValue != null
  350. && oldValue.Id != TPropertyItem.MainSelectedValue
  351. && newValue.Id == TPropertyItem.MainSelectedValue)
  352. {
  353. TPropertyItem.ChildSelectedValues = default;
  354. }
  355. }
  356. }
  357. /// <summary>
  358. /// 子规格被选
  359. /// </summary>
  360. /// <param name="value"></param>
  361. private void OnChildSelectedItemsChanged(IEnumerable<TProductProperty> value)
  362. {
  363. if (!IsControlByUser) return;
  364. GenerateSkuTable();
  365. }
  366. /// <summary>
  367. /// 新增规格
  368. /// </summary>
  369. /// <param name="args"></param>
  370. private void AddNewMainProperty(MouseEventArgs args)
  371. {
  372. if (!string.IsNullOrWhiteSpace(_name))
  373. {
  374. if (!_TProperty.IsAny(x => x.Name == _name))
  375. {
  376. _TProperty.AsInsertable(new TProductProperty() { Name = _name }).ExecuteCommand();
  377. var MainProperties = _TProperty.AsQueryable().Where(x => x.ParentId == 0).ToList();
  378. foreach (var item in TPropertyItems)
  379. {
  380. item.MainProperties = MainProperties;
  381. }
  382. _name = string.Empty;
  383. modalRef.UpdateConfigAsync();
  384. }
  385. else
  386. {
  387. MessageService.Warning("已存在该规格");
  388. }
  389. }
  390. }
  391. /// <summary>
  392. /// 新增子规格
  393. /// </summary>
  394. /// <param name="args"></param>
  395. /// <returns></returns>
  396. private async Task AddNewChildProperty(SkuSet? selectedValue, MouseEventArgs args)
  397. {
  398. var MainSelectedValue = selectedValue.MainSelect?.Value;
  399. if (!string.IsNullOrWhiteSpace(_name) && MainSelectedValue.HasValue && MainSelectedValue.Value > 0)
  400. {
  401. if (!_TProperty.IsAny(x => x.ParentId == MainSelectedValue && x.Name == _name))
  402. {
  403. await _TProperty.AsInsertable(new TProductProperty() { Name = _name, ParentId = MainSelectedValue.Value }).ExecuteCommandAsync();
  404. var child = TPropertyItems.Where(x => x.MainSelect?.Value == MainSelectedValue).First();
  405. child.ChildProperties = _TProperty.AsQueryable().Where(x => x.ParentId == MainSelectedValue).ToList();
  406. _name = string.Empty;
  407. modalRef?.UpdateConfigAsync();
  408. }
  409. else
  410. {
  411. MessageService.Warning("已存在该属性");
  412. }
  413. }
  414. }
  415. /// <summary>
  416. ///
  417. /// </summary>
  418. /// <param name="file"></param>
  419. /// <returns></returns>
  420. private bool BeforeUpload(UploadFileItem file)
  421. {
  422. var isLt2M = file.Size / 1024 / 1024 <= 4;
  423. if (!isLt2M)
  424. {
  425. MessageService.Error("图片必须小于4M");
  426. return false;
  427. }
  428. return true;
  429. }
  430. /// <summary>
  431. /// Sku属性设置
  432. /// </summary>
  433. internal class SkuSet
  434. {
  435. /// <summary>
  436. /// 索引
  437. /// </summary>
  438. public int Index { get; set; }
  439. /// <summary>
  440. /// 主要属性列表
  441. /// </summary>
  442. public List<TProductProperty> MainProperties { get; set; }
  443. /// <summary>
  444. /// 被选主要属性
  445. /// </summary>
  446. public Select<long?, TProductProperty> MainSelect { get; set; }
  447. /// <summary>
  448. /// 被选中的主要值
  449. /// </summary>
  450. public long? MainSelectedValue { get; set; }
  451. /// <summary>
  452. /// 子属性列表
  453. /// </summary>
  454. public Select<long?, TProductProperty> ChildSelect { get; set; }
  455. /// <summary>
  456. /// 子属性值
  457. /// </summary>
  458. public List<TProductProperty> ChildProperties { get; set; }
  459. /// <summary>
  460. /// 子属性值
  461. /// </summary>
  462. public IEnumerable<long?> ChildSelectedValues { get; set; }
  463. }
  464. /// <summary>
  465. /// 是否初始化表单
  466. /// </summary>
  467. private bool IsControlByUser { get; set; } = false;
  468. /// <summary>
  469. ///
  470. /// </summary>
  471. private bool ImageLoading { get; set; } = false;
  472. /// <summary>
  473. ///
  474. /// </summary>
  475. private bool IsDisabled { get; set; } = false;
  476. /// <summary>
  477. ///
  478. /// </summary>
  479. private List<SkuSet> TPropertyItems = new();
  480. /// <summary>
  481. /// 正在被使用的属性
  482. /// </summary>
  483. private List<TProductProperty> UsingTPropertyItems { get; set; } = new();
  484. /// <summary>
  485. ///
  486. /// </summary>
  487. private List<UploadFileItem> FileList { get; set; } = new();
  488. /// <summary>
  489. ///
  490. /// </summary>
  491. private ModalRef<bool> modalRef = default;
  492. /// <summary>
  493. ///
  494. /// </summary>
  495. private string _name = string.Empty;
  496. /// <summary>
  497. ///
  498. /// </summary>
  499. private ITable SkuTable;
  500. #endregion
  501. /// <summary>
  502. /// 注入实例
  503. /// </summary>
  504. [Inject] private SqlSugarRepository<TProduct> _Repository { get; set; }
  505. /// <summary>
  506. ///
  507. /// </summary>
  508. [Inject] private SqlSugarRepository<TProductSku> _Sku { get; set; }
  509. /// <summary>
  510. ///
  511. /// </summary>
  512. [Inject] private SqlSugarRepository<TProductProperty> _TProperty { get; set; }
  513. /// <summary>
  514. ///
  515. /// </summary>
  516. private List<TProductProperty> tProperties { get; set; }
  517. /// <summary>
  518. ///
  519. /// </summary>
  520. [Inject] NavigationManager NavigationManager { get; set; }
  521. /// <summary>
  522. ///
  523. /// </summary>
  524. [Inject] IJSRuntime IJSRuntime { get; set; }
  525. }