lrj
昨天 7ad9c3c93f0cc103347ae2e2429e0122fb512e24
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package com.rongyichuang.player.service;
 
import com.rongyichuang.activity.entity.Activity;
import com.rongyichuang.activity.entity.ActivityPlayerRating;
import com.rongyichuang.activity.repository.ActivityRepository;
import com.rongyichuang.activity.repository.ActivityPlayerRatingRepository;
import com.rongyichuang.common.entity.Media;
import com.rongyichuang.common.repository.MediaRepository;
import com.rongyichuang.message.service.MessageService;
import com.rongyichuang.player.dto.*;
import com.rongyichuang.player.entity.ActivityPlayer;
import com.rongyichuang.player.repository.ActivityPlayerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
/**
 * 比赛晋级服务类
 */
@Service
public class PromotionService {
    
    @Autowired
    private ActivityRepository activityRepository;
    
    @Autowired
    private ActivityPlayerRepository activityPlayerRepository;
    
    @Autowired
    private ActivityPlayerRatingRepository activityPlayerRatingRepository;
    
    @Autowired
    private MediaRepository mediaRepository;
    
    @Autowired
    private MessageService messageService;
    
    /**
     * 获取比赛晋级列表
     */
    public List<PromotionCompetitionResponse> getPromotionCompetitions(String name, Integer page, Integer size) {
        List<PromotionCompetitionResponse> result = new ArrayList<>();
        
        // 查询所有有效的主比赛(pid = 0)
        List<Activity> competitions = activityRepository.findByPidAndStateOrderByCreateTimeAsc(0L, 1);
        
        // 如果有名称过滤条件,进行过滤
        if (name != null && !name.trim().isEmpty()) {
            competitions = competitions.stream()
                .filter(comp -> comp.getName().contains(name.trim()))
                .collect(Collectors.toList());
        }
        
        // 为每个比赛查询其阶段
        for (Activity competition : competitions) {
            List<Activity> stages = activityRepository.findByPidAndStateOrderByCreateTimeAsc(competition.getId(), 1);
            
            for (Activity stage : stages) {
                // 统计当前阶段的参赛人数
                Long playerCountLong = activityPlayerRepository.countByStageIdAndState(stage.getId(), 1);
                Integer currentCount = playerCountLong != null ? playerCountLong.intValue() : 0;
                
                PromotionCompetitionResponse response = new PromotionCompetitionResponse(competition, stage, currentCount);
                result.add(response);
            }
        }
        
        // 简单分页处理(实际项目中建议使用数据库分页)
        if (page != null && size != null && page > 0 && size > 0) {
            int start = (page - 1) * size;
            int end = Math.min(start + size, result.size());
            if (start < result.size()) {
                result = result.subList(start, end);
            } else {
                result = new ArrayList<>();
            }
        }
        
        return result;
    }
    
    /**
     * 获取比赛参赛人员
     */
    public List<CompetitionParticipantResponse> getCompetitionParticipants(Long competitionId, Integer page, Integer size) {
        // 查询指定阶段的所有参赛者(已审核通过的)
        List<ActivityPlayer> participants = activityPlayerRepository.findByStageIdAndStateWithPlayerOrderByCreateTimeDesc(competitionId, 1);
        
        // 转换为响应对象
        List<CompetitionParticipantResponse> result = participants.stream()
            .map(participant -> {
                // 这里可以添加评分次数的统计逻辑
                Integer ratingCount = 0; // TODO: 从评分表中统计
                return new CompetitionParticipantResponse(participant, ratingCount);
            })
            .collect(Collectors.toList());
        
        // 简单分页处理
        if (page != null && size != null && page > 0 && size > 0) {
            int start = (page - 1) * size;
            int end = Math.min(start + size, result.size());
            if (start < result.size()) {
                result = result.subList(start, end);
            } else {
                result = new ArrayList<>();
            }
        }
        
        return result;
    }
    
