blob: feb7404968f53b484904efe4e990bf3ee2243e39 [file] [log] [blame]
package com.example.myproject.service;
import com.example.myproject.entity.Likes;
import com.example.myproject.entity.Post;
import com.example.myproject.entity.Users;
import com.example.myproject.repository.CollectionsRepository;
import com.example.myproject.repository.LikesRepository;
import com.example.myproject.repository.PostRepository;
import com.example.myproject.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.example.myproject.entity.Collections;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
@Service
public class PostService {
@Autowired
private PostRepository postRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private LikesRepository likesRepository;
@Autowired
private CollectionsRepository collectionsRepository;
private static final String IMAGE_DIR = "uploads/post/";
//创建帖子
public Map<String, Object> createPost(Long userId, String postContent, String title, MultipartFile[] imageFiles) {
// 查找用户信息
Users user = userRepository.findById(Long.valueOf(userId)).orElseThrow(() -> new RuntimeException("User not found"));
Post post = new Post();
post.setUser_id(user.getUserId());
post.setPostTime(new Date());
post.setPostLikeNum(0);
post.setPostCollectNum(0);
post.setPostContent(postContent);
post.setTitle(title);
// 处理多张图片的上传
StringBuilder imageUrlsBuilder = new StringBuilder();
if (imageFiles != null && imageFiles.length > 0) {
for (int i = 0; i < imageFiles.length; i++) {
if (i > 0) {
imageUrlsBuilder.append(",");
}
try {
String imageUrl = saveImage(imageFiles[i]);
imageUrlsBuilder.append(imageUrl);
} catch (IOException e) {
throw new RuntimeException("Image upload failed: " + e.getMessage());
}
}
}
post.setImageUrl(imageUrlsBuilder.toString());
Post savedPost = postRepository.save(post);
Map<String, Object> response = new HashMap<>();
response.put("postNo", savedPost.getPostNo());
response.put("message", "帖子创建成功");
return response;
}
// 保存图片并返回图片的 URL
public String saveImage(MultipartFile imageFile) throws IOException {
String fileName = imageFile.getOriginalFilename();
Path path = Paths.get(IMAGE_DIR + fileName);
Files.createDirectories(path.getParent());
Files.write(path, imageFile.getBytes());
return "/images/" + fileName;
}
//编辑帖子
public void updatePost(Long postId, Post post) {
Post existingPost = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found"));
if (post.getTitle() != null) {
existingPost.setTitle(post.getTitle());
}
if (post.getPostContent() != null) {
existingPost.setPostContent(post.getPostContent());
}
if (post.getImageUrl() != null) {
existingPost.setImageUrl(post.getImageUrl());
}
existingPost.setPostTime(post.getPostTime());
// 保存更新后的帖子
postRepository.save(existingPost);
}
//删除帖子
public void deletePost(Long postId) {
// 查找指定 ID 的帖子,如果不存在则抛出异常
if (!postRepository.existsById(postId)) {
throw new RuntimeException("Post not found");
}
// 删除该帖子
postRepository.deleteById(postId);
}
//点赞帖子(已完成)
public void likePost(Long postId, Long userId) {
// 查找指定 ID 的帖子
Post post = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found"));
post.setPostLikeNum(post.getPostLikeNum() + 1);
// 保存帖子
postRepository.save(post);
Likes like = new Likes();
like.setUserId(userId);
like.setPostNo(postId);
// 保存点赞记录
likesRepository.save(like);
}
// 取消点赞帖子(已完成)
public void unlikePost(Long postId, Long userId) {
// 查找指定 ID 的帖子
Post post = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found"));
// 如果点赞数大于 0,则减少点赞数
if (post.getPostLikeNum() > 0) {
post.setPostLikeNum(post.getPostLikeNum() - 1);
}
// 删除点赞表中对应的记录
likesRepository.deleteLikeByUserIdAndPostNo(userId, postId);
// 保存更新后的帖子
postRepository.save(post);
}
// 获取帖子列表(已完成)
public Map<String, Object> getAllPosts() {
List<Post> posts = postRepository.findAll();
List<Map<String, Object>> postList = new ArrayList<>();
for (Post post : posts) {
Map<String, Object> postMap = new LinkedHashMap<>();
postMap.put("postNo", post.getPostNo());
postMap.put("user_id", post.getUser_id());
postMap.put("postContent", post.getPostContent());
postMap.put("imgUrl", post.getImageUrl());
postMap.put("title", post.getTitle());
postMap.put("createdAt", post.getPostTime().toString());
postMap.put("likeCount", post.getPostLikeNum());
postMap.put("collectCount", post.getPostCollectNum());
postList.add(postMap);
}
Map<String, Object> response = new HashMap<>();
// 统计帖子数量
response.put("total", postList.size());
response.put("posts", postList);
return response;
}
public Map<String, Object> getPostById(Long postId) {
// 获取帖子
Optional<Post> postOptional = postRepository.findById(postId);
// 如果帖子存在
if (postOptional.isPresent()) {
Post post = postOptional.get();
Map<String, Object> postData = new LinkedHashMap<>();
postData.put("postNo", post.getPostNo());
postData.put("user_id", post.getUser_id());
Long userId = post.getUser_id();
Users user = userRepository.findById(userId).orElse(null);
if (user != null) {
postData.put("username", user.getUsername());
postData.put("avatar_url", user.getAvatarUrl());
} else {
postData.put("username", null);
postData.put("avatar_url", null);
}
postData.put("postContent", post.getPostContent());
postData.put("imageUrl", post.getImageUrl());
postData.put("postTime", post.getPostTime());
postData.put("postLikeNum", post.getPostLikeNum());
postData.put("postCollectNum", post.getPostCollectNum());
postData.put("title", post.getTitle());
return postData;
} else {
throw new RuntimeException("Post not found with id: " + postId);
}
}
//收藏
public void collectPost(Long postId, Long userId) {
Post post = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found"));
post.setPostCollectNum(post.getPostCollectNum() + 1);
postRepository.save(post);
// 添加到收藏表
Collections collection = new Collections();
collection.setUserId(userId);
collection.setPostNo(postId);
collectionsRepository.save(collection);
}
//取消收藏
public void uncollectPost(Long postId, Long userId) {
Post post = postRepository.findById(postId).orElseThrow(() -> new RuntimeException("Post not found"));
// 减少帖子收藏数
if (post.getPostCollectNum() > 0) {
post.setPostCollectNum(post.getPostCollectNum() - 1);
postRepository.save(post);
}
// 从收藏表中删除对应记录
collectionsRepository.deleteLikeByUserIdAndPostNo(userId, postId);
}
}