using AutoMapper; using HardwarePerformance.Models.DTOs; using HardwarePerformance.Repositories; namespace HardwarePerformance.Services { public class ProductService : IProductService { private readonly IProductRepository _productRepository; private readonly IMapper _mapper; public ProductService(IProductRepository productRepository, IMapper mapper) { _productRepository = productRepository; _mapper = mapper; } public async Task> GetProductsByCategoryAsync(int categoryId, int page = 1, int pageSize = 20, string sortBy = "CurrentRank", string order = "asc") { var products = await _productRepository.GetByCategoryAsync(categoryId, page, pageSize, sortBy, order); var totalCount = await _productRepository.CountAsync(categoryId); var productDtos = _mapper.Map>(products); return new PagedResultDto { Items = productDtos.ToList(), Total = totalCount, CurrentPage = page, PageSize = pageSize, TotalPages = (int)Math.Ceiling((double)totalCount / pageSize) }; } public async Task GetProductByIdAsync(int id) { var product = await _productRepository.GetByIdAsync(id); if (product == null) return null; var productDto = _mapper.Map(product); // 获取类别信息 var category = await _productRepository.GetCategoryByProductIdAsync(id); if (category != null) { productDto.Category = new CategoryDto { Id = category.Id, Name = category.Name, Description = category.Description }; } return productDto; } public async Task> SearchProductsAsync(string query, int? categoryId = null, string? manufacturer = null, int? minScore = null, int? maxScore = null, int page = 1, int pageSize = 20) { var products = await _productRepository.SearchAsync(query, categoryId, manufacturer, minScore, maxScore, page, pageSize); var totalCount = await _productRepository.CountSearchResultsAsync(query, categoryId, manufacturer, minScore, maxScore); var productDtos = _mapper.Map>(products); return new PagedResultDto { Items = productDtos.ToList(), Total = totalCount, CurrentPage = page, PageSize = pageSize, TotalPages = (int)Math.Ceiling((double)totalCount / pageSize) }; } public async Task> FilterProductsAsync(int categoryId, string? manufacturer = null, int? minScore = null, int? maxScore = null, int? releaseYear = null, int page = 1, int pageSize = 20, string sortBy = "CurrentRank", string order = "asc") { var products = await _productRepository.FilterAsync(categoryId, manufacturer, minScore, maxScore, releaseYear, page, pageSize, sortBy, order); var totalCount = await _productRepository.CountFilterResultsAsync(categoryId, manufacturer, minScore, maxScore, releaseYear); var productDtos = _mapper.Map>(products); return new PagedResultDto { Items = productDtos.ToList(), Total = totalCount, CurrentPage = page, PageSize = pageSize, TotalPages = (int)Math.Ceiling((double)totalCount / pageSize) }; } } }