22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 1 | package com.example.myproject.service; |
| 2 | |
| 3 | import com.example.myproject.entity.*; |
| 4 | |
| 5 | import com.example.myproject.repository.*; |
| 6 | import jakarta.transaction.Transactional; |
| 7 | import org.springframework.beans.factory.annotation.Autowired; |
| 8 | import org.springframework.data.domain.Page; |
| 9 | import org.springframework.data.domain.PageRequest; |
| 10 | import org.springframework.data.domain.Pageable; |
| 11 | import org.springframework.data.domain.Sort; |
| 12 | import org.springframework.http.ResponseEntity; |
| 13 | import org.springframework.stereotype.Service; |
| 14 | import org.springframework.web.multipart.MultipartFile; |
| 15 | import java.io.IOException; |
| 16 | import java.nio.file.Path; |
| 17 | import java.nio.file.Files; |
| 18 | |
| 19 | import java.util.*; |
| 20 | |
| 21 | @Service |
| 22 | public class GroupService { |
| 23 | |
| 24 | @Autowired |
| 25 | private GroupRepository groupRepository; |
| 26 | |
| 27 | @Autowired |
| 28 | private GroupMembersRepository groupMembersRepository; |
| 29 | |
| 30 | |
| 31 | @Autowired |
| 32 | private UserRepository userRepository; |
| 33 | |
| 34 | @Autowired |
| 35 | private GroupPostRepository groupPostRepository; |
| 36 | |
| 37 | @Autowired |
| 38 | private GroupCommentsRepository groupCommentsRepository; |
| 39 | |
| 40 | private static final String IMAGE_DIR = "uploads/groupPost/"; |
| 41 | |
| 42 | @Transactional |
| 43 | // 创建小组的方法 |
| 44 | public ResponseEntity<Map<String, Object>> createGroup(Group groupRequest) { |
| 45 | try { |
| 46 | // 创建新的小组对象 |
| 47 | Group newGroup = new Group(); |
| 48 | newGroup.setGroupName(groupRequest.getGroupName()); |
| 49 | newGroup.setDescription(groupRequest.getDescription()); |
| 50 | newGroup.setCreateTime(new Date()); |
| 51 | newGroup.setUserId(groupRequest.getUserId()); |
| 52 | newGroup.setMemberCount(1); |
| 53 | newGroup.setCategory(groupRequest.getCategory()); |
| 54 | newGroup.setCoverImage(groupRequest.getCoverImage()); |
| 55 | Group createdGroup = groupRepository.save(newGroup); |
| 56 | |
| 57 | // 返回成功响应 |
| 58 | Map<String, Object> response = new HashMap<>(); |
| 59 | response.put("status", "success"); |
| 60 | response.put("message", "兴趣小组创建成功"); |
| 61 | response.put("group_id", createdGroup.getGroupId()); |
| 62 | |
| 63 | return ResponseEntity.ok(response); |
| 64 | } catch (Exception e) { |
| 65 | // 返回失败响应 |
| 66 | Map<String, Object> errorResponse = new HashMap<>(); |
| 67 | errorResponse.put("status", "error"); |
| 68 | errorResponse.put("message", "小组创建失败"); |
| 69 | errorResponse.put("group_id", null); |
| 70 | |
| 71 | return ResponseEntity.status(400).body(errorResponse); |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | |
| 76 | // 加入小组 |
| 77 | @Transactional |
| 78 | public ResponseEntity<Map<String, Object>> joinGroup(Long groupId, Long userId) { |
| 79 | // 查找小组 |
| 80 | Optional<Group> groupOptional = groupRepository.findById(groupId); |
| 81 | if (!groupOptional.isPresent()) { |
| 82 | return ResponseEntity.status(400).body( |
| 83 | Map.of("status", "failure", "message", "小组不存在") |
| 84 | ); |
| 85 | } |
| 86 | |
| 87 | Group group = groupOptional.get(); |
| 88 | |
| 89 | // 检查用户是否已经是该小组成员 |
| 90 | if (groupMembersRepository.existsByGroupIdAndUserId(groupId, userId)) { |
| 91 | return ResponseEntity.status(400).body( |
| 92 | Map.of("status", "failure", "message", "用户已经是该小组的成员") |
| 93 | ); |
| 94 | } |
| 95 | |
| 96 | // 插入用户和小组的关联记录 |
| 97 | GroupMembers groupMembers = new GroupMembers(); |
| 98 | groupMembers.setGroupId(groupId); |
| 99 | groupMembers.setUserId(userId); |
| 100 | groupMembersRepository.save(groupMembers); |
| 101 | |
| 102 | // 更新小组的成员数 |
| 103 | group.setMemberCount(group.getMemberCount() + 1); |
| 104 | groupRepository.save(group); |
| 105 | |
| 106 | return ResponseEntity.ok().body( |
| 107 | Map.of("status", "success", "message", "成功加入小组") |
| 108 | ); |
| 109 | } |
| 110 | |
| 111 | // 退出小组 |
| 112 | @Transactional |
| 113 | public ResponseEntity<Map<String, Object>> leaveGroup(Long groupId, Long userId) { |
| 114 | // 查找小组 |
| 115 | Optional<Group> groupOptional = groupRepository.findById(groupId); |
| 116 | if (!groupOptional.isPresent()) { |
| 117 | return ResponseEntity.status(400).body( |
| 118 | Map.of("status", "failure", "message", "小组不存在") |
| 119 | ); |
| 120 | } |
| 121 | |
| 122 | Group group = groupOptional.get(); |
| 123 | |
| 124 | // 检查用户是否是该小组成员 |
| 125 | if (!groupMembersRepository.existsByGroupIdAndUserId(groupId, userId)) { |
| 126 | return ResponseEntity.status(400).body( |
| 127 | Map.of("status", "failure", "message", "用户不是该小组的成员") |
| 128 | ); |
| 129 | } |
| 130 | |
| 131 | // 删除用户和小组的关联记录 |
| 132 | groupMembersRepository.deleteByGroupIdAndUserId(groupId, userId); |
| 133 | |
| 134 | // 更新小组的成员数 |
| 135 | group.setMemberCount(group.getMemberCount() - 1); |
| 136 | groupRepository.save(group); |
| 137 | |
| 138 | return ResponseEntity.ok().body( |
| 139 | Map.of("status", "success", "message", "成功退出小组") |
| 140 | ); |
| 141 | } |
| 142 | |
| 143 | // 获取所有成员 |
| 144 | @Transactional |
| 145 | public ResponseEntity<Map<String, Object>> getGroupMembers(Long groupId) { |
| 146 | // 查找小组 |
| 147 | Optional<Group> groupOptional = groupRepository.findById(groupId); |
| 148 | if (!groupOptional.isPresent()) { |
| 149 | return ResponseEntity.status(400).body( |
| 150 | Map.of("status", "failure", "message", "小组不存在") |
| 151 | ); |
| 152 | } |
| 153 | |
| 154 | Group group = groupOptional.get(); |
| 155 | |
| 156 | // 获取所有小组成员 |
| 157 | List<GroupMembers> groupMembersList = groupMembersRepository.findByGroupId(groupId); |
| 158 | |
| 159 | // 创建成员返回列表 |
| 160 | List<Map<String, Object>> members = new ArrayList<>(); |
| 161 | for (GroupMembers groupMember : groupMembersList) { |
| 162 | Optional<Users> userOptional = userRepository.findById(groupMember.getUserId()); |
| 163 | if (userOptional.isPresent()) { |
| 164 | Users user = userOptional.get(); |
| 165 | members.add(Map.of( |
| 166 | "user_id", user.getUserId(), |
| 167 | "username", user.getUsername(), |
| 168 | "avatar_url", user.getAvatarUrl() |
| 169 | )); |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | return ResponseEntity.ok().body( |
| 174 | Map.of("status", "success", "members", members) |
| 175 | ); |
| 176 | } |
| 177 | |
| 178 | |
| 179 | //发布帖子 |
| 180 | public Map<String, Object> createPost(Long groupId, Long userId, String postContent, String title, MultipartFile[] imageFiles) { |
| 181 | // 创建一个新的帖子对象 |
| 182 | GroupPost post = new GroupPost(); |
| 183 | post.setGroupId(groupId); |
| 184 | post.setUserId(userId); |
| 185 | post.setContent(postContent); |
| 186 | post.setTitle(title); |
| 187 | post.setTime(new Date()); |
| 188 | post.setLikeCount(0); |
| 189 | post.setCommentCount(0); |
| 190 | |
| 191 | // 处理图片上传,如果没有图片,返回空字符串 |
| 192 | String imageUrls = handleImages(imageFiles); |
| 193 | post.setImage(imageUrls); |
| 194 | |
| 195 | // 保存帖子到数据库 |
| 196 | GroupPost savedPost = groupPostRepository.save(post); |
| 197 | |
| 198 | // 返回结果 |
| 199 | Map<String, Object> response = new LinkedHashMap<>(); |
| 200 | response.put("post_id", savedPost.getGroupPostId()); |
| 201 | response.put("message", "帖子创建成功"); |
| 202 | return response; |
| 203 | } |
| 204 | |
| 205 | // 处理图片上传的方法,返回图片的 URL 字符串 |
| 206 | private String handleImages(MultipartFile[] imageFiles) { |
| 207 | if (imageFiles == null || imageFiles.length == 0) { |
| 208 | return ""; |
| 209 | } |
| 210 | |
| 211 | StringBuilder imageUrlsBuilder = new StringBuilder(); |
| 212 | |
| 213 | for (int i = 0; i < imageFiles.length; i++) { |
| 214 | if (i > 0) { |
| 215 | imageUrlsBuilder.append(","); |
| 216 | } |
| 217 | try { |
| 218 | String imageUrl = saveImage(imageFiles[i]); |
| 219 | imageUrlsBuilder.append(imageUrl); |
| 220 | } catch (IOException e) { |
| 221 | throw new RuntimeException("图片上传失败: " + e.getMessage()); |
| 222 | } |
| 223 | } |
| 224 | return imageUrlsBuilder.toString(); |
| 225 | } |
| 226 | |
| 227 | // 保存图片并返回图片的 URL |
| 228 | private String saveImage(MultipartFile imageFile) throws IOException { |
| 229 | if (imageFile == null) { |
| 230 | throw new IOException("图片文件为空"); |
| 231 | } |
| 232 | |
| 233 | String fileName = imageFile.getOriginalFilename(); |
| 234 | Path path = Path.of(IMAGE_DIR + fileName); |
| 235 | Files.createDirectories(path.getParent()); |
| 236 | Files.write(path, imageFile.getBytes()); |
| 237 | return "/images/" + fileName; |
| 238 | } |
| 239 | |
| 240 | // 获取小组内的所有帖子 |
| 241 | public Map<String, Object> getAllPosts(Long groupId) { |
| 242 | List<GroupPost> posts = groupPostRepository.findByGroupId(groupId); |
| 243 | |
| 244 | List<Map<String, Object>> postList = new ArrayList<>(); |
| 245 | |
| 246 | for (GroupPost post : posts) { |
| 247 | Map<String, Object> postData = new HashMap<>(); |
| 248 | Users user = userRepository.findById(post.getUserId()).orElseThrow(() -> new RuntimeException("User not found")); |
| 249 | postData.put("group_post_id", post.getGroupPostId()); |
| 250 | postData.put("user_id", post.getUserId()); |
| 251 | postData.put("username", user.getUsername()); |
| 252 | postData.put("title", post.getTitle()); |
| 253 | postData.put("content", post.getContent()); |
| 254 | postData.put("time", post.getTime()); |
| 255 | |
| 256 | postList.add(postData); |
| 257 | } |
| 258 | |
| 259 | // 返回响应数据 |
| 260 | Map<String, Object> response = new LinkedHashMap<>(); |
| 261 | response.put("status", "success"); |
| 262 | response.put("posts", postList); |
| 263 | return response; |
| 264 | } |
| 265 | |
| 266 | |
| 267 | // 获取小组列表接口 |
| 268 | public Map<String, Object> searchGroups(Map<String, Object> params) { |
| 269 | String name = (String) params.get("name"); |
| 270 | String category = (String) params.get("category"); |
| 271 | Integer page = (Integer) params.getOrDefault("page", 1); |
| 272 | Integer size = (Integer) params.getOrDefault("size", 10); |
| 273 | String sortBy = (String) params.getOrDefault("sort_by", "memberCount"); |
| 274 | |
| 275 | // 构建分页对象 |
| 276 | Pageable pageable; |
| 277 | |
| 278 | // 根据 `sortBy` 判断排序方式 |
| 279 | if ("createTime".equals(sortBy)) { |
| 280 | pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Order.asc("createTime"))); |
| 281 | } else if ("groupName".equals(sortBy)) { |
| 282 | pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Order.asc("groupName"))); |
| 283 | } else { |
| 284 | pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Order.desc("memberCount"))); |
| 285 | } |
| 286 | |
| 287 | Page<Group> groups; |
| 288 | if (name != null && !name.isEmpty()) { |
| 289 | // 小组名称模糊查询 |
| 290 | groups = groupRepository.searchGroups(name, category, pageable); |
| 291 | } else { |
| 292 | groups = groupRepository.searchWithFilters(category, pageable); |
| 293 | } |
| 294 | |
| 295 | return buildResponse(groups); |
| 296 | } |
| 297 | |
| 298 | // 构建返回的响应数据 |
| 299 | private Map<String, Object> buildResponse(Page<Group> groups) { |
| 300 | Map<String, Object> response = new LinkedHashMap<>(); |
| 301 | response.put("status", "success"); |
| 302 | response.put("total", groups.getTotalElements()); |
| 303 | response.put("total_pages", groups.getTotalPages()); |
| 304 | response.put("current_page", groups.getNumber() + 1); |
| 305 | response.put("items", groups.getContent()); |
| 306 | |
| 307 | return response; |
| 308 | } |
| 309 | |
| 310 | // 点赞帖子 |
| 311 | public Map<String, Object> likePost(Long GroupPostId) { |
| 312 | // 查找帖子 |
| 313 | Optional<GroupPost> postOpt = groupPostRepository.findById(GroupPostId); |
| 314 | if (!postOpt.isPresent()) { |
| 315 | throw new RuntimeException("Post not found"); |
| 316 | } |
| 317 | |
| 318 | GroupPost post = postOpt.get(); |
| 319 | |
| 320 | // 更新点赞数 |
| 321 | post.setLikeCount(post.getLikeCount() + 1); |
| 322 | groupPostRepository.save(post); |
| 323 | |
| 324 | // 返回成功信息 |
| 325 | Map<String, Object> response = new HashMap<>(); |
| 326 | response.put("status", "success"); |
| 327 | response.put("message", "点赞成功"); |
| 328 | return response; |
| 329 | } |
| 330 | |
| 331 | // 取消点赞 |
| 332 | public Map<String, Object> unlikePost(Long GroupPostId) { |
| 333 | // 查找帖子 |
| 334 | Optional<GroupPost> postOpt = groupPostRepository.findById(GroupPostId); |
| 335 | if (!postOpt.isPresent()) { |
| 336 | throw new RuntimeException("Post not found"); |
| 337 | } |
| 338 | |
| 339 | GroupPost post = postOpt.get(); |
| 340 | |
| 341 | // 更新点赞数 |
| 342 | if (post.getLikeCount() > 0) { |
| 343 | post.setLikeCount(post.getLikeCount() - 1); |
| 344 | groupPostRepository.save(post); |
| 345 | |
| 346 | // 返回成功信息 |
| 347 | Map<String, Object> response = new HashMap<>(); |
| 348 | response.put("status", "success"); |
| 349 | response.put("message", "取消点赞成功"); |
| 350 | return response; |
| 351 | } else { |
| 352 | // 如果点赞数已经是0,则返回相应消息 |
| 353 | Map<String, Object> response = new HashMap<>(); |
| 354 | response.put("status", "failure"); |
| 355 | response.put("message", "无法取消点赞,点赞数已经为0"); |
| 356 | return response; |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | // 添加评论并更新帖子的评论数 |
| 361 | public Map<String, Object> addComment(Long postId, GroupComments comment) { |
| 362 | // 查找帖子 |
| 363 | Optional<GroupPost> postOpt = groupPostRepository.findById(postId); |
| 364 | if (!postOpt.isPresent()) { |
| 365 | throw new RuntimeException("Post not found"); |
| 366 | } |
| 367 | |
| 368 | GroupPost post = postOpt.get(); |
| 369 | |
| 370 | comment.setGroupPostId(postId); |
| 371 | comment.setTime(new java.util.Date()); |
| 372 | groupCommentsRepository.save(comment); |
| 373 | post.setCommentCount(post.getCommentCount() + 1); |
| 374 | groupPostRepository.save(post); |
| 375 | Map<String, Object> response = new HashMap<>(); |
| 376 | response.put("status", "success"); |
| 377 | response.put("message", "评论成功"); |
| 378 | return response; |
| 379 | } |
| 380 | |
| 381 | |
| 382 | } |