package org.lingniu.idp.service.core;

import jakarta.annotation.Resource;
import org.lingniu.idp.common.redis.RedisCache;
import org.lingniu.idp.constant.CacheConstants;
import org.lingniu.idp.constant.Constants;
import org.lingniu.idp.constant.UserConstants;
import org.lingniu.idp.exception.ServiceException;
import org.lingniu.idp.exception.user.*;
import org.lingniu.idp.manager.AsyncManager;
import org.lingniu.idp.manager.factory.AsyncFactory;
import org.lingniu.idp.model.dto.LoginUser;
import org.lingniu.idp.security.context.AuthenticationContextHolder;
import org.lingniu.idp.service.ISysConfigService;
import org.lingniu.idp.service.ISysUserService;
import org.lingniu.idp.utils.DateUtils;
import org.lingniu.idp.utils.MessageUtils;
import org.lingniu.idp.utils.StringUtils;
import org.lingniu.idp.utils.ip.IpUtils;
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;


/**
 * 登录校验方法
 * 
 * @author portal
 */
@Component
public class CaptchaService
{
    @Autowired
    private RedisCache redisCache;


    @Autowired
    private ISysConfigService configService;

    /**
     * 校验验证码
     * 
     * @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();
            }
        }
    }

}
