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

import com.yunfeiyun.agmp.common.constant.Constants;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.exception.BizException;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseUser;
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.SecurityUtils;
import com.yunfeiyun.agmp.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

/**
 * 登录密码方法
 * 
 * @author 杨晓辉
 */
@Component
public class SysPasswordService
{
    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime}")
    private int lockTime;



    public void validate(IBaseUser user)
    {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();

        Integer retryCount = SpringUtils.getBean(RedisCacheManager.class).getCacheObject(RedisCacheKey.SYS_PWD_ERR_CNT_KEY,username);

        if (retryCount == null)
        {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,   "密码输入错误" + maxRetryCount  +"次，帐户锁定" + lockTime + "分钟"));
            String strError = "密码输入错误{" + maxRetryCount + "}次，帐户锁定" + lockTime + "分钟";
            throw new BizException( ErrorCode.UNAUTHORIZED_ERROR.getCode(), strError);
        }

        if (!matches(user, password))
        {
            retryCount = retryCount + 1;
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "密码输入错误" + retryCount + "次" ));
            SpringUtils.getBean(RedisCacheManager.class).setCacheObject(RedisCacheKey.SYS_PWD_ERR_CNT_KEY,username, retryCount, lockTime, TimeUnit.MINUTES);
            throw new BizException(ErrorCode.USERPWD_EMPTY_ERROR.getCode(),ErrorCode.USERPWD_EMPTY_ERROR.getMessage());
        }
        else
        {
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(IBaseUser user, String rawPassword)
    {
        return SecurityUtils.matchesPassword(rawPassword, user.getUserLoginpwd());
    }

    public void clearLoginRecordCache(String loginName)
    {
        if (SpringUtils.getBean(RedisCacheManager.class).hasKey(RedisCacheKey.SYS_PWD_ERR_CNT_KEY,loginName))
        {
            SpringUtils.getBean(RedisCacheManager.class).deleteObject(RedisCacheKey.SYS_PWD_ERR_CNT_KEY,loginName);
        }
    }
}
