using AutoMapper; using ProductionLineMonitor.Core.Dtos; using ProductionLineMonitor.Core.IRepositories; using ProductionLineMonitor.Core.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProductionLineMonitor.Core.Services { public class RecipeService : IRecipeService { private readonly IUnitOfWork _unitOfWork; private readonly IMapper _mapper; public RecipeService(IUnitOfWork unitOfWork, IMapper mapper) { _unitOfWork = unitOfWork; _mapper = mapper; } public ResultDto Create(RecipeCreateOrUpdateDto input) { if (_unitOfWork.RecipeRepository.Any( x => x.ModuleType == input.ModuleType && x.ProductionLineId == input.ProductionLineId)) { return ResultDto.Fail("该机种对应线别已存在,请检查!"); } var recipe = _mapper.Map(input); recipe.CreateTime = DateTime.Now; _unitOfWork.RecipeRepository.Create(recipe); _unitOfWork.SaveChanges(); var recipeDto = _mapper.Map(recipe); return ResultDto.Success(recipeDto); } public ResultDto Delete(string id) { var recipe = _unitOfWork.RecipeRepository.GetById(id); if (recipe == null) { return ResultDto.Fail("资源不存在!"); } _unitOfWork.RecipeRepository.Delete(recipe); _unitOfWork.SaveChanges(); return ResultDto.Success(); } public ResultDto GetById(string id) { var recipe = _unitOfWork.RecipeRepository.GetById(id); if (recipe == null) { return ResultDto.Fail("资源不存在!"); } var recipeDto = _mapper.Map(recipe); var line = _unitOfWork.ProductionLineRepository.GetById(recipe.ProductionLineId); if (line != null) { recipeDto.ProductionLineName = line.Name; } return ResultDto.Success(recipeDto); } public ResultDto> GetList() { List list = new List(); var recipes = _unitOfWork.RecipeRepository.GetList(); if (recipes != null) { foreach (var recipe in recipes) { var recipeDto = _mapper.Map(recipe); var line = _unitOfWork.ProductionLineRepository.GetById(recipeDto.ProductionLineId); if (line != null) { recipeDto.ProductionLineName = line.Name; } list.Add(recipeDto); } } return ResultDto>.Success(list); } public PageDto> GetPageList(int pageIndex, int pageSize, string? keyword = null) { List recipeDtos = new List(); var recipes = _unitOfWork.RecipeRepository.GetPageList(out int total, pageIndex, pageSize, o => o.OrderByDescending(o => o.CreateTime), x => x.ModuleType.Contains(keyword)); if (recipes != null) { foreach (var recipe in recipes) { var recipeDto = _mapper.Map(recipe); var line = _unitOfWork.ProductionLineRepository.GetById(recipeDto.ProductionLineId); if (line != null) { recipeDto.ProductionLineName = line.Name; } recipeDtos.Add(recipeDto); } } return new PageDto>(total, recipeDtos); } public ResultDto Update(string id, RecipeCreateOrUpdateDto input) { var recipe = _unitOfWork.RecipeRepository.GetById(id); if (recipe == null) { return ResultDto.Fail("资源不存在!"); } _mapper.Map(input, recipe); recipe.UpdateTime = DateTime.Now; _unitOfWork.RecipeRepository.Update(recipe); _unitOfWork.SaveChanges(); return ResultDto.Success(); } } }