using MES.Service.DB; using MES.Service.Dto.webApi; using MES.Service.Modes; namespace MES.Service.service.BasicData; public class MesItemTypeManager : Repository { //当前类已经继承了 Repository 增、删、查、改的方法 public bool Save(ErpItemType customer) { var entity = GetMesItemType(customer); try { switch (customer.Type) { case "0": return InsertItemType(entity); case "1": return DeleteItemType(entity.Id); default: throw new ArgumentNullException( $"type没有{customer.Type}这个类型的参数"); } } catch (Exception ex) { throw new ApplicationException($"操作失败: {ex.Message}", ex); } } private bool InsertItemType(MesItemType entity) { // 先根据ID删除现有记录 try { Db.Deleteable() .Where(it => it.Id == entity.Id).ExecuteCommand(); } catch (Exception) { // 删除失败可能是因为记录不存在,继续执行插入操作 } var insert = base.Insert(entity); if (insert) return true; throw new NotImplementedException("插入失败"); } private bool DeleteItemType(long? id) { var deleteById = Db.Deleteable() .Where(it => it.Id == id).ExecuteCommand(); if (deleteById > 0) return true; throw new NotImplementedException("删除失败"); } private MesItemType GetMesItemType(ErpItemType department) { var entity = new MesItemType { Id = string.IsNullOrEmpty(department.Id) ? DateTimeOffset.UtcNow.ToUnixTimeSeconds() : long.Parse(department.Id), Pgroup = department.FParentId, Tcode = department.FNumber, Tname = department.FName, Description = department.FDescription, CreateDate = DateTime.Now, LastupdateDate = DateTime.Now, Company = "1000", Factory = "1000" }; var mesItemType = Db.Queryable() .Where(it => it.Tcode == entity.Tcode) .First(); if (mesItemType != null) { entity.Id = mesItemType.Id; } return entity; } public bool SaveList(List departments) { var list = new List(); departments.ForEach(s => { var entity = GetMesItemType(s); entity.Type = s.Type; list.Add(entity); }); var groupBy = list.GroupBy(s => s.Type) .ToDictionary(g => g.Key, g => g.ToList()); var result = new List(); foreach (var itemTypeGroup in groupBy) try { switch (itemTypeGroup.Key) { case "0": result.Add(InsertItemTypeBatch(itemTypeGroup.Value)); break; case "1": result.Add(DeleteItemTypeBatch(itemTypeGroup.Value)); break; default: throw new ArgumentNullException( $"type没有{itemTypeGroup.Key}这个类型的参数"); } } catch (Exception ex) { throw new ApplicationException($"批量操作失败: {ex.Message}", ex); } if (result.All(b => b)) return true; throw new NotImplementedException("接口执行失败"); } private bool InsertItemTypeBatch(List itemTypeList) { var insertRange = base.InsertRange(itemTypeList); if (insertRange) return true; throw new NotImplementedException("插入失败"); } private bool DeleteItemTypeBatch(List itemTypeList) { var ids = itemTypeList.Select(it => it.Id).ToArray(); var deleteByIds = Db.Deleteable() .Where(s => ids.Contains(s.Id)).ExecuteCommand(); if (deleteByIds > 0) return true; throw new NotImplementedException("删除失败"); } }