    /**
     * 获取可晋级的参赛者列表
     */
    public PromotableParticipantsResponse getPromotableParticipants(Long currentStageId) {
        try {
            // 查询当前阶段信息
            Activity currentStage = activityRepository.findById(currentStageId).orElse(null);
            if (currentStage == null) {
                return new PromotableParticipantsResponse(new ArrayList<>(), 0, 0, "", "");
            }
            
            // 查找上一个阶段
            Activity previousStage = findPreviousStage(currentStage);
            if (previousStage == null) {
                return new PromotableParticipantsResponse(new ArrayList<>(), 0, 0, "", currentStage.getName());
            }
            
            // 查询上一阶段的所有有效参赛者
            List<ActivityPlayer> previousParticipants = activityPlayerRepository
                .findByStageIdAndStateWithPlayerOrderByCreateTimeDesc(previousStage.getId(), 1);
            
            // 查询当前阶段已有的参赛者ID列表
            List<ActivityPlayer> currentParticipants = activityPlayerRepository
                .findByStageIdAndStateWithPlayerOrderByCreateTimeDesc(currentStageId, 1);
            List<Long> currentPlayerIds = currentParticipants.stream()
                .map(ActivityPlayer::getPlayerId)
                .collect(Collectors.toList());
            
            // 过滤掉已经在当前阶段的参赛者,并计算平均分
            List<PromotableParticipantResponse> promotableList = new ArrayList<>();
            
            for (ActivityPlayer participant : previousParticipants) {
                // 排除已经在当前阶段的参赛者
                if (!currentPlayerIds.contains(participant.getPlayerId())) {
                    // 计算平均分
                    BigDecimal averageScore = calculateAverageScore(participant.getId());
                    
                    // 只包含有评分的参赛者
                    if (averageScore != null && averageScore.compareTo(BigDecimal.ZERO) > 0) {
                        // 统计评分次数
                        long ratingCount = activityPlayerRatingRepository
                            .countCompletedRatingsByActivityPlayerId(participant.getId());
                        
                        PromotableParticipantResponse response = new PromotableParticipantResponse(
                            participant, averageScore, (int) ratingCount);
                        promotableList.add(response);
                    }
                }
            }
            
            // 按平均分降序排序
            promotableList.sort((a, b) -> {
                if (a.getAverageScore() == null && b.getAverageScore() == null) return 0;
                if (a.getAverageScore() == null) return 1;
                if (b.getAverageScore() == null) return -1;
                return b.getAverageScore().compareTo(a.getAverageScore());
            });
            
            // 计算可选择人数(当前阶段最大人数 - 当前阶段已有人数)
            Integer maxParticipants = currentStage.getPlayerMax() != null ? currentStage.getPlayerMax() : 0;
            Integer selectableCount = Math.max(0, maxParticipants - currentParticipants.size());
            
            return new PromotableParticipantsResponse(
                promotableList, 
                selectableCount, 
                promotableList.size(),
                previousStage.getName(),
                currentStage.getName()
            );
            
        } catch (Exception e) {
            return new PromotableParticipantsResponse(new ArrayList<>(), 0, 0, "", "");
        }
    }
    
    /**
     * 计算参赛者的平均分
     */
    private BigDecimal calculateAverageScore(Long activityPlayerId) {
        List<ActivityPlayerRating> ratings = activityPlayerRatingRepository
            .findCompletedRatingsByActivityPlayerId(activityPlayerId);
        
        if (ratings.isEmpty()) {
            return null;
        }
        
        BigDecimal totalScore = BigDecimal.ZERO;
        int count = 0;
        
        for (ActivityPlayerRating rating : ratings) {
            if (rating.getTotalScore() != null) {
                totalScore = totalScore.add(rating.getTotalScore());
                count++;
            }
        }
        
        if (count == 0) {
            return null;
        }
        
        return totalScore.divide(BigDecimal.valueOf(count), 2, RoundingMode.HALF_UP);
    }
    
    /**
     * 查找上一个阶段
     */
    private Activity findPreviousStage(Activity currentStage) {
        // 查询同一比赛下的所有阶段,按排序顺序
        List<Activity> stages = activityRepository.findByPidAndStateOrderBySortOrderAsc(currentStage.getPid(), 1);
        
        // 找到当前阶段的位置,返回上一个阶段
        for (int i = 0; i < stages.size(); i++) {
            if (stages.get(i).getId().equals(currentStage.getId()) && i > 0) {
                return stages.get(i - 1);
            }
        }
        
        return null; // 没有上一个阶段
    }
    
