lrj
6 天以前 6d519474e44855682043d3c40db2c86a6822caca
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
package com.rongyichuang.user.service;
 
import com.rongyichuang.user.entity.User;
import com.rongyichuang.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.Optional;
 
/**
 * 用户服务类
 */
@Service
@Transactional
public class UserService {
 
    @Autowired
    private UserRepository userRepository;
    
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
 
    /**
     * 根据手机号查找或创建用户
     * 如果用户存在,更新姓名和密码(如果提供了密码)
     * 如果用户不存在,创建新用户
     * 
     * @param phone 手机号
     * @param name 姓名
     * @param password 密码(可以为null,表示不更新密码)
     * @return 用户实体
     */
    public User findOrCreateUserByPhone(String phone, String name, String password) {
        Optional<User> existingUser = userRepository.findByPhone(phone);
        
        if (existingUser.isPresent()) {
            // 用户存在,更新姓名和密码(如果提供了密码)
            User user = existingUser.get();
            user.setName(name);
            if (password != null && !password.trim().isEmpty()) {
                user.setPassword(passwordEncoder.encode(password));
            }
            return userRepository.save(user);
        } else {
            // 用户不存在,创建新用户
            User newUser = new User();
            newUser.setName(name);
            newUser.setPhone(phone);
            if (password != null && !password.trim().isEmpty()) {
                newUser.setPassword(passwordEncoder.encode(password));
            } else {
                // 如果没有提供密码,设置一个默认密码
                newUser.setPassword(passwordEncoder.encode("123456"));
            }
            return userRepository.save(newUser);
        }
    }
 
    /**
     * 根据手机号查找用户
     */
    public Optional<User> findByPhone(String phone) {
        return userRepository.findByPhone(phone);
    }
 
    /**
     * 保存用户
     */
    public User save(User user) {
        return userRepository.save(user);
    }
 
    /**
     * 根据ID查找用户
     */
    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }
}