package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.entity.AdminUser;
import com.zhentao.mapper.AdminUserMapper;
import com.zhentao.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 认证服务实现
 */
@Service
public class AuthServiceImpl implements AuthService {
    
    @Autowired
    private AdminUserMapper adminUserMapper;
    
    @Autowired(required = false)
    private StringRedisTemplate redisTemplate;
    
    @Override
    public AdminUser login(String username, String password) {
        try {
            // 查询用户
            QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
            wrapper.eq("username", username);
            wrapper.eq("status", 1); // 只查询启用的用户
            
            AdminUser user = adminUserMapper.selectOne(wrapper);
            
            if (user == null) {
                return null;
            }
            
            // 验证密码（简化处理，实际项目应使用BCrypt）
            String encryptedPassword = encryptPassword(password);
            if (!user.getPassword().equals(encryptedPassword)) {
                // 兼容明文密码（测试用）
                if (!user.getPassword().equals(password)) {
                    return null;
                }
            }
            
            // 更新最后登录时间
            user.setLastLoginTime(LocalDateTime.now());
            adminUserMapper.updateById(user);
            
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public String generateToken(AdminUser user) {
        String token = UUID.randomUUID().toString().replace("-", "");
        
        // 将token存储到Redis（如果可用）
        if (redisTemplate != null) {
            try {
                String key = "admin:token:" + token;
                redisTemplate.opsForValue().set(key, String.valueOf(user.getId()), 24, TimeUnit.HOURS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        return token;
    }
    
    @Override
    public AdminUser getUserByToken(String token) {
        try {
            // 移除 Bearer 前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            // 从Redis获取用户ID
            Integer userId = null;
            if (redisTemplate != null) {
                try {
                    String key = "admin:token:" + token;
                    String userIdStr = redisTemplate.opsForValue().get(key);
                    if (userIdStr != null) {
                        userId = Integer.parseInt(userIdStr);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            
            // 如果Redis中没有，返回null
            if (userId == null) {
                return null;
            }
            
            // 查询用户信息
            return adminUserMapper.selectById(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 密码加密（简化版，实际项目应使用BCrypt）
     */
    private String encryptPassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
    }
}

