lrj
14 小时以前 f04f35b562760afbac0c477357e2a29f77aec3b9
backend/src/main/java/com/rongyichuang/player/service/ActivityPlayerRatingService.java
@@ -7,6 +7,7 @@
import com.rongyichuang.common.util.UserContextUtil;
import com.rongyichuang.judge.entity.Judge;
import com.rongyichuang.judge.repository.JudgeRepository;
import com.rongyichuang.activity.repository.ActivityJudgeRepository;
import com.rongyichuang.player.dto.input.ActivityPlayerRatingInput;
import com.rongyichuang.player.dto.input.ActivityPlayerRatingItemInput;
import com.rongyichuang.player.dto.response.JudgeRatingStatusResponse;
@@ -50,6 +51,9 @@
    @Autowired
    private UserContextUtil userContextUtil;
    @Autowired
    private ActivityJudgeRepository activityJudgeRepository;
    @Transactional
    public boolean saveRating(ActivityPlayerRatingInput input) {
        try {
@@ -62,22 +66,37 @@
            }
            
            Long activityPlayerId = input.getActivityPlayerId();
            Long stageId = input.getStageId();
            // 验证前端传递的stageId
            if (stageId == null) {
                throw new RuntimeException("stageId不能为空");
            }
            
            // 查询 activity_id, player_id
            String queryPlayerSql = "SELECT activity_id, player_id FROM t_activity_player WHERE id = ?";
            Map<String, Object> playerData = jdbcTemplate.queryForMap(queryPlayerSql, activityPlayerId);
            Long activityId = (Long) playerData.get("activity_id");
            Long playerId = (Long) playerData.get("player_id");
            log.info("查询到的数据 - activityId: {}, playerId: {}, judgeId: {}", activityId, playerId, currentJudgeId);
            Long activityId = ((Number) playerData.get("activity_id")).longValue();
            Long playerId = ((Number) playerData.get("player_id")).longValue();
            log.info("查询到的数据 - activityId: {}, playerId: {}, judgeId: {}, stageId: {}", activityId, playerId, currentJudgeId, stageId);
            
            // 验证评委是否有权限评分此活动
            // 验证评委是否有权限评分此活动和阶段
            if (!userContextUtil.isCurrentUserJudgeForActivity(activityId)) {
                throw new RuntimeException("当前评委无权限评分此活动");
            }
            
            // 验证评委是否有权限评分此阶段
            String verifyJudgeStageIdSql = "SELECT COUNT(*) FROM t_activity_judge WHERE activity_id = ? AND judge_id = ? AND stage_id = ?";
            Number judgeStageCountNumber = jdbcTemplate.queryForObject(verifyJudgeStageIdSql, Number.class, activityId, currentJudgeId, stageId);
            Integer judgeStageCount = judgeStageCountNumber != null ? judgeStageCountNumber.intValue() : 0;
            if (judgeStageCount == null || judgeStageCount == 0) {
                throw new RuntimeException("当前评委无权限评分此阶段,stageId: " + stageId);
            }
            // 查询活动的评分模板ID
            String queryActivitySql = "SELECT rating_scheme_id FROM t_activity WHERE id = ?";
            Long ratingSchemeId = jdbcTemplate.queryForObject(queryActivitySql, Long.class, activityId);
            Number ratingSchemeIdNumber = jdbcTemplate.queryForObject(queryActivitySql, Number.class, activityId);
            Long ratingSchemeId = ratingSchemeIdNumber != null ? ratingSchemeIdNumber.longValue() : null;
            log.info("查询到的ratingSchemeId: {}", ratingSchemeId);
            
            if (ratingSchemeId == null) {
@@ -95,10 +114,10 @@
                // 删除已有的评分项
                activityPlayerRatingItemRepository.deleteByActivityPlayerRatingId(rating.getId());
            } else {
                // 创建新的评分记录,暂时使用1作为stageId的默认值
                rating = new ActivityPlayerRating(activityId, activityPlayerId, 1L, playerId, currentJudgeId, ratingSchemeId);
                // 创建新的评分记录,使用前端传递的stageId
                rating = new ActivityPlayerRating(activityId, activityPlayerId, stageId, playerId, currentJudgeId, ratingSchemeId);
                rating = activityPlayerRatingRepository.save(rating);
                log.info("创建新的评分记录,ID: {}", rating.getId());
                log.info("创建新的评分记录,ID: {}, stageId: {}", rating.getId(), stageId);
            }
            
            // 保存评分项
@@ -121,7 +140,7 @@
                        activityId,
                        activityPlayerId,
                        rating.getId(),
                        1L, // stageId,暂时使用1
                        stageId, // 使用前端传递的stageId
                        playerId,
                        currentJudgeId,
                        ratingSchemeId,
@@ -238,51 +257,85 @@
     * 获取指定选手的所有评委评分状态
     */
    public List<JudgeRatingStatusResponse> getAllJudgeRatingsForPlayer(Long activityPlayerId) {
        // 首先获取活动ID
        String activitySql = "SELECT activity_id FROM t_activity_player WHERE id = ?";
        Long activityId = jdbcTemplate.queryForObject(activitySql, Long.class, activityPlayerId);
        log.info("开始获取选手评委评分状态,activityPlayerId: {}", activityPlayerId);
        
        if (activityId == null) {
        // 首先获取活动ID和阶段ID
        String activityPlayerSql = "SELECT activity_id, stage_id FROM t_activity_player WHERE id = ?";
        Map<String, Object> activityPlayerData = jdbcTemplate.queryForMap(activityPlayerSql, activityPlayerId);
        if (activityPlayerData == null) {
            throw new RuntimeException("未找到活动选手记录,activityPlayerId: " + activityPlayerId);
        }
        
        // 获取活动的所有评委
        Long activityId = ((Number) activityPlayerData.get("activity_id")).longValue();
        Long stageId = ((Number) activityPlayerData.get("stage_id")).longValue();
        log.info("找到活动ID: {}, 阶段ID: {}", activityId, stageId);
        // 获取指定阶段的评委(通过stageId过滤,确保唯一性)
        String judgesSql = "SELECT j.id, j.name FROM t_judge j " +
                          "JOIN t_activity_judge aj ON j.id = aj.judge_id " +
                          "WHERE aj.activity_id = ? ORDER BY j.name";
                          "WHERE aj.activity_id = ? AND aj.stage_id = ? ORDER BY j.name";
        
        List<Map<String, Object>> judgeRows = jdbcTemplate.queryForList(judgesSql, activityId);
        List<Map<String, Object>> judgeRows = jdbcTemplate.queryForList(judgesSql, activityId, stageId);
        log.info("找到评委数量: {}", judgeRows.size());
        
        Long currentJudgeId = userContextUtil.getCurrentJudgeId();
        
        return judgeRows.stream().map(row -> {
        List<JudgeRatingStatusResponse> result = judgeRows.stream().map(row -> {
            Long judgeId = ((Number) row.get("id")).longValue();
            String judgeName = (String) row.get("name");
            
            // 查找该评委的评分记录数量(从t_activity_player_rating表按activity_player_id和judge_id查询)
            String ratingCountSql = "SELECT COUNT(*) FROM t_activity_player_rating WHERE activity_player_id = ? AND judge_id = ?";
            // 只查找有效的评分记录(state=1),避免重复计算
            String ratingCountSql = "SELECT COUNT(*) FROM t_activity_player_rating WHERE activity_player_id = ? AND judge_id = ? AND state = 1";
            Integer ratingCount = jdbcTemplate.queryForObject(ratingCountSql, Integer.class, activityPlayerId, judgeId);
            
            Boolean hasRated = ratingCount != null && ratingCount > 0; // 评审次数>0表示已评审
            String ratingTime = null;
            BigDecimal totalScore = null;
            
            // 如果已评分,获取最新的评分记录
            // 如果已评分,获取最新的有效评分记录
            if (hasRated) {
                Optional<ActivityPlayerRating> ratingOpt = activityPlayerRatingRepository
                        .findByActivityPlayerIdAndJudgeId(activityPlayerId, judgeId);
                // 获取最新的有效评分记录(按更新时间倒序,取第一条)
                String latestRatingSql = "SELECT * FROM t_activity_player_rating " +
                                       "WHERE activity_player_id = ? AND judge_id = ? AND state = 1 " +
                                       "ORDER BY update_time DESC LIMIT 1";
                
                if (ratingOpt.isPresent()) {
                    ActivityPlayerRating rating = ratingOpt.get();
                    totalScore = rating.getTotalScore();
                    if (rating.getUpdateTime() != null) {
                        ratingTime = rating.getUpdateTime().toString();
                try {
                    Map<String, Object> ratingRow = jdbcTemplate.queryForMap(latestRatingSql, activityPlayerId, judgeId);
                    if (ratingRow != null) {
                        totalScore = (BigDecimal) ratingRow.get("total_score");
                        Object updateTimeObj = ratingRow.get("update_time");
                        if (updateTimeObj != null) {
                            ratingTime = updateTimeObj.toString();
                        }
                    }
                } catch (Exception e) {
                    // 如果查询失败,使用repository方法作为备选
                    Optional<ActivityPlayerRating> ratingOpt = activityPlayerRatingRepository
                            .findByActivityPlayerIdAndJudgeId(activityPlayerId, judgeId);
                    if (ratingOpt.isPresent()) {
                        ActivityPlayerRating rating = ratingOpt.get();
                        // 只有当记录状态为1时才使用
                        if (rating.getState() != null && rating.getState() == 1) {
                            totalScore = rating.getTotalScore();
                            if (rating.getUpdateTime() != null) {
                                ratingTime = rating.getUpdateTime().toString();
                            }
                        }
                    }
                }
            }
            
            return new JudgeRatingStatusResponse(judgeId, judgeName, hasRated, ratingTime, totalScore);
            JudgeRatingStatusResponse response = new JudgeRatingStatusResponse(judgeId, judgeName, hasRated, ratingTime, totalScore);
            log.info("评委 {} (ID: {}) 评分状态: hasRated={}, totalScore={}, ratingTime={}",
                    judgeName, judgeId, hasRated, totalScore, ratingTime);
            return response;
        }).collect(java.util.stream.Collectors.toList());
        log.info("返回评委评分状态列表,总数: {}", result.size());
        return result;
    }
    /**
@@ -298,8 +351,68 @@
        return new CurrentJudgeInfoResponse(
                currentJudge.getId(),
                currentJudge.getName(),
                currentJudge.getPhone(),
                currentJudge.getDescription()
                currentJudge.getTitle(),
                currentJudge.getCompany()
        );
    }
    /**
     * 检查评委是否在指定比赛阶段的评委列表中
     */
    public boolean isJudgeInActivity(Long stageId, Long judgeId) {
        try {
            return activityJudgeRepository.existsByStageIdAndJudgeId(stageId, judgeId);
        } catch (Exception e) {
            log.error("检查评委权限时发生异常: stageId={}, judgeId={}, error={}", stageId, judgeId, e.getMessage(), e);
            return false;
        }
    }
    /**
     * 获取指定评委对指定选手的评分明细
     */
    public CurrentJudgeRatingResponse getJudgeRatingDetail(Long activityPlayerId, Long judgeId) {
        try {
            Optional<ActivityPlayerRating> ratingOpt = activityPlayerRatingRepository
                    .findByActivityPlayerIdAndJudgeId(activityPlayerId, judgeId);
            if (!ratingOpt.isPresent()) {
                return null;
            }
            ActivityPlayerRating rating = ratingOpt.get();
            // 查询评分明细项
            String itemsSql = "SELECT ri.id as rating_item_id, ri.name as rating_item_name, " +
                             "apri.score, ri.max_score " +
                             "FROM t_activity_player_rating_item apri " +
                             "JOIN t_rating_item ri ON apri.rating_item_id = ri.id " +
                             "WHERE apri.activity_player_rating_id = ? " +
                             "ORDER BY ri.order_no";
            List<Map<String, Object>> itemRows = jdbcTemplate.queryForList(itemsSql, rating.getId());
            List<CurrentJudgeRatingResponse.CurrentJudgeRatingItemResponse> items = itemRows.stream()
                    .map(row -> new CurrentJudgeRatingResponse.CurrentJudgeRatingItemResponse(
                            ((Number) row.get("rating_item_id")).longValue(),
                            (String) row.get("rating_item_name"),
                            (BigDecimal) row.get("score"),
                            (BigDecimal) row.get("score") // weightedScore 暂时使用相同值
                    ))
                    .collect(java.util.stream.Collectors.toList());
            CurrentJudgeRatingResponse response = new CurrentJudgeRatingResponse();
            response.setId(rating.getId());
            response.setTotalScore(rating.getTotalScore());
            response.setStatus(rating.getState());
            response.setRemark(rating.getFeedback());
            response.setItems(items);
            return response;
        } catch (Exception e) {
            log.error("获取评委评分明细失败: activityPlayerId={}, judgeId={}, error={}",
                     activityPlayerId, judgeId, e.getMessage(), e);
            return null;
        }
    }
}