package com.yushu.framework.web.service;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.yushu.common.constant.CacheConstants;
import com.yushu.common.constant.Constants;
import com.yushu.common.constant.UserConstants;
import com.yushu.common.core.domain.model.LoginUser;
import com.yushu.common.core.redis.RedisCache;
import com.yushu.common.exception.ServiceException;
import com.yushu.common.exception.user.BlackListException;
import com.yushu.common.exception.user.CaptchaException;
import com.yushu.common.exception.user.CaptchaExpireException;
import com.yushu.common.exception.user.UserNotExistsException;
import com.yushu.common.exception.user.UserPasswordNotMatchException;
import com.yushu.common.core.domain.entity.SysUser;
import com.yushu.common.utils.DateUtils;
import com.yushu.common.utils.MessageUtils;
import com.yushu.common.utils.StringUtils;
import com.yushu.common.utils.ip.IpUtils;
import com.yushu.framework.manager.AsyncManager;
import com.yushu.framework.manager.factory.AsyncFactory;
import com.yushu.framework.security.context.AuthenticationContextHolder;
import com.yushu.system.service.ISysConfigService;
import com.yushu.system.service.ISysMailService;
import com.yushu.system.service.ISysUserService;
import com.yushu.framework.web.service.UserDetailsServiceImpl;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 * 
 * @author YuShu
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysMailService mailService;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        userService.updateLoginInfo(userId, IpUtils.getIpAddr(), DateUtils.getNowDate());
    }

    /**
     * 发送邮箱验证码
     * 
     * @param email 邮箱地址
     * @return 结果
     */
    public boolean sendEmailCode(String email)
    {
        // 验证邮箱是否存在于用户列表
        SysUser user = userService.selectUserByEmail(email);
        if (user == null)
        {
            throw new ServiceException("该邮箱未绑定任何用户");
        }
        // 检查用户状态
        if (UserConstants.USER_DISABLE.equals(user.getStatus()))
        {
            throw new ServiceException("该用户已被停用");
        }
        // 生成6位数字验证码
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        // 存储到Redis，10分钟有效（与模板说明一致）
        String verifyKey = CacheConstants.EMAIL_CODE_KEY + email;
        redisCache.setCacheObject(verifyKey, code, 10, TimeUnit.MINUTES);
        // 使用模板发送邮件（配置ID=1，模板verify_code）
        java.util.Map<String, Object> variables = new java.util.HashMap<>();
        variables.put("siteName", "YUSHU SYSTEM");
        variables.put("code", code);
        variables.put("expireMinutes", "10");
        return mailService.sendMailByTemplate(1L, "verify_code", email, variables);
    }

    /**
     * 邮箱验证码登录
     * 
     * @param email 邮箱
     * @param emailCode 邮箱验证码
     * @return 令牌
     */
    public String emailLogin(String email, String emailCode)
    {
        // 验证邮箱验证码
        validateEmailCode(email, emailCode);
        // 查询用户
        SysUser user = userService.selectUserByEmail(email);
        if (user == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(email, Constants.LOGIN_FAIL, "该邮箱未绑定任何用户"));
            throw new ServiceException("该邮箱未绑定任何用户");
        }
        // 检查用户状态
        if (UserConstants.USER_DISABLE.equals(user.getStatus()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(email, Constants.LOGIN_FAIL, "用户已被停用"));
            throw new ServiceException("对不起，您的账号已被停用");
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(email, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
        // 加载用户信息
        LoginUser loginUser = (LoginUser) userDetailsService.createLoginUser(user);
        // 记录登录成功日志
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验邮箱验证码
     * 
     * @param email 邮箱
     * @param emailCode 验证码
     */
    public void validateEmailCode(String email, String emailCode)
    {
        String verifyKey = CacheConstants.EMAIL_CODE_KEY + email;
        String cachedCode = redisCache.getCacheObject(verifyKey);
        if (cachedCode == null)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(email, Constants.LOGIN_FAIL, "邮箱验证码已过期"));
            throw new ServiceException("邮箱验证码已过期，请重新获取");
        }
        redisCache.deleteObject(verifyKey);
        if (!emailCode.equalsIgnoreCase(cachedCode))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(email, Constants.LOGIN_FAIL, "邮箱验证码错误"));
            throw new ServiceException("邮箱验证码错误");
        }
    }
}

