Krishya | b0cc188 | 2025-06-09 10:54:09 +0800 | [diff] [blame] | 1 | package com.example.myproject.service; |
| 2 | |
| 3 | import com.example.myproject.entity.SeedRating; |
| 4 | import com.example.myproject.repository.SeedRatingRepository; |
| 5 | import org.springframework.beans.factory.annotation.Autowired; |
| 6 | import org.springframework.stereotype.Service; |
| 7 | |
| 8 | import java.util.HashMap; |
| 9 | import java.util.Map; |
| 10 | import java.util.Optional; |
| 11 | |
| 12 | @Service |
| 13 | public class SeedRatingService { |
| 14 | |
| 15 | @Autowired |
| 16 | private SeedRatingRepository seedRatingRepository; |
| 17 | |
| 18 | public Map<String, Object> rateSeed(Long userId, Long seedId, Integer score) { |
| 19 | validateScoreRange(score); |
| 20 | |
| 21 | Map<String, Object> response = new HashMap<>(); |
| 22 | |
| 23 | try { |
| 24 | Optional<SeedRating> existingRating = seedRatingRepository.findByUserIdAndSeedId(userId, seedId); |
| 25 | |
| 26 | SeedRating rating; |
| 27 | if (existingRating.isPresent()) { |
| 28 | rating = existingRating.get(); |
| 29 | rating.setScore(score); |
| 30 | response.put("message", "评分更新成功"); |
| 31 | } else { |
| 32 | rating = new SeedRating(); |
| 33 | rating.setUserId(userId); |
| 34 | rating.setSeedId(seedId); |
| 35 | rating.setScore(score); |
| 36 | response.put("message", "新评分提交成功"); |
| 37 | } |
| 38 | |
| 39 | seedRatingRepository.save(rating); |
| 40 | |
| 41 | response.put("status", "success"); |
| 42 | response.put("rating_id", rating.getRatingId()); |
| 43 | response.put("score", rating.getScore()); |
| 44 | |
| 45 | } catch (Exception e) { |
| 46 | response.put("status", "error"); |
| 47 | response.put("message", "评分失败: " + e.getMessage()); |
| 48 | } |
| 49 | |
| 50 | return response; |
| 51 | } |
| 52 | |
| 53 | private void validateScoreRange(Integer score) { |
| 54 | if (score == null || score < 0 || score > 10) { |
| 55 | throw new IllegalArgumentException("评分必须在0-10之间"); |
| 56 | } |
| 57 | } |
| 58 | } |