基础服务api
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

1319 lines
55 KiB

  1. using BPA.Franchisee.Application.FranchiseeCenter.GoodsServices;
  2. using BPA.SAAS.Manage.Application.DataBase.Dtos.Batching;
  3. using BPA.SAAS.Manage.Application.DataBase.Dtos.Goods;
  4. using BPA.SAAS.Manage.Application.DataBase.Dtos.GoodsAttribute;
  5. using BPA.SAAS.Manage.Application.DataBase.Interface;
  6. using BPA.SAAS.Manage.Application.System.Dtos;
  7. using BPA.SAAS.Manage.Application.System.Interface;
  8. using BPA.SAAS.Manage.Application.System.Services;
  9. using BPA.SAAS.Manage.Comm.Const;
  10. using BPA.SAAS.Manage.Comm.Enum;
  11. using BPA.SAAS.Manage.Comm.Util;
  12. using BPA.SAAS.Manage.Core.Base;
  13. using BPA.SAAS.Manage.Core.DataBase;
  14. using BPA.SAAS.Manage.Core.Device;
  15. using BPA.SAAS.Manage.Core.Product;
  16. using Newtonsoft.Json;
  17. using Npoi.Mapper;
  18. using NPOI.HSSF.UserModel;
  19. using NPOI.SS.UserModel;
  20. using NPOI.SS.Util;
  21. using NPOI.XSSF.UserModel;
  22. using System;
  23. using System.Collections;
  24. using System.ComponentModel.DataAnnotations.Schema;
  25. using System.Data;
  26. using System.Drawing;
  27. using System.Drawing.Imaging;
  28. using System.Linq;
  29. using System.Reflection;
  30. using System.Text;
  31. using System.Threading.Tasks;
  32. namespace BPA.SAAS.Manage.Application.DataBase.Services
  33. {
  34. public class GoodsService: IGoodsService, ITransient
  35. {
  36. private readonly ISqlSugarClient _db;
  37. IGoodsAttributeService _goodsAttributeService;
  38. ISystemConfigService _SystemConfigService;
  39. public GoodsService(ISqlSugarClient db, IGoodsAttributeService goodsAttributeService, ISystemConfigService SystemConfigService)
  40. {
  41. _db=db;
  42. _goodsAttributeService=goodsAttributeService;
  43. _SystemConfigService = SystemConfigService;
  44. }
  45. /// <summary>
  46. /// 分页查询
  47. /// </summary>
  48. /// <param name="dto"></param>
  49. /// <returns></returns>
  50. public async Task<PageUtil> GetGoodsPage(GoodsQueryDto dto)
  51. {
  52. List<IConditionalModel> conModels = new List<IConditionalModel>();
  53. #region 条件查询
  54. if (!string.IsNullOrEmpty(dto.Name))
  55. {
  56. conModels.Add(new ConditionalModel() { FieldName = "a.Name", ConditionalType = ConditionalType.Like, FieldValue = dto.Name });
  57. }
  58. if (!string.IsNullOrEmpty(dto.GoodsTypeName))
  59. {
  60. conModels.Add(new ConditionalModel() { FieldName = "a.GoodsTypeId", ConditionalType = ConditionalType.Equal, FieldValue = dto.GoodsTypeName });
  61. }
  62. if (!string.IsNullOrEmpty(dto.Status))
  63. {
  64. conModels.Add(new ConditionalModel() { FieldName = "a.Status", ConditionalType = ConditionalType.Like, FieldValue = dto.Status });
  65. }
  66. #endregion
  67. RefAsync<int> total = 0;
  68. var res =await _db.Queryable<BPA_GoodsInfo, BPA_GoodsType>((a, b) => new JoinQueryInfos(
  69. JoinType.Left, a.GoodsTypeId == b.Id
  70. ))
  71. .WhereIF(!string.IsNullOrWhiteSpace(dto.Code), (a, b) => a.Code.Contains(dto.Code))
  72. // .WhereIF(dto.CreateAt.HasValue, (a, b) => SqlFunc.DateIsSame(a.CreateAt, Convert.ToDateTime(dto.CreateAt), DateType.Day))
  73. .Where(conModels)
  74. .OrderBy(a => a.CreateAt, OrderByType.Desc)
  75. .Select((a, b) => new
  76. {
  77. Id = a.Id,
  78. Code = a.Code,
  79. Name = a.Name,
  80. Price = a.Price,
  81. ImgUrl = a.ImgUrl,
  82. Status = a.Status,
  83. GoodsTypeId = b.IsDeleted == 0 ? a.GoodsTypeId : "",
  84. GoodsTypeName = b.IsDeleted == 0 ? b.Name : "",
  85. Descritption = a.Descritption,
  86. IsDeleted = a.IsDeleted,
  87. // CreateAt = a.CreateAt,
  88. GoodsUintId = a.GoodsUintId,
  89. ForeignKeyRe = a.ForeignKeyRe,
  90. Design = a.Design,
  91. IsWeigh = a.IsWeigh,
  92. DefaultMate = a.DefaultMate,
  93. IsAttrubute = a.IsAttrubute,
  94. Goodstechnology = SqlFunc.Subqueryable<BPA_GoodsTechnologyAction>().Where(p => p.GoodsId == a.Id).WhereIF(!string.IsNullOrWhiteSpace(dto.DeviceId),p=>p.DeviceId== dto.DeviceId).ToList(),
  95. })
  96. .ToPageListAsync(dto.Current, dto.PageSize, total);
  97. PageUtil util = new PageUtil()
  98. {
  99. Total = total,
  100. Data = res
  101. };
  102. return util;
  103. }
  104. /// <summary>
  105. /// 查询所有商品
  106. /// </summary>
  107. /// <returns></returns>
  108. public async Task<List<BPA_GoodsInfo>> GetGoodsList()
  109. {
  110. var res = await _db.Queryable<BPA_GoodsInfo>().ToListAsync();
  111. return res;
  112. }
  113. /// <summary>
  114. /// 添加商品
  115. /// </summary>
  116. /// <param name="dto"></param>
  117. /// <returns></returns>
  118. public async Task<bool> AddGoods(GoodsDto dto)
  119. {
  120. if (string.IsNullOrWhiteSpace(dto.Id))
  121. {
  122. var resEntity = new BPA_GoodsInfo();
  123. resEntity.Id = Guid.NewGuid().ToString();
  124. resEntity.GoodsTypeId = dto.GoodsTypeId;
  125. resEntity.Name = dto.Name;
  126. resEntity.Descritption = dto.Descritption;
  127. resEntity.ImgUrl = dto.ImgUrl;
  128. resEntity.Price = dto.Price;
  129. resEntity.IsWeigh = dto.IsWeigh;
  130. resEntity.GoodsUintId = dto.GoodsUintId;
  131. resEntity.IsAttrubute = dto.IsAttrubute;
  132. resEntity.Code = GetNumber2(8);
  133. var data = _db.Queryable<BPA_GoodsInfo>().Max(x => x.AutoKey);
  134. //if (data == 0) data = 1000;
  135. //else data = data + 1;
  136. // resEntity.AutoKey = data;
  137. var res = await _db.Insertable(resEntity).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
  138. return res > 0;
  139. }
  140. else
  141. {
  142. return await UpdateGoods(dto);
  143. }
  144. }
  145. /// <summary>
  146. /// 更新商品
  147. /// </summary>
  148. /// <param name="dto"></param>
  149. /// <returns></returns>
  150. public async Task<bool> UpdateGoods(GoodsDto dto)
  151. {
  152. // 查询数据库中是否存在未删除的商品类型
  153. var resEntity = _db.Queryable<BPA_GoodsInfo>().Where(it => it.IsDeleted == 0).First(it => it.Id == dto.Id);
  154. if (null == resEntity)
  155. {
  156. throw Oops.Oh("商品不存在");
  157. }
  158. resEntity.GoodsTypeId = dto.GoodsTypeId;
  159. resEntity.Name = dto.Name;
  160. resEntity.Descritption = dto.Descritption;
  161. resEntity.ImgUrl = dto.ImgUrl;
  162. resEntity.Price = dto.Price;
  163. resEntity.IsWeigh = dto.IsWeigh;
  164. resEntity.GoodsUintId = dto.GoodsUintId;
  165. resEntity.IsAttrubute = Convert.ToBoolean(dto.IsAttrubute);
  166. if (!string.IsNullOrWhiteSpace(dto.Status))
  167. {
  168. resEntity.Status = (CommonStatus)Enum.ToObject(typeof(CommonStatus), int.Parse(dto.Status));
  169. }
  170. var res = await _db.Updateable(resEntity).ExecuteCommandAsync();
  171. return res > 0;
  172. }
  173. /// <summary>
  174. /// 删除商品
  175. /// </summary>
  176. /// <param name="id"></param>
  177. /// <returns></returns>
  178. public async Task<bool> DeleteGoods(string id)
  179. {
  180. try
  181. {
  182. _db.Ado.BeginTran();
  183. var goods = _db.Queryable<BPA_GoodsInfo>().Where(x => x.Id == id).First();
  184. if (goods == null) throw Oops.Oh("商品不存在");
  185. var goodsbom = _db.Queryable<BPA_GoodsBom>().Where(x => x.Goods_Id == id).ToList();
  186. var goodsTechnology = _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.GoodsId == id).ToList();
  187. await _db.Deleteable(goodsbom).ExecuteCommandAsync();
  188. await _db.Deleteable(goodsTechnology).ExecuteCommandAsync();
  189. var res = await _db.Deleteable(goods).ExecuteCommandAsync();
  190. _db.Ado.CommitTran();
  191. return res > 0;
  192. }
  193. catch (Exception)
  194. {
  195. _db.Ado.RollbackTran();
  196. throw Oops.Oh("删除失败");
  197. }
  198. }
  199. /// <summary>
  200. /// 查询商品单位
  201. /// </summary>
  202. /// <returns></returns>
  203. public async Task<List<dynamic>> GetGoodsUintList()
  204. {
  205. var res = await _db.Queryable<BPA_GoodsUint>().Select<dynamic>(x => new
  206. {
  207. id = x.Id,
  208. name = x.Name
  209. }).ToListAsync();
  210. return res;
  211. }
  212. /// <summary>
  213. /// 添加商品单位
  214. /// </summary>
  215. /// <param name="dto"></param>
  216. /// <returns></returns>
  217. public async Task<bool> AddGoodsUint(GoodsUintDto dto)
  218. {
  219. var productCode = _db.Queryable<BPA_GoodsUint>().Where(x =>x.Name == dto.Name).ToList();
  220. if (productCode.Count() > 0)
  221. {
  222. throw Oops.Oh("商品单位已存在");
  223. }
  224. try
  225. {
  226. BPA_GoodsUint bPA_Product = new BPA_GoodsUint();
  227. bPA_Product.Name = dto.Name;
  228. var res = await _db.Insertable(bPA_Product).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
  229. return res > 0;
  230. }
  231. catch (Exception ex)
  232. {
  233. throw Oops.Oh("添加失败");
  234. }
  235. }
  236. /// <summary>
  237. /// 商品配方
  238. /// </summary>
  239. /// <param name="dto"></param>
  240. /// <returns></returns>
  241. public async Task<PageUtil> GetGoodsBomPageAsync(OrtherGoodsQueryDto dto)
  242. {
  243. RefAsync<int> total = 0;
  244. var res =await _db.Queryable<BPA_Bom, BPA_GoodsBom>((a, b) => new JoinQueryInfos(
  245. JoinType.Left, a.Id == b.BomId
  246. ))
  247. .WhereIF(!string.IsNullOrWhiteSpace(dto.GoodsId), (a, b) => b.Goods_Id == dto.GoodsId)
  248. .Select((a, b) => new
  249. {
  250. Id = b.Id,
  251. Name = a.Name,
  252. BomId= b.BomId,
  253. IsMain = a.IsMain
  254. })
  255. .ToPageListAsync(dto.Current, dto.PageSize, total);
  256. PageUtil util = new PageUtil()
  257. {
  258. Total = total,
  259. Data = res
  260. };
  261. return util;
  262. }
  263. /// <summary>
  264. /// 删除商品配方
  265. /// </summary>
  266. /// <param name="Ids"></param>
  267. /// <returns></returns>
  268. public async Task<bool> BatchDelGoodsBomAsync(string Ids)
  269. {
  270. // var GoodsBom=_db.Queryable<BPA_GoodsBom>().Where(x => x.Id == Ids).First();
  271. // 查询数据库中是否存在未删除的商品
  272. var res = _db.Deleteable<BPA_GoodsBom>().In(Ids).ExecuteCommand();
  273. return res > 0;
  274. }
  275. /// <summary>
  276. /// 添加商品配方
  277. /// </summary>
  278. /// <param name="dto"></param>
  279. /// <returns></returns>
  280. public async Task<bool> AddGoodsBomAttribute(GoodsBomAttributeDto dto)
  281. {
  282. _db.Ado.BeginTran();
  283. try
  284. {
  285. var sortMax = _db.Queryable<BPA_Bom>().Max(x => x.Sort);
  286. BPA_Bom newbPA_BOM = new BPA_Bom
  287. {
  288. Name = dto.BomName,
  289. Code = GetNumber2(),
  290. IsMain = dto.BomType == "1" ? true : false,
  291. Sort = sortMax + 1,
  292. Id = Guid.NewGuid().ToString(),
  293. CreateAt = DateTime.Now,
  294. Status = CommonStatus.ENABLE,
  295. };
  296. //添加配方
  297. var res = _db.Insertable(newbPA_BOM).CallEntityMethod(m => m.Create()).ExecuteCommand();
  298. //添加配方分类
  299. var list = dto.BomtypeList.Select(item => new BPA_BomTypeInfo() { BomId = newbPA_BOM.Id, BomTypeId = item }).ToList();
  300. _db.Insertable(list).CallEntityMethod(m => m.Create()).ExecuteCommand();
  301. BPA_GoodsBom bom = new BPA_GoodsBom();
  302. bom.Goods_Id = dto.GoodsId;
  303. bom.BomId = newbPA_BOM.Id;
  304. bom.Status = CommonStatus.ENABLE;
  305. //添加商品配方关系
  306. _db.Insertable(bom).CallEntityMethod(m => m.Create()).ExecuteCommand();
  307. List<BPA_BomEntry> BOMEntryList = new();
  308. if (dto.Mate.Count > 0)
  309. {
  310. for (int i = 0; i < dto.Mate.Count; i++)
  311. {
  312. BPA_BomEntry newbPA_BOMEnty = new BPA_BomEntry
  313. {
  314. BatchingId = dto.Mate[i].batchingId,
  315. //BatchingKey = dto.Mate[i].AutoKey,
  316. BomQty = dto.Mate[i].dosage,
  317. BomId = newbPA_BOM.Id,
  318. Status = CommonStatus.ENABLE,
  319. IsReplace = false,
  320. };
  321. BOMEntryList.Add(newbPA_BOMEnty);
  322. }
  323. }
  324. //添加配方物料关系
  325. _db.Insertable(BOMEntryList).CallEntityMethod(m => m.Create()).ExecuteCommand();
  326. BPA_BomAttributeValueRe bPA_BomAttributeValueRe = new();
  327. bPA_BomAttributeValueRe.Id = Guid.NewGuid().ToString();
  328. bPA_BomAttributeValueRe.GoodsId = dto.GoodsId;
  329. bPA_BomAttributeValueRe.BoomId = newbPA_BOM.Id;
  330. bPA_BomAttributeValueRe.GoodsAttributeValueId = string.Join(",", dto.Shuxing);
  331. //添加商品配方属性关系
  332. _db.Insertable(bPA_BomAttributeValueRe).ExecuteCommand();
  333. _db.Ado.CommitTran();
  334. return true;
  335. }
  336. catch (Exception e)
  337. {
  338. _db.Ado.RollbackTran();
  339. throw Oops.Oh("添加失败,失败信息:" + e.Message);
  340. }
  341. }
  342. public async Task<bool> AddGoodsBom(GoodsBomDto dto)
  343. {
  344. var res = false;
  345. List<BPA_GoodsBom> list = new();
  346. if (dto.BomId.Count() > 0)
  347. {
  348. for (int i = 0; i < dto.BomId.Count; i++)
  349. {
  350. BPA_GoodsBom goodsBom = new();
  351. goodsBom.BomId = dto.BomId[i];
  352. goodsBom.Goods_Id= dto.GoodsId;
  353. goodsBom.Status = CommonStatus.ENABLE;
  354. list.Add(goodsBom);
  355. }
  356. }
  357. if (list.Count>0)
  358. {
  359. res=await _db.Insertable(list).CallEntityMethod(m => m.Create()).ExecuteCommandAsync()>0;
  360. }
  361. return res;
  362. }
  363. /// <summary>
  364. /// 根据id查询商品信息
  365. /// </summary>
  366. /// <param name="id"></param>
  367. /// <returns></returns>
  368. public async Task<GoodsInfoBaseView> GetGoods(string id)
  369. {
  370. var res = await _db.Queryable<BPA_GoodsInfo>()
  371. .Where((a) => a.IsDeleted == 0 && a.Id == id)
  372. .OrderBy(a => a.CreateAt, OrderByType.Desc)
  373. .Select((a) => new GoodsInfoBaseView
  374. {
  375. Id = a.Id,
  376. Code = a.Code,
  377. Name = a.Name,
  378. Price = a.Price,
  379. ImgUrl = a.ImgUrl,
  380. Status = a.Status,
  381. GoodsTypeId = a.GoodsTypeId,
  382. GoodsTypeName = SqlFunc.Subqueryable<BPA_GoodsType>().Where(s => s.Id == a.GoodsTypeId && s.IsDeleted == 0).Select(s => s.Name),
  383. Remark = a.Descritption,
  384. // CreateAt = a.CreateAt,
  385. GoodsUintId = a.GoodsUintId,
  386. IsAttrubute = a.IsAttrubute,
  387. GoodsUintName = SqlFunc.Subqueryable<BPA_GoodsUint>().Where(s => s.Id == a.GoodsUintId && s.IsDeleted == 0).Select(s => s.Name),
  388. //GoodsAttributeList = new List<GoodsAttributeList>()
  389. }).FirstAsync();
  390. if (!res.IsAttrubute)
  391. {
  392. res.GoodsAttributeList = await _goodsAttributeService.GetByNameAttribute("默认属性");
  393. }
  394. else
  395. {
  396. res.GoodsAttributeList = await _goodsAttributeService.GetByGoodsIdAttribute(res.Id);
  397. }
  398. return res;
  399. }
  400. public async Task<bool> ExportGood(IFormFile file)
  401. {
  402. bool isReplace = true;
  403. try
  404. {
  405. //var groupId = string.IsNullOrWhiteSpace(CurrentUser.TenantId)
  406. //? App.User?.FindFirst(ClaimConst.GroupId)?.Value
  407. // : CurrentUser.TenantId;
  408. var userId = App.User?.FindFirst(ClaimConst.CLAINM_USERID)?.Value;
  409. if (string.IsNullOrEmpty(userId))
  410. {
  411. userId = "";
  412. }
  413. var source = file.OpenReadStream();
  414. var mapper = new Mapper(source);
  415. _db.Ado.BeginTran();
  416. //添加 设备_烹饪工序模型
  417. #region 添加 设备_烹饪工序模型
  418. //ReadExcel<GoodstechnologyModel> readGoodstechnologyExcel = new();
  419. //var GoodstechnologyModellist = readGoodstechnologyExcel.ExcelToList(source, mapper, "设备_烹饪工序模型");
  420. //List<BPA_GoodsTechnology> GoodsTechnologyList = new();
  421. //List<BPA_TechnologyAction> GoodsTechnologyActionList = new();
  422. //string currennaid = "";
  423. //for (int i = 0; i < GoodstechnologyModellist.Count; i++)
  424. //{
  425. // if (!string.IsNullOrWhiteSpace(GoodstechnologyModellist[i].Name))
  426. // {
  427. // BPA_GoodsTechnology item = new BPA_GoodsTechnology()
  428. // {
  429. // Id = Guid.NewGuid().ToString(),
  430. // Name = GoodstechnologyModellist[i].Name,
  431. // Status = 0,
  432. // CreateAt = DateTime.Now,
  433. // GroupId = groupId,
  434. // IsDeleted = 0,
  435. // };
  436. // GoodsTechnologyList.Add(item);
  437. // currennaid = item.Id;
  438. // }
  439. // var actvalueary = GoodstechnologyModellist[i].ActionValue?.Split('、');
  440. // BPA_TechnologyAction technologyAction = new()
  441. // {
  442. // Id = Guid.NewGuid().ToString(),
  443. // GoodstechnologyId = currennaid,
  444. // ActionName = GoodstechnologyModellist[i].ActionName,
  445. // ActionType = GoodstechnologyModellist[i].ActionType,
  446. // Sort = i,
  447. // GroupId = groupId,
  448. // CreateAt = DateTime.Now,
  449. // //ActionValue = GoodstechnologyModellist[i].ActionValue,
  450. // };
  451. // List<ActionValueModel> ActionValueModelList = new();
  452. // if (actvalueary != null)
  453. // {
  454. // foreach (var item in actvalueary)
  455. // {
  456. // ActionValueModelList.Add(new ActionValueModel() { actionValueName = item });
  457. // }
  458. // technologyAction.ActionValue = JsonConvert.SerializeObject(ActionValueModelList);
  459. // }
  460. // GoodsTechnologyActionList.Add(technologyAction);
  461. //}
  462. //await _db.Insertable(GoodsTechnologyList).ExecuteCommandAsync();
  463. //await _db.Insertable(GoodsTechnologyActionList).ExecuteCommandAsync();
  464. #endregion
  465. //添加 商品_物料信息
  466. #region 添加 商品_物料信息
  467. //1.查询并且添加类型
  468. var nonLiquid = await _db.Queryable<BPA_BatchingType>()
  469. .Where(x => x.Name == "非液体" ).FirstAsync();
  470. if (nonLiquid == null)
  471. {
  472. nonLiquid = new BPA_BatchingType()
  473. {
  474. IsDeleted = 0,
  475. Name = "非液体",
  476. };
  477. await _db.Insertable(nonLiquid).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
  478. }
  479. var liquid = await _db.Queryable<BPA_BatchingType>()
  480. .Where(x => x.Name == "液体料").FirstAsync();
  481. if (liquid == null)
  482. {
  483. liquid = new BPA_BatchingType
  484. {
  485. IsDeleted = 0,
  486. Name = "液体料",
  487. };
  488. await _db.Insertable(liquid).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
  489. }
  490. //单位
  491. var unit = await _db.Queryable<BPA_BatchingUint>().Where(x => x.Name == "默认单位").FirstAsync();
  492. if (unit == null)
  493. {
  494. unit = new BPA_BatchingUint
  495. {
  496. IsDeleted = 0,
  497. Name = "默认单位",
  498. };
  499. await _db.Insertable(unit).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
  500. }
  501. //3.物料
  502. ReadExcel<BatchingModel> readGoodBaseModelExcel = new();
  503. var GoodBaseModellist = readGoodBaseModelExcel.ExcelToList(source, mapper, "商品_物料信息");
  504. List<BPA_Batching> batchingList = GoodBaseModellist.Select(t => new BPA_Batching()
  505. {
  506. Aittribute = 0,
  507. Batching_Name = t.BatchingName,
  508. Code = Guid.NewGuid().ToString(),
  509. IsDeleted = 0,
  510. netrecovery = 0,
  511. outstockUint = unit.Id,
  512. Price = 0,
  513. proportion = 0,
  514. Specs = "默认规格",
  515. Status = 0,
  516. StockUint = unit.Id,
  517. TypeID = t.BatchingType == "液体料" ? liquid.Id : nonLiquid.Id,
  518. }).ToList();
  519. var batchingNameList = batchingList.Select(x => x.Batching_Name).ToList();
  520. var batchingListrDb = _db.Queryable<BPA_Batching>().Where(x => batchingNameList.Contains(x.Batching_Name))
  521. .ToList();
  522. //替换
  523. if (isReplace)
  524. {
  525. foreach (var item2 in batchingList)
  526. {
  527. var thisitem = batchingListrDb.FirstOrDefault(x => x.Batching_Name == item2.Batching_Name);
  528. if (thisitem != null)
  529. {
  530. item2.Id = thisitem.Id;
  531. _db.Updateable(item2).ExecuteCommand();
  532. }
  533. else
  534. {
  535. _db.Insertable(item2).CallEntityMethod(m => m.Create()).ExecuteCommand();
  536. }
  537. }
  538. }
  539. else
  540. {
  541. var batchingListrDbName = batchingListrDb.Select(x => x.Batching_Name).ToList();
  542. batchingList = batchingList.Where(x => !batchingListrDbName.Contains(x.Batching_Name)).ToList();
  543. await _db.Insertable(batchingList).ExecuteCommandAsync();
  544. }
  545. #endregion
  546. //添加 商品_基础信息
  547. #region 添加 商品_基础信息
  548. //1.查询大分类 和小分类
  549. var type = new BPA_GoodsType();
  550. var parentType = await _db.Queryable<BPA_GoodsType>()
  551. .Where(x => x.Name == "默认分类" && x.GroupId == x.GroupId).FirstAsync();
  552. if (parentType == null)
  553. {
  554. parentType = new BPA_GoodsType()
  555. {
  556. IsDeleted = 0,
  557. Name = "默认分类",
  558. Remark = "",
  559. Sort = 0,
  560. Status = 0,
  561. Pid="0"
  562. };
  563. type=await _db.Insertable(parentType).CallEntityMethod(m => m.Create()).ExecuteReturnEntityAsync();
  564. }
  565. //属性
  566. var goodsAttribute = await _db.Queryable<BPA_GoodsAttribute>()
  567. .Where(x => x.AttributeName == "默认属性" ).FirstAsync();
  568. if (goodsAttribute == null)
  569. {
  570. goodsAttribute = new BPA_GoodsAttribute()
  571. {
  572. AttributeName = "默认属性",
  573. GoodsTypeId = type.Id,
  574. IsDeleted = 0,
  575. Sort = 0,
  576. };
  577. _db.Insertable(goodsAttribute).CallEntityMethod(m => m.Create()).ExecuteCommand();
  578. }
  579. var goodsattributevalue = await _db.Queryable<BPA_GoodsAttributeValue>()
  580. .FirstAsync(x => x.AttributeValue == "默认属性值" && x.GoodsAttributeId == goodsAttribute.Id && x.IsDeleted == 0);
  581. if (goodsattributevalue == null)
  582. {
  583. goodsattributevalue = new BPA_GoodsAttributeValue()
  584. {
  585. AttributeValue = "默认属性值",
  586. GoodsAttributeId = goodsAttribute.Id,
  587. IsDeleted = 0,
  588. Sort = 1,
  589. };
  590. _db.Insertable(goodsattributevalue).CallEntityMethod(m => m.Create()).ExecuteCommand();
  591. }
  592. ReadExcel<GoodModel> readGoodModelExcel = new();
  593. var oodModellist = readGoodModelExcel.ExcelToList(source, mapper, "商品_基础信息");
  594. List<BPA_GoodsInfo> goodsInfo = new List<BPA_GoodsInfo>();
  595. int index = 1;
  596. foreach (var item in oodModellist.Where(x => !string.IsNullOrEmpty(x.Name)))
  597. {
  598. //单位
  599. var goodsUint = await _db.Queryable<BPA_GoodsUint>().Where(x => x.Name == "默认单位").FirstAsync();
  600. if (goodsUint == null)
  601. {
  602. goodsUint = new BPA_GoodsUint()
  603. {
  604. IsDeleted = 0,
  605. Name = "默认单位",
  606. Status = 0,
  607. };
  608. await _db.Insertable(goodsUint).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
  609. }
  610. Console.WriteLine("数据解析完成,开始解析图片");
  611. var images = await ExcelToDatatable(file.OpenReadStream(), Path.GetExtension(file.FileName), "商品_基础信息");
  612. var imagePath = images.FirstOrDefault(x => x.Index == index);
  613. goodsInfo.Add(new BPA_GoodsInfo()
  614. {
  615. Code = Guid.NewGuid().ToString(),
  616. CreateAt = DateTime.Now,
  617. CreateBy = userId,
  618. DefaultMate = null,
  619. Design = "默认规格",
  620. ForeignKeyRe = null,
  621. GoodsUintId = goodsUint.Id,
  622. Descritption = "",
  623. ImgMode = 0,
  624. ImgUrl = imagePath?.ImgesPath,
  625. Name = item.Name,
  626. Sort = 0,
  627. GoodsTypeId = type.Id,
  628. Price = 0,
  629. IsAttrubute = false,
  630. IsDeleted = 0,
  631. IsWeigh = false,
  632. Key = null,
  633. Status = 0,
  634. });
  635. index++;
  636. }
  637. var ngoodsInfoName = goodsInfo.Select(x => x.Name).ToList();
  638. var goodsInfoListDb = _db.Queryable<BPA_GoodsInfo>().Where(x => ngoodsInfoName.Contains(x.Name)).ToList();
  639. //替换
  640. if (isReplace)
  641. {
  642. foreach (var item2 in goodsInfo)
  643. {
  644. var thisitem = goodsInfoListDb.FirstOrDefault(x => x.Name == item2.Name);
  645. if (thisitem != null)
  646. {
  647. item2.Id = thisitem.Id;
  648. _db.Updateable(item2).ExecuteCommand();
  649. }
  650. else
  651. {
  652. await _db.Insertable(item2).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
  653. }
  654. }
  655. }
  656. else
  657. {
  658. var goodsInfoListDbName = goodsInfoListDb.Select(x => x.Name).ToList();
  659. goodsInfo = goodsInfo.Where(x => !goodsInfoListDbName.Contains(x.Name)).ToList();
  660. await _db.Insertable(goodsInfo).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
  661. }
  662. #endregion
  663. //添加设备商品仓位
  664. #region 添加设备商品仓位
  665. ReadExcel<DeviceGoodsPositionModel> deviceGoodsPositionModelExcel = new();
  666. var deviceGoodsPosition = deviceGoodsPositionModelExcel.ExcelToList(source, mapper, "设备物料仓位");
  667. var _deviceNames = deviceGoodsPosition.Select(x => x.DeviceName).ToList();
  668. var _goodsName = deviceGoodsPosition.Select(x => x.GoodsName).Distinct().ToList();
  669. var _deviceList = _db.Queryable<BPA_DeviceInfo>()
  670. .Where(x => _deviceNames.Contains(x.DeviceName))
  671. .ToList();
  672. var _goodsNameList = _db.Queryable<BPA_GoodsInfo>()
  673. .Where(x => _goodsName.Contains(x.Name))
  674. .ToList();
  675. var deviceGoodsPositionList = new List<BPA_DeviceGoodsPosition>();
  676. foreach (var item in deviceGoodsPosition)
  677. {
  678. var thisDevice = _deviceList.FirstOrDefault(x => x.DeviceName == item.DeviceName);
  679. var thisGoods = _goodsNameList.FirstOrDefault(x => x.Name == item.GoodsName);
  680. deviceGoodsPositionList.Add(new BPA_DeviceGoodsPosition()
  681. {
  682. DeviceId = thisDevice.Id,
  683. GoodsId = thisGoods.Id,
  684. Id = Guid.NewGuid().ToString(),
  685. Position1 = item.Position1,
  686. Position2 = item.Position2,
  687. Position3 = item.Position3,
  688. Position4 = item.Position4,
  689. });
  690. }
  691. var deviceGoodsPositionListDb = _db.Queryable<BPA_DeviceGoodsPosition>().ToList();
  692. foreach (var item in deviceGoodsPositionList)
  693. {
  694. var dGPDb = deviceGoodsPositionListDb.FirstOrDefault(x => x.DeviceId == item.DeviceId && x.GoodsId == x.GoodsId);
  695. if (dGPDb != null)
  696. {
  697. item.Id = dGPDb.Id;
  698. await _db.Updateable(item).ExecuteCommandAsync();
  699. }
  700. else
  701. {
  702. await _db.Insertable(item).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
  703. }
  704. }
  705. #endregion
  706. //添加 功能_{商品名称}
  707. var tableName = ExcelToShtteName(file.OpenReadStream(), Path.GetExtension(file.FileName));
  708. #region 添加 工艺_{商品名称}
  709. foreach (var name in tableName)
  710. {
  711. var nameList = name.Split('_');
  712. //查询设备
  713. var name1 = nameList[1];
  714. var name2 = nameList[2];
  715. var device = await _db.Queryable<BPA_DeviceInfo>().FirstAsync(x => x.DeviceName == name1 && x.IsDeleted == 0);
  716. if (device == null)
  717. {
  718. throw Oops.Oh(nameList + " 设备【" + nameList[1] + "】不存在");
  719. }
  720. ReadExcel<GoodTechnologyModel> goodTechnologyModelExcel = new();
  721. var goodTechnologyModel = goodTechnologyModelExcel.ExcelToList(source, mapper, name);
  722. var goodstechnologyactionDto = new List<GoodsTechnologyActionDto>();
  723. var cName = "";
  724. var info = new List<ActionJson>();
  725. var namestr = nameList[2];
  726. var goods = await _db.Queryable<BPA_GoodsInfo>().Where(x => x.Name == namestr).FirstAsync();
  727. var goodsId = goods == null ? "" : goods.Id;
  728. _db.Deleteable<BPA_GoodsTechnologyAction>().Where(x => x.GoodsId == goodsId).ExecuteCommand();
  729. var goodTechnologyIndex = 0;
  730. for (int i = 0; i < goodTechnologyModel.Count; i++)
  731. {
  732. var thisName = goodTechnologyModel[i].Name == null ? cName : goodTechnologyModel[i].Name;
  733. var data = await _db.Queryable<BPA_ProductFunction>()
  734. .Where(x => x.Name == thisName && x.DeviceVersionKey == device.ProductVersionId).FirstAsync();
  735. var data2 = await _db.Queryable<BPA_ProductFunctionAction>()
  736. .Where(x => x.ActionName == goodTechnologyModel[i].Configuration && x.ProductFunctionId == data.Id).FirstAsync();
  737. var batching = new BPA_Batching();
  738. var IsBatch = goodTechnologyModel[i].Name != "液体料";
  739. if (!string.IsNullOrEmpty(goodTechnologyModel[i].Name))
  740. {
  741. goodTechnologyIndex++;
  742. cName = goodTechnologyModel[i].Name;
  743. GoodsTechnologyActionDto item = new GoodsTechnologyActionDto()
  744. {
  745. ActionJson = "",
  746. ChnologyId = data?.Id,
  747. GoodsAttributeId = goodsattributevalue.Id,
  748. GoodsId = goods?.Id,
  749. IsBatch = IsBatch,
  750. IsDeleted = 0,
  751. Sort = goodTechnologyIndex,
  752. DeviceId = device?.Id,
  753. StepName = goodTechnologyModel[i].Name,
  754. Index = goodTechnologyIndex.ToString(),
  755. };
  756. info.Add(new ActionJson
  757. {
  758. chnologyId = data?.Id,
  759. actionName = goodTechnologyModel[i].Configuration,
  760. actionValue = goodTechnologyModel[i].Value,
  761. technologyactionId = !IsBatch ? batching.Id : data2?.Id,
  762. index = goodTechnologyIndex.ToString(),
  763. });
  764. goodstechnologyactionDto.Add(item);
  765. }
  766. else
  767. {
  768. info.Add(new ActionJson
  769. {
  770. chnologyId = data?.Id,
  771. actionName = goodTechnologyModel[i].Configuration,
  772. actionValue = goodTechnologyModel[i].Value,
  773. technologyactionId = !IsBatch ? batching.Id : data2?.Id,
  774. index = goodTechnologyIndex.ToString(),
  775. }); ;
  776. }
  777. }
  778. foreach (var thisItem in goodstechnologyactionDto)
  779. {
  780. var json = info.Where(x => x.chnologyId == thisItem.ChnologyId && x.index == thisItem.Index).ToList();
  781. if (thisItem.StepName == "液体料")
  782. {
  783. foreach (var item in json)
  784. {
  785. var batching = await _db.Queryable<BPA_Batching>()
  786. .FirstAsync(x => x.Batching_Name == item.actionName);
  787. item.technologyactionId = batching?.Id;
  788. }
  789. }
  790. if (thisItem.StepName == "主料")
  791. {
  792. var v1 = json.FirstOrDefault(x => x.actionName == "主料名称");
  793. var v2 = deviceGoodsPosition.FirstOrDefault(x => x.GoodsName == name2 && x.DeviceName == name1);
  794. var jsondb = await _db.Queryable<BPA_ProductFunctionAction>()
  795. .Where(x => x.ProductFunctionId == thisItem.ChnologyId)
  796. .ToListAsync();
  797. foreach (var item in from item in jsondb let insertableJsondb = json.FirstOrDefault(x => x.technologyactionId == item.Id) where insertableJsondb == null select item)
  798. {
  799. json.Add(new ActionJson()
  800. {
  801. actionName = item.ActionName,
  802. actionValue = item.ActionName == "主料重量" ? "0" : item.ActionValue,
  803. chnologyId = item.ProductFunctionId,
  804. index = thisItem.Index,
  805. technologyactionId = item.Id
  806. });
  807. }
  808. foreach (var thisitem2 in json)
  809. {
  810. if (thisitem2.actionName == "主料位置")
  811. {
  812. if (v2 == null)
  813. {
  814. throw Oops.Oh(v1.actionValue + "物料没有确定位置");
  815. }
  816. thisitem2.actionValue = GetPositionMaterial(v2, v1.actionValue);
  817. if (string.IsNullOrEmpty(thisitem2.actionValue))
  818. {
  819. throw Oops.Oh(v1.actionValue + "物料没有确定位置");
  820. }
  821. }
  822. }
  823. }
  824. thisItem.ActionJson = JsonConvert.SerializeObject(json);
  825. }
  826. var insertableDta = goodstechnologyactionDto.Adapt<List<BPA_GoodsTechnologyAction>>();
  827. await _db.Insertable(insertableDta).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
  828. }
  829. #endregion
  830. _db.Ado.CommitTran();
  831. return true;
  832. }
  833. catch (Exception e)
  834. {
  835. _db.Ado.RollbackTran();
  836. throw Oops.Oh("导入失败,失败信息:" + e.Message);
  837. }
  838. }
  839. /// <summary>
  840. /// 获取 物料仓位
  841. /// </summary>
  842. /// <returns></returns>
  843. private string GetPositionMaterial(DeviceGoodsPositionModel item, string goodsName)
  844. {
  845. var properties = item.GetType().GetProperties();
  846. foreach (var item2 in properties)
  847. {
  848. var value = item.GetType().GetProperty(item2.Name)?.GetValue(item);
  849. if (value == null)
  850. {
  851. value = "";
  852. }
  853. if (value.ToString().Trim() == goodsName.Trim())
  854. {
  855. if (item2.IsDefined(typeof(ColumnAttribute), false))
  856. {
  857. ColumnAttribute attribute = (ColumnAttribute)item2.GetCustomAttribute(typeof(ColumnAttribute), false);
  858. return attribute.Name;
  859. }
  860. }
  861. }
  862. return "";
  863. }
  864. /// <summary>
  865. /// 导出 设备工艺流程
  866. /// </summary>
  867. /// <returns></returns>
  868. public async Task<string> TechnologyTemplateExport(string deviceId)
  869. {
  870. var result = "";
  871. //查询设备
  872. var device = await _db.Queryable<BPA_DeviceInfo>().FirstAsync(x => x.Id == deviceId);
  873. //设备类型
  874. var dictData = await _db.Queryable<BPA_ProductVesion>().FirstAsync(x => x.Id == device.ProductVersionId);
  875. return dictData?.TemplatePath ?? "";
  876. }
  877. /// <summary>
  878. /// 设备 版本 工序模型导入
  879. /// </summary>
  880. /// <returns></returns>
  881. public async Task<bool> DeviceVersionTemplateImport(DeviceVersionTemplateImportInputDto inputDto)
  882. {
  883. var file = inputDto.file;
  884. try
  885. {
  886. _db.Ado.BeginTran();
  887. if (inputDto.IsAddGoodsTemplate)
  888. {
  889. var path = await _SystemConfigService.GetCosImgesURL(file);
  890. await _db.Updateable<BPA_ProductVesion>()
  891. .SetColumns(it => it.TemplatePath == path)
  892. .Where(it => it.Id == inputDto.Id)
  893. .ExecuteCommandAsync();
  894. }
  895. else
  896. {
  897. var source = file.OpenReadStream();
  898. var mapper = new Mapper(source);
  899. var deviceVersion = await _db.Queryable<BPA_ProductVesion>().FirstAsync(x => x.ProductId == inputDto.DeviceClientType && x.Vesion == inputDto.Version);
  900. //添加 设备_烹饪工序模型
  901. #region 添加 设备_烹饪工序模型
  902. ReadExcel<GoodstechnologyModel> readGoodstechnologyExcel = new();
  903. var GoodstechnologyModellist = readGoodstechnologyExcel.ExcelToList(source, mapper);
  904. List<BPA_ProductFunction> GoodsTechnologyList = new();
  905. List<BPA_ProductFunctionAction> GoodsTechnologyActionList = new();
  906. var GoodsTechnologyListDB = await _db.Queryable<BPA_ProductFunction>()
  907. .Where(x => x.DeviceVersionKey == deviceVersion.Id).ToListAsync();
  908. string currennaid = "";
  909. string currennaname = "";
  910. for (int i = 0; i < GoodstechnologyModellist.Count; i++)
  911. {
  912. var goodsTechnologyId = GoodsTechnologyListDB.FirstOrDefault(x => x.Name == GoodstechnologyModellist[i].Name);
  913. if (!string.IsNullOrWhiteSpace(GoodstechnologyModellist[i].Name))
  914. {
  915. BPA_ProductFunction item = new BPA_ProductFunction()
  916. {
  917. Id = goodsTechnologyId == null ? Guid.NewGuid().ToString() : goodsTechnologyId.Id,
  918. Name = GoodstechnologyModellist[i].Name,
  919. Status = 0,
  920. IsDeleted = 0,
  921. DeviceVersionKey = deviceVersion.Id
  922. };
  923. GoodsTechnologyList.Add(item);
  924. currennaid = item.Id;
  925. currennaname = item.Name;
  926. }
  927. var actvalueary = GoodstechnologyModellist[i].ActionValue?.Split('、');
  928. if (string.IsNullOrEmpty(GoodstechnologyModellist[i].ActionType) && currennaname != "液体料")
  929. {
  930. throw Oops.Oh($"类型错误");
  931. }
  932. BPA_ProductFunctionAction technologyAction = new()
  933. {
  934. Id = Guid.NewGuid().ToString(),
  935. ProductFunctionId = currennaid,
  936. ActionName = GoodstechnologyModellist[i].ActionName,
  937. ActionType = CharacterConversion(GoodstechnologyModellist[i].ActionType),
  938. Sort = i,
  939. CreateAt = DateTime.Now,
  940. //ActionValue = GoodstechnologyModellist[i].ActionValue,
  941. };
  942. List<ActionValueModel> ActionValueModelList = new();
  943. if (actvalueary != null)
  944. {
  945. foreach (var item in actvalueary)
  946. {
  947. ActionValueModelList.Add(new ActionValueModel() { actionValueName = item });
  948. }
  949. technologyAction.ActionValue = JsonConvert.SerializeObject(ActionValueModelList);
  950. }
  951. GoodsTechnologyActionList.Add(technologyAction);
  952. }
  953. //修改添加 主表
  954. foreach (var item in GoodsTechnologyList)
  955. {
  956. var thisitem = GoodsTechnologyListDB.FirstOrDefault(x => x.Name == item.Name);
  957. if (thisitem != null)
  958. {
  959. item.Id = thisitem.Id;
  960. _db.Updateable(item).ExecuteCommand();
  961. }
  962. else
  963. {
  964. await _db.Insertable(item).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
  965. }
  966. }
  967. //修改添从表
  968. GoodsTechnologyActionList = GoodsTechnologyActionList.Where(x => !string.IsNullOrEmpty(x.ActionName)).ToList();
  969. var goodstechnologyIds = GoodsTechnologyList.Select(x => x.Id).ToList();
  970. var GoodsTechnologyActionListDb = await _db.Queryable<BPA_ProductFunctionAction>()
  971. .Where(x => goodstechnologyIds.Contains(x.ProductFunctionId)).ToListAsync();
  972. foreach (var item in GoodsTechnologyActionList)
  973. {
  974. var thisitem = GoodsTechnologyActionListDb.FirstOrDefault(x => item.ProductFunctionId == x.ProductFunctionId && item.ActionName == x.ActionName);
  975. if (thisitem != null)
  976. {
  977. item.Id = thisitem.Id;
  978. _db.Updateable(item).ExecuteCommand();
  979. }
  980. else
  981. {
  982. await _db.Insertable(item).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
  983. }
  984. }
  985. #endregion
  986. }
  987. _db.Ado.CommitTran();
  988. }
  989. catch (Exception e)
  990. {
  991. _db.Ado.RollbackTran();
  992. throw Oops.Oh($"Excel导入错误," + e.Message);
  993. }
  994. return true;
  995. }
  996. public string GetValueStr(string str)
  997. {
  998. try
  999. {
  1000. var obj = JsonConvert.DeserializeObject<List<ActionValueJsonDto>>(str);
  1001. var result = String.Join(",", obj.Select(x => x.ActionValueName).ToArray());
  1002. return result;
  1003. }
  1004. catch (Exception e)
  1005. {
  1006. return "";
  1007. }
  1008. }
  1009. public string CharacterConversion(string str)
  1010. {
  1011. switch (str)
  1012. {
  1013. case "下拉框":
  1014. return "select";
  1015. case "数字输入框":
  1016. return "digit";
  1017. case "文本框":
  1018. return "text";
  1019. case "开关":
  1020. return "switch";
  1021. case "文字域":
  1022. return "textarea";
  1023. default:
  1024. break;
  1025. }
  1026. return "";
  1027. }
  1028. /// <summary>
  1029. /// 设置excel的下拉框
  1030. /// </summary>
  1031. /// <param name="sheet"></param>
  1032. /// <param name="col"></param>
  1033. /// <param name="selectData"></param>
  1034. private void SetExcelSelect(ISheet sheet, List<string> selectData, int firstRow, int lastRow, int firstCol, int lastCol)
  1035. {
  1036. var count = selectData.Sum(item => item.Count());
  1037. if (count > 180)
  1038. {
  1039. return;
  1040. }
  1041. //设置生成下拉框的行和列
  1042. var cellRegions = new CellRangeAddressList(1, 65535, firstCol, lastCol);
  1043. //设置 下拉框内容
  1044. DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(selectData.ToArray());
  1045. //绑定下拉框和作用区域,并设置错误提示信息
  1046. HSSFDataValidation dataValidate = new HSSFDataValidation(cellRegions, constraint);
  1047. dataValidate.CreateErrorBox("输入不合法", "请输入或选择下拉列表中的值。");
  1048. dataValidate.ShowPromptBox = true;
  1049. sheet.AddValidationData(dataValidate);
  1050. }
  1051. /// <summary>
  1052. /// 将 Stream 写入文件
  1053. /// </summary>
  1054. private void StreamToFile(byte[] bytes, string filepath)
  1055. {
  1056. // 把 byte[] 写入文件
  1057. FileStream fs = new FileStream(filepath, FileMode.Create);
  1058. BinaryWriter bw = new BinaryWriter(fs);
  1059. bw.Write(bytes);
  1060. bw.Close();
  1061. fs.Close();
  1062. }
  1063. /// <summary>
  1064. /// 获取 shtte name
  1065. /// </summary>
  1066. /// <param name="stream"></param>
  1067. /// <param name="fileType"></param>
  1068. /// <param name="strMsg"></param>
  1069. /// <param name="sheetName"></param>
  1070. /// <returns></returns>
  1071. private List<string> ExcelToShtteName(Stream stream, string fileType, bool isGY = true)
  1072. {
  1073. var result = new List<string>();
  1074. ISheet sheet = null;
  1075. IWorkbook workbook = null;
  1076. var shellCount = 0;
  1077. try
  1078. {
  1079. #region 判断excel版本
  1080. //2007以上版本excel
  1081. if (fileType == ".xlsx")
  1082. {
  1083. workbook = new XSSFWorkbook(stream);
  1084. shellCount = ((XSSFWorkbook)workbook).Count;
  1085. }
  1086. //2007以下版本excel
  1087. else if (fileType == ".xls")
  1088. {
  1089. workbook = new HSSFWorkbook(stream);
  1090. shellCount = ((HSSFWorkbook)workbook).Count;
  1091. }
  1092. else
  1093. {
  1094. throw Oops.Oh($"传入的不是Excel文件");
  1095. }
  1096. #endregion
  1097. for (int sheetI = 0; sheetI < shellCount; sheetI++)
  1098. {
  1099. sheet = workbook.GetSheetAt(sheetI);
  1100. if (isGY)
  1101. {
  1102. if (sheet.SheetName.Contains("工艺"))
  1103. {
  1104. result.Add(sheet.SheetName);
  1105. }
  1106. }
  1107. else
  1108. {
  1109. result.Add(sheet.SheetName);
  1110. }
  1111. }
  1112. }
  1113. catch (Exception ex)
  1114. {
  1115. throw Oops.Oh($"Excel操作错误" + ex.Message);
  1116. }
  1117. return result;
  1118. }
  1119. /// <summary>
  1120. /// 将Excel单表转为Datatable
  1121. /// </summary>
  1122. /// <param name="stream"></param>
  1123. /// <param name="fileType"></param>
  1124. /// <param name="strMsg"></param>
  1125. /// <param name="sheetName"></param>
  1126. /// <returns></returns>
  1127. public async Task<List<ExcelDtoImagDto>> ExcelToDatatable(Stream stream, string fileType, string sheetName = null)
  1128. {
  1129. var result = new List<ExcelDtoImagDto>();
  1130. ISheet sheet = null;
  1131. IWorkbook workbook = null;
  1132. try
  1133. {
  1134. #region 判断excel版本
  1135. //2007以上版本excel
  1136. if (fileType == ".xlsx")
  1137. {
  1138. workbook = new XSSFWorkbook(stream);
  1139. }
  1140. //2007以下版本excel
  1141. else if (fileType == ".xls")
  1142. {
  1143. workbook = new HSSFWorkbook(stream);
  1144. }
  1145. else
  1146. {
  1147. throw new Exception("传入的不是Excel文件!");
  1148. }
  1149. #endregion
  1150. Console.WriteLine("已确定解析格式,开始解析");
  1151. if (workbook == null)
  1152. {
  1153. Console.WriteLine("已确定解析格式,工具");
  1154. }
  1155. IList pictures = workbook.GetAllPictures();
  1156. Console.WriteLine("已确定解析格式,成功解析" + JsonConvert.SerializeObject(pictures));
  1157. int i = 1;
  1158. foreach (XSSFPictureData pic in pictures)
  1159. {
  1160. Console.WriteLine("讲数据流转化为图片");
  1161. Image jpg1 = Image.FromStream(new MemoryStream(pic.Data));//从pic.Data数据流创建图片
  1162. Console.WriteLine("转化成功");
  1163. var imagePath = await GetCosImgesURL(PhotoImageInsert(jpg1));
  1164. Console.WriteLine("图片路径" + imagePath);
  1165. result.Add(new ExcelDtoImagDto()
  1166. {
  1167. ImgesPath = imagePath,
  1168. Index = i
  1169. });
  1170. i++;
  1171. }
  1172. }
  1173. catch (Exception ex)
  1174. {
  1175. throw new Exception(ex.Message);
  1176. }
  1177. return result;
  1178. }
  1179. //将Image转换成流数据,并保存为byte[]
  1180. public byte[] PhotoImageInsert(Image imgPhoto)
  1181. {
  1182. MemoryStream mstream = new MemoryStream();
  1183. imgPhoto.Save(mstream, ImageFormat.Bmp);
  1184. byte[] byData = new Byte[mstream.Length];
  1185. mstream.Position = 0;
  1186. mstream.Read(byData, 0, byData.Length); mstream.Close();
  1187. return byData;
  1188. }
  1189. public async Task<string> GetCosImgesURL(byte[] data)
  1190. {
  1191. var result = "";
  1192. TransferUploadObjectModel m = new TransferUploadObjectModel(_db);
  1193. /// 高级接口上传对象
  1194. result = await m.TransferUploadFile(new FileInputInfoDto()
  1195. {
  1196. Directory = "goods",
  1197. FileExtension = "png",
  1198. Method = "PUT",
  1199. }, data);
  1200. return result;
  1201. }
  1202. private string GetNumber2(int Length = 10)
  1203. {
  1204. byte[] buffer = Guid.NewGuid().ToByteArray();
  1205. var ram = BitConverter.ToInt64(buffer, 0);
  1206. var str = string.Format("{0}", ram.ToString().Substring(0, Length));
  1207. return str;
  1208. }
  1209. }
  1210. }