package com.erp.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.erp.user.entity.User;
import com.erp.user.repository.UserRepository;
import com.erp.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 用户服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserRepository, User> implements UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    @Override
    public List<User> listUsers(Long tenantId, String username, Integer page, Integer size) {
        // 计算分页
        int offset = (page - 1) * size;
        
        if (tenantId != null && StringUtils.hasText(username)) {
            return userRepository.findByTenantIdAndUsername(tenantId, username, (long) offset, size);
        }
        
        // 使用MyBatis Plus查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(User::getDeletedAt);
        
        if (tenantId != null) {
            queryWrapper.eq(User::getTenantId, tenantId);
        }
        
        if (StringUtils.hasText(username)) {
            queryWrapper.like(User::getUsername, username);
        }
        
        queryWrapper.orderByDesc(User::getId);
        queryWrapper.last("LIMIT " + offset + ", " + size);
        
        return userRepository.selectList(queryWrapper);
    }
    
    @Override
    public User getUserById(Long id) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, id)
                   .isNull(User::getDeletedAt);
        return userRepository.selectOne(queryWrapper);
    }
    
    @Override
    @Transactional
    public User createUser(User user) {
        // 验证用户名唯一性
        User existingUser = findByUsername(user.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在: " + user.getUsername());
        }
        
        // 验证邮箱唯一性
        if (StringUtils.hasText(user.getEmail())) {
            existingUser = findByEmail(user.getEmail());
            if (existingUser != null) {
                throw new RuntimeException("邮箱已存在: " + user.getEmail());
            }
        }
        
        // 加密密码
        if (StringUtils.hasText(user.getPassword())) {
            user.setPasswordHash(passwordEncoder.encode(user.getPassword()));
        }
        
        // 设置默认值
        if (user.getStatus() == null) {
            user.setStatus(1); // 默认启用
        }
        
        if (user.getTenantId() == null) {
            user.setTenantId(0L); // 默认租户ID
        }
        
        if (user.getSuperAdmin() == null) {
            user.setSuperAdmin(false); // 默认非超级管理员
        }
        
        // 保存用户
        userRepository.insert(user);
        log.info("用户创建成功: id={}, username={}", user.getId(), user.getUsername());
        
        return user;
    }
    
    @Override
    @Transactional
    public User updateUser(User user) {
        User existingUser = getUserById(user.getId());
        if (existingUser == null) {
            throw new RuntimeException("用户不存在: " + user.getId());
        }
        
        // 如果更新了密码，需要重新加密
        if (StringUtils.hasText(user.getPassword()) && 
            !user.getPassword().equals(existingUser.getPasswordHash())) {
            user.setPasswordHash(passwordEncoder.encode(user.getPassword()));
        } else {
            // 保持原密码
            user.setPasswordHash(existingUser.getPasswordHash());
        }
        
        // 更新用户
        userRepository.updateById(user);
        log.info("用户更新成功: id={}", user.getId());
        
        return getUserById(user.getId());
    }
    
    @Override
    @Transactional
    public void deleteUser(Long id) {
        User user = getUserById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在: " + id);
        }
        
        // 逻辑删除
        user.setDeletedAt(LocalDateTime.now());
        userRepository.updateById(user);
        log.info("用户删除成功: id={}, username={}", id, user.getUsername());
    }
    
    @Override
    @Transactional
    public User toggleUserStatus(Long id) {
        User user = getUserById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在: " + id);
        }
        
        // 切换状态
        Integer newStatus = user.getStatus() == 1 ? 0 : 1;
        user.setStatus(newStatus);
        userRepository.updateById(user);
        
        log.info("用户状态切换成功: id={}, username={}, newStatus={}", 
                id, user.getUsername(), newStatus);
        
        return getUserById(id);
    }
    
    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    
    @Override
    public User findByEmail(String email) {
        return userRepository.findByEmail(email);
    }
    
    @Override
    public boolean verifyPassword(User user, String password) {
        if (user == null || !StringUtils.hasText(password)) {
            return false;
        }
        return passwordEncoder.matches(password, user.getPassword());
    }
}