package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import com.ruoyi.common.exception.user.*;
import com.ruoyi.framework.security.authentication.SmsCodeAuthenticationToken;
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.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;

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

    @Resource
    private AuthenticationManager authenticationManager;

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

    @Autowired
    private ISysConfigService configService;

    /**
     * 登录验证
     * 
     * @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);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                //异步记录登录失败日志
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            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)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public String backstageLoginPassword(String username, String password){

        System.out.println("backstageLoginPassword"+username+password);

        loginPreCheck(username, password);

        Authentication authentication = null;
        try
        {
//            创建UsernamePasswordAuthenticationToken对象 用于封装用户名和密码 作为认证的凭证，'UsernamePasswordAuthenticationToken'是spring security存储认证请求信息的标准类
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
//            设置认证上下文
            AuthenticationContextHolder.setContext(authenticationToken);
            /**
             *  调用authenticationManager进行认证
             *  该方法会通过传入的'authenticationToken'进行用户认证
              */

            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();
        }


        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        String userType = loginUser.getUser().getUserType();

        String userStatus = loginUser.getUser().getStatus();

        System.out.println("用户类型:"+userType);

        if (userType.equals(Constants.COMMON_USER)){
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "user.login.not.authority"));
            throw new ServiceException("无后台访问权限");

        }
        if (userStatus.equals("1")){
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "user.login.not.authority"));
            throw new ServiceException("账号已停用");

        }

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);

    }


    public String appLoginPassword(String username, String password) {
        // APP端验证码校验
//        appvalidateCaptcha(username, code, phone);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
//        用于存储最终的认证信息 初始化null
        Authentication authentication = null;
        try
        {
//            创建UsernamePasswordAuthenticationToken对象 用于封装用户名和密码 作为认证的凭证，'UsernamePasswordAuthenticationToken'是spring security存储认证请求信息的标准类
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
//            设置认证上下文
            AuthenticationContextHolder.setContext(authenticationToken);
            /**
             *  调用authenticationManager进行认证
             *  该方法会通过传入的'authenticationToken'进行用户认证
              */

            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);
    }

    public String backstageLoginMessage(String username, String code,String phone) {

        appvalidateCaptcha(username, code, phone);

        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsByPhonenumberServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new SmsCodeAuthenticationToken(phone));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone,
                        Constants.LOGIN_FAIL, MessageUtils.message("account.not.incorrect")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone,
                        Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }

        // 获取登录人信息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        String userType = loginUser.getUser().getUserType();
        String userStatus = loginUser.getUser().getStatus();

        if(userType.equals(Constants.COMMON_USER)){
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "user.login.not.authority"));
            throw new ServiceException("无后台访问权限");
        }
        if (userStatus.equals("1")){
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "user.login.not.authority"));
            throw new ServiceException("账号已停用");
//            return ;
        }


        // 执行异步任务，记录登录信息
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone,
                Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));

        // 修改最近登录IP和登录时间
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);


    }


    /**
     *
     * @param username
     * @param code
     * @return
     */
    public String appLoginMessage(String username, String code,String phone) {
        // APP端验证码校验
        appvalidateCaptcha(username, code, phone);
        // 登录前置校验
//        loginPreCheck(username, password);
        // 用户验证
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsByPhonenumberServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new SmsCodeAuthenticationToken(phone));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone,
                        Constants.LOGIN_FAIL, MessageUtils.message("account.not.incorrect")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone,
                        Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        // 执行异步任务，记录登录信息
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone,
                Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        // 获取登录人信息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 修改最近登录IP和登录时间
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }



    /**
     * app端校验验证码
     *
     * @param username 用户名
     * @param code 验证码
     * @param phone 唯一标识 手机号
     * @return 结果
     */
    private void appvalidateCaptcha(String username, String code, String phone) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + phone;
            String captcha = redisCache.getCacheObject(verifyKey);

            // 尝试次数
            String countKey = CacheConstants.CAPTCHA_CODE_KEY_COUNT + phone;
            int captchaCount = redisCache.getCacheObject(countKey);

            if(captchaCount >= 3){
                // 删除缓存
                redisCache.deleteObject(verifyKey);

                // 验证码失效
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaDisableException();
            }

            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaDisableException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                // 尝试次数加1
                redisCache.setCacheObject(countKey, captchaCount + 1);
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
            else{
                // 登录成功删除验证码
                redisCache.deleteObject(verifyKey);
            }
        }

    }


}
