blob: 6c0a56f6963440f1889615263f7c095860c7cdf3 [file] [log] [blame]
package com.pt.service;
import com.pt.entity.User;
import com.pt.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User findByUsername(String username) {
return userRepository.findByUsername(username);
}
public User findByEmail(String email) {
return userRepository.findByEmail(email);
}
public User findByUsernameAndPassword(String username, String password) {
return userRepository.findByUsernameAndPassword(username, password);
}
public User findByEmailAndPassword(String email, String password) {
return userRepository.findByEmailAndPassword(email, password);
}
public User save(User user) {
return userRepository.save(user);
}
public User findById(String uid) {
return userRepository.findById(uid).orElse(null);
}
public void deleteById(String uid) {
userRepository.deleteById(uid);
}
public List<User> listAll() {
return userRepository.findAll();
}
/**
* 根据用户的统计数据(上传量、下载量、积分)更新其等级。
* 该方法包含等级提升的规则,且只升不降。
* @param userId 要更新等级的用户的ID
*/
public void updateUserLevel(String userId) {
User user = userRepository.findById(userId).orElse(null);
if (user == null) {
// 在实际应用中,这里可能需要记录日志或抛出异常
return;
}
long uploaded = user.getUploaded();
long downloaded = user.getDownloaded();
int points = user.getPoints();
// 定义数据大小常量
final long GB = 1024L * 1024L * 1024L;
final long TB = 1024L * GB;
// 计算分享率。如果下载量为0,分享率视为无限大(只要有上传)
double shareRatio = (downloaded == 0 && uploaded > 0) ? Double.MAX_VALUE :
(downloaded == 0 && uploaded == 0) ? 0 : (double) uploaded / downloaded;
int newLevel = 1; // 默认为1级
// 等级规则(从高到低判断)
// 规则5: 大佬级
if (uploaded > 5 * TB && shareRatio > 2.0 && points > 10000) {
newLevel = 5;
}
// 规则4: 专家级
else if (uploaded > 1 * TB && shareRatio > 1.5 && points > 2000) {
newLevel = 4;
}
// 规则3: 熟练级
else if (uploaded > 200 * GB && shareRatio > 1.0 && points > 500) {
newLevel = 3;
}
// 规则2: 入门级 (获得发布权限)
else if (uploaded > 50 * GB && shareRatio > 0.5 && points > 100) {
newLevel = 2;
}
// 如果计算出的新等级高于当前等级,则更新用户等级
if (newLevel > user.getLevel()) {
user.setLevel(newLevel);
userRepository.save(user);
}
}
/**
* 批量更新所有用户的等级。
* 适合用于定时任务,定期刷新所有用户的等级。
*/
public void updateAllUsersLevel() {
List<User> allUsers = userRepository.findAll();
for (User user : allUsers) {
updateUserLevel(user.getUid());
}
}
}