| package com.example.myproject.service; |
| |
| import com.example.myproject.entity.SeedRating; |
| import com.example.myproject.repository.SeedRatingRepository; |
| import org.springframework.beans.factory.annotation.Autowired; |
| import org.springframework.stereotype.Service; |
| |
| import java.util.HashMap; |
| import java.util.Map; |
| import java.util.Optional; |
| |
| @Service |
| public class SeedRatingService { |
| |
| @Autowired |
| private SeedRatingRepository seedRatingRepository; |
| |
| public Map<String, Object> rateSeed(Long userId, Long seedId, Integer score) { |
| validateScoreRange(score); |
| |
| Map<String, Object> response = new HashMap<>(); |
| |
| try { |
| Optional<SeedRating> existingRating = seedRatingRepository.findByUserIdAndSeedId(userId, seedId); |
| |
| SeedRating rating; |
| if (existingRating.isPresent()) { |
| rating = existingRating.get(); |
| rating.setScore(score); |
| response.put("message", "评分更新成功"); |
| } else { |
| rating = new SeedRating(); |
| rating.setUserId(userId); |
| rating.setSeedId(seedId); |
| rating.setScore(score); |
| response.put("message", "新评分提交成功"); |
| } |
| |
| seedRatingRepository.save(rating); |
| |
| response.put("status", "success"); |
| response.put("rating_id", rating.getRatingId()); |
| response.put("score", rating.getScore()); |
| |
| } catch (Exception e) { |
| response.put("status", "error"); |
| response.put("message", "评分失败: " + e.getMessage()); |
| } |
| |
| return response; |
| } |
| |
| private void validateScoreRange(Integer score) { |
| if (score == null || score < 0 || score > 10) { |
| throw new IllegalArgumentException("评分必须在0-10之间"); |
| } |
| } |
| } |