package com.yonge.cooleshow.auth.core.handler;

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

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 com.fasterxml.jackson.databind.ObjectMapper;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.auth.api.entity.SysUserLogin;
import com.yonge.cooleshow.auth.service.SysUserLoginService;
import com.yonge.cooleshow.auth.service.SysUserService;
import com.yonge.cooleshow.common.security.SecurityConstants;

@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.queryLockByPhone(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.setLoginCount(1);
                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(9);
                    sysUser.setUpdateTime(date);
                    sysUserService.update(sysUser);
                }*/
                sysUserLoginService.update(userLogin);
            }
            logger.info("用户：{} 登录失败", sysUser.getPhone());
        }else {
            logger.info("用户：{} 不存在", username);
        }
    }
}