    /**
     * 执行晋级操作
     */
    @Transactional
    public PromotionResult promoteParticipants(PromotionInput input) {
        try {
            if (input.getParticipantIds() == null || input.getParticipantIds().isEmpty()) {
                return PromotionResult.failure("请选择要晋级的参赛者");
            }
            
            // 查询目标晋级阶段信息(用户点击的阶段就是要晋级到的阶段)
            Activity targetStage = activityRepository.findById(input.getCompetitionId()).orElse(null);
            if (targetStage == null) {
                return PromotionResult.failure("目标晋级阶段不存在");
            }
            
            // 查询要晋级的参赛者
            List<ActivityPlayer> participants = activityPlayerRepository.findAllById(input.getParticipantIds());
            if (participants.isEmpty()) {
                return PromotionResult.failure("没有找到要晋级的参赛者");
            }
            
            int promotedCount = 0;
            
            // 为每个参赛者创建目标阶段的报名记录
            for (ActivityPlayer participant : participants) {
                // 检查是否已经在目标阶段报名
                boolean alreadyPromoted = activityPlayerRepository.existsByStageIdAndPlayerId(targetStage.getId(), participant.getPlayerId());
                if (!alreadyPromoted) {
                    // 创建新的报名记录
                    ActivityPlayer newParticipant = new ActivityPlayer();
                    newParticipant.setActivityId(targetStage.getPid()); // 主比赛ID
                    newParticipant.setStageId(targetStage.getId()); // 目标阶段ID
                    newParticipant.setPlayerId(participant.getPlayerId());
                    newParticipant.setRegionId(participant.getRegionId());
                    newParticipant.setProjectName(participant.getProjectName());
                    newParticipant.setDescription(participant.getDescription());
                    newParticipant.setState(1); // 直接设为审核通过
                    
                    ActivityPlayer savedParticipant = activityPlayerRepository.save(newParticipant);
                    
                    // 复制媒体文件
                    copyMediaFiles(participant.getId(), savedParticipant.getId());
                    
                    // 创建晋级消息
                    messageService.createPromotionMessage(
                        savedParticipant.getId(), 
                        savedParticipant.getPlayerId(), 
                        savedParticipant.getProjectName()
                    );
                    
                    promotedCount++;
                }
            }
            
            return PromotionResult.success(
                String.format("成功晋级 %d 名参赛者到 %s", promotedCount, targetStage.getName()),
                promotedCount
            );
            
        } catch (Exception e) {
            return PromotionResult.failure("晋级操作失败:" + e.getMessage());
        }
    }
    
    /**
     * 复制媒体文件
     */
    private void copyMediaFiles(Long sourceActivityPlayerId, Long targetActivityPlayerId) {
        try {
            // 获取源参赛者的所有媒体文件 (targetType=5 表示 ACTIVITY_PLAYER)
            List<Media> sourceMediaFiles = mediaRepository.findByTargetTypeAndTargetIdAndState(5, sourceActivityPlayerId, 1);
            
            for (Media sourceMedia : sourceMediaFiles) {
                // 创建新的媒体记录
                Media newMedia = new Media();
                newMedia.setName(sourceMedia.getName());
                newMedia.setPath(sourceMedia.getPath());
                newMedia.setFileSize(sourceMedia.getFileSize());
                newMedia.setFileExt(sourceMedia.getFileExt());
                newMedia.setMediaType(sourceMedia.getMediaType());
                newMedia.setTargetType(5); // ACTIVITY_PLAYER
                newMedia.setTargetId(targetActivityPlayerId);
                newMedia.setThumbPath(sourceMedia.getThumbPath());
                newMedia.setDuration(sourceMedia.getDuration());
                newMedia.setDescription(sourceMedia.getDescription());
                
                // 保存新的媒体记录
                mediaRepository.save(newMedia);
            }
        } catch (Exception e) {
            // 记录错误但不中断晋级流程
            System.err.println("复制媒体文件失败: " + e.getMessage());
        }
    }
 
    /**
     * 查找下一个阶段
     */
 
}