using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using KonSoft.Admin.Dtos; using KonSoft.Admin.Entities; using KonSoft.Admin.IApplicationServices; using Volo.Abp.Application.Services; using Volo.Abp.Domain.Repositories; namespace KonSoft.Admin.ApplicationServices; public class ServiceCategoryAppService : ApplicationService, IServiceCategoryAppService { private readonly IRepository _repository; public ServiceCategoryAppService(IRepository repository) { _repository = repository; } public async Task CreateAsync(CreateServiceCategoryDto input) { ServiceCategory parent = null; if (input.ParentId.HasValue) { parent = await _repository.GetAsync(input.ParentId.Value); } var category = new ServiceCategory(Guid.NewGuid(), input.Name); category.SetParent(parent); await _repository.InsertAsync(category); return ObjectMapper.Map(category); } public async Task DeleteAsync(Guid id) { var hasChildren = await _repository.AnyAsync(c => c.ParentId == id); if (hasChildren) { throw new InvalidOperationException("存在子节点无法删除!"); } await _repository.DeleteAsync(o => o.Id == id); } public async Task> GetTreeAsync() { var allCategories = await _repository.GetListAsync(); // 构建树 var lookup = allCategories.ToDictionary(c => c.Id, c => ObjectMapper.Map(c)); var rootList = new List(); foreach (var dto in lookup.Values) { if (dto.ParentId.HasValue && lookup.ContainsKey(dto.ParentId.Value)) { lookup[dto.ParentId.Value].Children.Add(dto); } else { rootList.Add(dto); } } return rootList.OrderBy(c => c.Name).ToList(); } }