基础服务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.
 
 

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