package com.yunfeiyun.agmp.common.web.system.service;

import com.yunfeiyun.agmp.common.constant.Constants;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.constant.UserConstants;
import com.yunfeiyun.agmp.common.exception.BizException;
import com.yunfeiyun.agmp.common.exception.SsoException;
import com.yunfeiyun.agmp.common.framework.web.service.ISysUserService;
import com.yunfeiyun.agmp.common.framework.web.service.TokenService;
import com.yunfeiyun.agmp.common.core.domain.entity.SysUser;
import com.yunfeiyun.agmp.common.core.domain.model.LoginUser;
import com.yunfeiyun.agmp.common.enums.RedisCacheKey;
import com.yunfeiyun.agmp.common.framework.manager.AsyncFactory;
import com.yunfeiyun.agmp.common.framework.manager.AsyncManager;
import com.yunfeiyun.agmp.common.framework.manager.RedisCacheManager;
import com.yunfeiyun.agmp.common.framework.security.context.AuthenticationContextHolder;
import com.yunfeiyun.agmp.common.utils.DateUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.common.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;
import javax.annotation.Resource;

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

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCacheManager redisCacheManager;
    
    @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, "用户不存在/密码错误"));
                throw new BizException(ErrorCode.PASSWORD_ERROR.getCode() ,ErrorCode.PASSWORD_ERROR.getMessage());
            } else if(e instanceof BizException){
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "用户不存在/密码错误"));
                throw new BizException(((BizException) e).getCode() , ((BizException) e).getMsg());
            }else if(e instanceof SsoException){
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "用户不存在/密码错误"));
                throw new BizException(((SsoException) e).getCode() , ((SsoException) e).getMessage());
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new BizException(ErrorCode.PASSWORD_ERROR.getCode(),ErrorCode.PASSWORD_ERROR.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.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 = StringUtils.nvl(uuid, "");
            String captcha = redisCacheManager.getCacheObject(RedisCacheKey.CAPTCHA_CODE_KEY,verifyKey);
            redisCacheManager.deleteObject(RedisCacheKey.CAPTCHA_CODE_KEY,verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "验证码已失效"));
                throw new BizException(ErrorCode.VERIFYCODE_LOGIN_ERROR.getCode() , ErrorCode.VERIFYCODE_LOGIN_ERROR.getMessage());
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "验证码错误"));
                throw new BizException(ErrorCode.VERIFYCODE_LOGIN_ERROR.getCode() , ErrorCode.VERIFYCODE_LOGIN_ERROR.getMessage());
            }
        }
    }

    /**
     * 登录前置校验
     * @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, "* 必须填写"));
            throw new BizException(ErrorCode.USERPWD_EMPTY_ERROR.getCode() , ErrorCode.USERPWD_EMPTY_ERROR.getMessage());
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "用户不存在/密码错误"));
            throw new BizException(ErrorCode.PWD_UNRANGE_ERROR.getCode() , ErrorCode.PWD_UNRANGE_ERROR.getMessage());
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "用户不存在/密码错误"));
            throw new BizException(ErrorCode.PWD_UNRANGE_ERROR.getCode() , ErrorCode.PWD_UNRANGE_ERROR.getMessage());
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单"));
            throw new BizException(ErrorCode.IP_INBLACKLIST_ERROR.getCode() , ErrorCode.IP_INBLACKLIST_ERROR.getMessage());
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(String userId)
    {
        SysUser sysUser = new SysUser("");
        sysUser.setUserId(userId);
        sysUser.setUserLastloginip(IpUtils.getIpAddr());
        sysUser.setUserLastlogindate(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss").toString());
        userService.updateUserProfile(sysUser);
    }
}
