package com.ym.mec.auth.core.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.auth.api.entity.SysUserLogin;
import com.ym.mec.auth.api.enums.UserLockFlag;
import com.ym.mec.auth.config.constant.SecurityConstants;
import com.ym.mec.auth.service.SysUserLoginService;
import com.ym.mec.auth.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;

@Component
public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
    private final static Logger logger = LoggerFactory.getLogger(AuthenticationFailureListener.class);

    @Autowired
    private SysUserLoginService sysUserLoginService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent authenticationFailureBadCredentialsEvent) {
        Authentication authentication = authenticationFailureBadCredentialsEvent.getAuthentication();
        HashMap<String,String> hashMap = objectMapper.convertValue(authentication.getDetails(), HashMap.class);
        String username = authentication.getPrincipal().toString();
        Date date = new Date();
        SysUser sysUser = null;
        if(username.split(":").length > 1){
        	if(username.startsWith(SecurityConstants.USERNAME_PRINCIPAL_PREFIX)){
                sysUser = sysUserService.queryByUsername(username.split(":")[1]);
            }else {
                sysUser = sysUserService.queryByPhone(username.split(":")[1]);
            }
        }
        if(sysUser != null){
            SysUserLogin userLogin = sysUserLoginService.findLoginByUserId(sysUser.getId());
            if(userLogin == null){
                userLogin = new SysUserLogin();
                userLogin.setUserId(sysUser.getId());
                userLogin.setFailCount(0);
                userLogin.setLastLoginTime(date);
                userLogin.setLastLoginIp(hashMap.get("remoteAddress"));
                sysUserLoginService.insert(userLogin);
            }else {
                userLogin.setFailCount(userLogin.getFailCount() + 1);
                userLogin.setLastLoginTime(date);
                userLogin.setLastLoginIp(hashMap.get("remoteAddress"));
                if(userLogin.getFailCount() >= 5){
                    userLogin.setLockTime(30);
                    userLogin.setLockDate(date);
                    sysUser.setLockFlag(UserLockFlag.NORMAL);
                    sysUser.setUpdateTime(date);
                    sysUserService.update(sysUser);
                }
                sysUserLoginService.update(userLogin);
            }
            logger.info("用户：{} 登录失败", sysUser.getPhone());
        }else {
            logger.info("用户：{} 不存在", username);
        }
    }
}
