22301115 | cf6dba2 | 2025-03-25 19:06:21 +0800 | [diff] [blame] | 1 | package com.example.myproject.service; |
| 2 | |
22301138 | b253341 | 2025-06-05 00:18:58 +0800 | [diff] [blame] | 3 | import com.example.myproject.entity.User; |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 4 | import com.example.myproject.entity.Users; |
| 5 | import com.example.myproject.entity.UserInviteCode; |
| 6 | import com.example.myproject.repository.UserRepository; |
| 7 | import com.example.myproject.repository.UserInviteCodeRepository; |
| 8 | import org.springframework.beans.factory.annotation.Autowired; |
| 9 | import org.springframework.stereotype.Service; |
22301138 | b253341 | 2025-06-05 00:18:58 +0800 | [diff] [blame] | 10 | import org.springframework.web.multipart.MultipartFile; |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 11 | |
22301138 | b253341 | 2025-06-05 00:18:58 +0800 | [diff] [blame] | 12 | import javax.servlet.http.HttpServletRequest; |
| 13 | import java.io.File; |
| 14 | import java.io.IOException; |
| 15 | import java.nio.file.Files; |
| 16 | import java.nio.file.Path; |
| 17 | import java.nio.file.Paths; |
| 18 | import java.time.LocalDateTime; |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 19 | import java.util.*; |
| 20 | |
| 21 | @Service |
| 22 | public class UserService { |
| 23 | |
| 24 | @Autowired |
| 25 | private UserRepository userRepository; |
| 26 | |
| 27 | @Autowired |
| 28 | private UserInviteCodeRepository userInviteCodeRepository; |
| 29 | |
| 30 | // 生成邀请码 |
| 31 | public Map<String, Object> generateInviteCode(Long userId) { |
| 32 | // 获取用户信息 |
| 33 | Users user = userRepository.findById(userId).orElse(null); |
| 34 | |
| 35 | // 如果用户不存在,返回错误 |
| 36 | if (user == null) { |
| 37 | Map<String, Object> errorResponse = new HashMap<>(); |
| 38 | errorResponse.put("status", "failure"); |
| 39 | errorResponse.put("message", "用户不存在"); |
| 40 | return errorResponse; |
| 41 | } |
| 42 | |
| 43 | // 检查用户的邀请数量 |
| 44 | if (user.getInviteCount() <= 0) { |
| 45 | Map<String, Object> errorResponse = new HashMap<>(); |
| 46 | errorResponse.put("status", "failure"); |
| 47 | errorResponse.put("message", "没有剩余的邀请码"); |
| 48 | return errorResponse; |
| 49 | } |
| 50 | |
| 51 | // 生成唯一的邀请码 |
| 52 | String inviteCode = generateUniqueInviteCode(); |
| 53 | |
| 54 | // 将邀请码保存到 `user_invite_code` 表 |
| 55 | UserInviteCode userInviteCode = new UserInviteCode(); |
| 56 | userInviteCode.setUserId(userId); |
| 57 | userInviteCode.setInviteCode(inviteCode); |
| 58 | userInviteCode.setCreatedAt(java.time.LocalDateTime.now()); |
| 59 | |
| 60 | userInviteCodeRepository.save(userInviteCode); |
| 61 | |
| 62 | // 更新用户的 `invite_count`,减少1 |
| 63 | user.setInviteCount(user.getInviteCount() - 1); |
| 64 | userRepository.save(user); |
| 65 | |
| 66 | // 返回成功信息 |
| 67 | Map<String, Object> response = new HashMap<>(); |
| 68 | response.put("status", "success"); |
| 69 | response.put("message", "邀请码生成成功"); |
| 70 | response.put("invite_code", inviteCode); |
| 71 | |
| 72 | return response; |
| 73 | } |
| 74 | |
| 75 | // 生成唯一的邀请码,使用26个字母(大小写) |
| 76 | private String generateUniqueInviteCode() { |
| 77 | String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; |
| 78 | StringBuilder inviteCode = new StringBuilder(); |
| 79 | |
| 80 | Random random = new Random(); |
| 81 | for (int i = 0; i < 10; i++) { |
| 82 | inviteCode.append(characters.charAt(random.nextInt(characters.length()))); |
| 83 | } |
| 84 | |
| 85 | return inviteCode.toString(); |
| 86 | } |
| 87 | |
| 88 | public String registerUser(String username, String email, String password, String role, String inviteCode) { |
| 89 | // 检查邮箱是否已经注册 |
| 90 | Optional<Users> existingEmailUser = userRepository.findByEmail(email); |
| 91 | if (existingEmailUser.isPresent()) { |
| 92 | return "该邮箱已被注册"; |
| 93 | } |
| 94 | |
| 95 | // 检查用户名是否已经存在 |
| 96 | Optional<Users> existingUsernameUser = userRepository.findByUsername(username); // 需要根据用户名查询 |
| 97 | if (existingUsernameUser.isPresent()) { |
| 98 | return "该用户名已被注册"; |
| 99 | } |
| 100 | |
| 101 | // 检查邀请码是否有效 |
| 102 | if (inviteCode == null || inviteCode.isEmpty()) { |
| 103 | return "邀请码不能为空"; |
| 104 | } |
| 105 | |
| 106 | Optional<UserInviteCode> invite = userInviteCodeRepository.findByInviteCode(inviteCode); |
| 107 | if (invite.isEmpty() || invite.get().getIsUsed()) { |
| 108 | return "邀请码无效或已被使用"; |
| 109 | } |
| 110 | |
| 111 | // 设置默认等级为2(由于邀请码有效) |
| 112 | Long level = 2L; |
| 113 | |
| 114 | // 设置默认头像 URL |
| 115 | String avatarUrl = "https://example.com/default-avatar.jpg"; // 默认头像 |
| 116 | |
| 117 | // 获取邀请码对应的用户ID |
| 118 | UserInviteCode inviteEntity = invite.get(); |
| 119 | Long inviteUserId = inviteEntity.getUserId(); |
| 120 | |
| 121 | // 创建新用户 |
| 122 | Users newUser = new Users(); |
| 123 | newUser.setUsername(username); |
| 124 | newUser.setEmail(email); |
| 125 | newUser.setPassword(password); |
| 126 | newUser.setRole(role); |
| 127 | newUser.setInviteCount(0); // 初始邀请码数量为 0 |
| 128 | newUser.setLevel(level); |
| 129 | newUser.setAvatarUrl(avatarUrl); // 设置默认头像 |
| 130 | newUser.setRegistrationDate(new java.util.Date()); // 设置注册日期 |
| 131 | newUser.setCurrentExperience(0); // 默认经验为 0 |
| 132 | newUser.setCurrentSeedingHours(0f); // 默认做种时长为 0 |
| 133 | newUser.setRegistrationTime(new java.util.Date()); // 设置注册时间为当前时间 |
| 134 | |
| 135 | // 保存用户信息 |
| 136 | userRepository.save(newUser); |
| 137 | |
| 138 | // 更新邀请码的使用状态 |
| 139 | inviteEntity.setIsUsed(true); |
| 140 | userInviteCodeRepository.save(inviteEntity); |
| 141 | |
| 142 | return "用户注册成功"; |
| 143 | } |
22301115 | cf6dba2 | 2025-03-25 19:06:21 +0800 | [diff] [blame] | 144 | |
| 145 | |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 146 | public String loginUser(String username, String password) { |
| 147 | // 检查用户是否存在 |
| 148 | Optional<Users> userOptional = userRepository.findByUsername(username); |
| 149 | if (userOptional.isEmpty()) { |
| 150 | return "用户名不存在"; |
| 151 | } |
22301115 | cf6dba2 | 2025-03-25 19:06:21 +0800 | [diff] [blame] | 152 | |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 153 | Users user = userOptional.get(); |
22301115 | cf6dba2 | 2025-03-25 19:06:21 +0800 | [diff] [blame] | 154 | |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 155 | // 检查密码是否正确 |
| 156 | if (!user.getPassword().equals(password)) { |
| 157 | return "密码错误"; |
| 158 | } |
| 159 | |
| 160 | // 登录成功 |
| 161 | return "登录成功"; |
| 162 | } |
| 163 | |
| 164 | public String changePassword(Long userId, String oldPassword, String newPassword, String confirmPassword) { |
| 165 | // 查找用户 |
| 166 | Users user = userRepository.findById(userId).orElse(null); |
| 167 | |
| 168 | if (user == null) { |
| 169 | return "用户不存在"; |
| 170 | } |
| 171 | |
| 172 | // 检查旧密码是否正确 |
| 173 | if (!user.getPassword().equals(oldPassword)) { |
| 174 | return "旧密码错误"; |
| 175 | } |
| 176 | |
| 177 | // 检查新密码和确认密码是否一致 |
| 178 | if (!newPassword.equals(confirmPassword)) { |
| 179 | return "新密码与确认密码不一致"; |
| 180 | } |
| 181 | |
| 182 | // 更新密码 |
| 183 | user.setPassword(newPassword); |
| 184 | userRepository.save(user); |
| 185 | |
| 186 | return "密码修改成功"; |
| 187 | } |
| 188 | |
| 189 | // 获取用户个人资料 |
| 190 | public Map<String, Object> getProfile(Long userId) { |
| 191 | Optional<Users> userOptional = userRepository.findById(userId); |
| 192 | |
| 193 | // 如果用户不存在,返回null或者可以抛出异常 |
| 194 | if (userOptional.isEmpty()) { |
| 195 | return null; // 可以返回 null 或者根据需要返回错误信息 |
| 196 | } |
| 197 | |
| 198 | Users user = userOptional.get(); |
| 199 | |
| 200 | // 将需要的字段放入 Map 中 |
| 201 | Map<String, Object> profile = new LinkedHashMap<>(); |
| 202 | profile.put("avatarUrl", user.getAvatarUrl()); |
| 203 | profile.put("username", user.getUsername()); |
| 204 | profile.put("email", user.getEmail()); |
| 205 | profile.put("gender", user.getGender()); |
| 206 | profile.put("description", user.getDescription()); |
| 207 | profile.put("hobbies", user.getHobbies()); |
| 208 | profile.put("level", user.getLevel()); |
| 209 | profile.put("Experience", user.getCurrentExperience()); |
| 210 | profile.put("uploadCount", user.getUploadCount()); |
| 211 | profile.put("downloadCount", user.getDownloadCount()); |
| 212 | profile.put("shareRate", user.getShareRate()); |
| 213 | profile.put("registrationTime", user.getRegistrationTime()); |
| 214 | |
| 215 | return profile; |
| 216 | } |
| 217 | |
| 218 | // 修改用户个人资料 |
22301138 | b253341 | 2025-06-05 00:18:58 +0800 | [diff] [blame] | 219 | public boolean editProfile(Long userId, String nickname, String gender, String description, String hobbies) { |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 220 | Optional<Users> userOptional = userRepository.findById(userId); |
| 221 | |
| 222 | // 如果用户不存在,返回false |
| 223 | if (userOptional.isEmpty()) { |
| 224 | return false; // 用户不存在 |
| 225 | } |
| 226 | |
| 227 | Users user = userOptional.get(); |
| 228 | |
| 229 | // 更新用户资料,只有传入值才会更新对应字段 |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 230 | if (nickname != null) { |
| 231 | user.setUsername(nickname); |
| 232 | } |
| 233 | if (gender != null) { |
| 234 | user.setGender(gender); |
| 235 | } |
| 236 | if (description != null) { |
| 237 | user.setDescription(description); |
| 238 | } |
| 239 | if (hobbies != null) { |
| 240 | user.setHobbies(hobbies); |
| 241 | } |
| 242 | |
| 243 | // 保存更新后的用户信息 |
| 244 | userRepository.save(user); |
| 245 | |
| 246 | return true; // 更新成功 |
| 247 | } |
| 248 | |
| 249 | public Map<String, Object> calculateShareRate(Long userId) { |
| 250 | // 查找用户 |
| 251 | Users user = userRepository.findById(userId).orElse(null); |
| 252 | if (user == null) { |
| 253 | return Map.of("status", "error", "message", "用户不存在"); |
| 254 | } |
| 255 | |
| 256 | // 获取上传量和下载量 |
| 257 | Float uploadCount = user.getUploadCount(); |
| 258 | Float downloadCount = user.getDownloadCount(); |
| 259 | |
| 260 | // 计算分享率 |
| 261 | Float shareRate = 0f; // 默认分享率为0 |
| 262 | if (downloadCount != 0) { |
| 263 | shareRate = uploadCount / downloadCount; // 分享率 = 上传量 / 下载量 |
| 264 | } |
| 265 | |
| 266 | // 更新用户的分享率 |
| 267 | user.setShareRate(shareRate); |
| 268 | userRepository.save(user); |
| 269 | |
| 270 | // 返回结果 |
| 271 | return Map.of("status", "success", "message", "分享率计算成功", "shareRate", shareRate); |
| 272 | } |
22301115 | cf6dba2 | 2025-03-25 19:06:21 +0800 | [diff] [blame] | 273 | |
| 274 | |
22301138 | b253341 | 2025-06-05 00:18:58 +0800 | [diff] [blame] | 275 | private static final String AVATAR_DIR = "uploads/avatarUrl/"; |
| 276 | |
| 277 | public Map<String, Object> uploadUserAvatar(Long userId, MultipartFile file) { |
| 278 | Users user = userRepository.findById(userId) |
| 279 | .orElseThrow(() -> new RuntimeException("用户不存在")); |
| 280 | |
| 281 | try { |
| 282 | String avatarUrl = saveAvatar(file, userId); |
| 283 | user.setAvatarUrl(avatarUrl); |
| 284 | userRepository.save(user); |
| 285 | |
| 286 | Map<String, Object> response = new HashMap<>(); |
| 287 | response.put("status", "success"); |
| 288 | response.put("message", "头像上传成功"); |
| 289 | response.put("userId", user.getUserId()); |
| 290 | response.put("avatarUrl", avatarUrl); |
| 291 | return response; |
| 292 | |
| 293 | } catch (IOException e) { |
| 294 | throw new RuntimeException("头像上传失败: " + e.getMessage()); |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | // 保存头像文件并返回可访问 URL |
| 299 | public String saveAvatar(MultipartFile file, Long userId) throws IOException { |
| 300 | String originalFilename = file.getOriginalFilename(); |
| 301 | String extension = originalFilename.substring(originalFilename.lastIndexOf('.')); |
| 302 | String fileName = userId + extension; // 以用户ID作为文件名 |
| 303 | Path path = Paths.get(AVATAR_DIR + fileName); |
| 304 | Files.createDirectories(path.getParent()); |
| 305 | Files.write(path, file.getBytes()); |
| 306 | return "/" + AVATAR_DIR + fileName; // 返回相对URL路径 |
| 307 | } |
| 308 | |
| 309 | |
| 310 | |
22301138 | 5e9c35a | 2025-06-04 15:52:45 +0800 | [diff] [blame] | 311 | } |