lrj
5 天以前 4fa9591629721797386fc11836e3a9deb69cd58c
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package com.rongyichuang.employee.service;
 
import com.rongyichuang.employee.dto.request.EmployeeInput;
import com.rongyichuang.employee.dto.response.EmployeeResponse;
import com.rongyichuang.employee.entity.Employee;
import com.rongyichuang.employee.repository.EmployeeRepository;
import com.rongyichuang.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
 
/**
 * 员工服务类
 */
@Service
@Transactional
public class EmployeeService {
 
    private static final Logger logger = LoggerFactory.getLogger(EmployeeService.class);
 
    @Autowired
    private EmployeeRepository employeeRepository;
 
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
 
    // 密码验证正则:至少6个字符,必须包含字母和数字
    private static final Pattern PASSWORD_PATTERN = Pattern.compile("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d@$!%*?&]{6,}$");
 
    /**
     * 获取所有员工列表
     */
    public List<EmployeeResponse> findAllEmployees() {
        List<Employee> employees = employeeRepository.findAll();
        return employees.stream()
                .map(EmployeeResponse::new)
                .collect(Collectors.toList());
    }
 
    /**
     * 分页查询员工列表,支持名称搜索
     */
    public Page<EmployeeResponse> findEmployees(String name, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Employee> employeePage = employeeRepository.findByNameContainingOrderByCreateTimeDesc(name, pageable);
        return employeePage.map(EmployeeResponse::new);
    }
 
    /**
     * 根据名称搜索员工
     */
    public List<EmployeeResponse> searchByName(String name) {
        if (name == null || name.trim().isEmpty()) {
            return findAllEmployees();
        }
        List<Employee> employees = employeeRepository.findByNameContaining(name.trim());
        return employees.stream()
                .map(EmployeeResponse::new)
                .collect(Collectors.toList());
    }
 
    /**
     * 根据ID获取员工详情
     */
    public EmployeeResponse findById(Long id) {
        Optional<Employee> employee = employeeRepository.findById(id);
        if (employee.isPresent()) {
            return new EmployeeResponse(employee.get());
        }
        throw new BusinessException("EMPLOYEE_NOT_FOUND", "员工不存在");
    }
 
    /**
     * 保存员工(新增或更新)
     */
    public EmployeeResponse saveEmployee(EmployeeInput input) {
        // 验证输入
        validateEmployeeInput(input);
 
        Employee employee;
        if (input.getId() != null) {
            // 更新员工
            employee = employeeRepository.findById(input.getId())
                    .orElseThrow(() -> new BusinessException("EMPLOYEE_NOT_FOUND", "员工不存在"));
            
            // 检查手机号是否被其他员工使用
            if (employeeRepository.existsByPhoneAndIdNot(input.getPhone(), input.getId())) {
                throw new BusinessException("PHONE_ALREADY_EXISTS", "手机号已被其他员工使用");
            }
        } else {
            // 新增员工
            if (employeeRepository.existsByPhone(input.getPhone())) {
                throw new BusinessException("PHONE_ALREADY_EXISTS", "手机号已存在");
            }
            employee = new Employee();
            employee.setUserId(1L); // 临时设置,实际应该从当前登录用户获取
        }
 
        // 设置基本信息
        employee.setName(input.getName());
        employee.setPhone(input.getPhone());
        employee.setRoleId(input.getRoleId());
        employee.setDescription(input.getDescription());
 
        // 处理密码
        if (input.getPassword() != null && !input.getPassword().trim().isEmpty()) {
            employee.setPassword(passwordEncoder.encode(input.getPassword()));
        }
 
        Employee savedEmployee = employeeRepository.save(employee);
        logger.info("员工保存成功: {}", savedEmployee.getName());
        
        return new EmployeeResponse(savedEmployee);
    }
 
    /**
     * 删除员工(软删除)
     */
    public boolean deleteEmployee(Long id) {
        Optional<Employee> employee = employeeRepository.findById(id);
        if (employee.isPresent()) {
            Employee emp = employee.get();
            emp.setState(0); // 软删除
            employeeRepository.save(emp);
            logger.info("员工删除成功: {}", emp.getName());
            return true;
        }
        return false;
    }
 
    /**
     * 验证员工输入数据
     */
    private void validateEmployeeInput(EmployeeInput input) {
        if (input.getName() == null || input.getName().trim().isEmpty()) {
            throw new BusinessException("NAME_REQUIRED", "员工姓名不能为空");
        }
 
        if (input.getPhone() == null || input.getPhone().trim().isEmpty()) {
            throw new BusinessException("PHONE_REQUIRED", "手机号不能为空");
        }
 
        if (input.getRoleId() == null || input.getRoleId().trim().isEmpty()) {
            throw new BusinessException("ROLE_REQUIRED", "角色不能为空");
        }
 
        // 新增员工时密码必填
        if (input.getId() == null) {
            if (input.getPassword() == null || input.getPassword().trim().isEmpty()) {
                throw new BusinessException("PASSWORD_REQUIRED", "密码不能为空");
            }
        }
 
        // 如果提供了密码,验证密码格式
        if (input.getPassword() != null && !input.getPassword().trim().isEmpty()) {
            if (!PASSWORD_PATTERN.matcher(input.getPassword()).matches()) {
                throw new BusinessException("INVALID_PASSWORD_FORMAT", "密码至少6个字符,必须包含字母和数字");
            }
        }
 
        // 验证手机号格式
        if (!isValidPhone(input.getPhone())) {
            throw new BusinessException("INVALID_PHONE_FORMAT", "手机号格式不正确");
        }
    }
 
    /**
     * 验证手机号格式
     */
    private boolean isValidPhone(String phone) {
        if (phone == null) return false;
        // 简单的手机号验证:11位数字
        return phone.matches("^1[3-9]\\d{9}$");
    }
}