package com.jiayue.center.handler;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jiayue.center.config.SendMailUtil;
import com.jiayue.center.constant.CacheConstants;
import com.jiayue.center.constant.Constants;
import com.jiayue.center.constant.LoginConstants;
import com.jiayue.center.constant.SecretKeyConstants;
import com.jiayue.center.dto.ActiveUserDto;
import com.jiayue.center.dto.UserVisitInfoDto;
import com.jiayue.center.factory.LoginFactory;
import com.jiayue.center.service.SysAlarmService;
import com.jiayue.center.service.SysPolicyService;
import com.jiayue.center.service.SysUserService;
import com.jiayue.center.util.*;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.jiayue.center.entity.SysUser;

import cn.hutool.json.JSONUtil;

/**
* 成功认证处理
* @author xsl
* @date 2023/2/16
*/
@Component("customAuthenticationSuccessHandler")
@Slf4j
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysPolicyService sysPolicyService;
    @Autowired
    SendMailUtil sendMailUtil;
    @Autowired
    SysAlarmService sysAlarmService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        // 验证码验证
        String username = request.getParameter("username");
        // 删除缓存邮箱口令
        LocalCache.remove(CacheConstants.MAIL_CODE_KEY + username);
        LocalCache.remove(CacheConstants.PREVENT_MAIL_CODE + username);
        SysUser sysUser = (SysUser) authentication.getPrincipal();
        sysUser.setErrNum(0);
        sysUser.setLockTime(0L);
        sysUser.setStatus("0");
        sysUser.setOnlineStatus("0");
        // 加入登录IP和时间
        String ip = IPUtils.getIpAddr(request);
        sysUser.setLoginIp(ip);
        sysUser.setLoginDate(new Date());
        sysUserService.updateUser(sysUser);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        CacheConstants.usernamePasswordMap.put(username,request.getParameter("password"));

        // 记录用户登录日志
        LoginFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");

        String token = jwtTokenUtil.generateToken(sysUser);
        // 访问时间
        Long vtime = System.currentTimeMillis();
        // token加入缓存，用于并发会话处理
        UserVisitInfoDto userVisitInfoDto = new UserVisitInfoDto();
        userVisitInfoDto.setUsername(username);
        userVisitInfoDto.setVtime(vtime);
        userVisitInfoDto.setIp(ip);
        userVisitInfoDto.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        userVisitInfoDto.setBrowser(browser);
        userVisitInfoDto.setOs(os);
        LoginConstants.sessionMap.put(username,userVisitInfoDto);

        CacheConstants.LOGIN_TOKEN_MAP.put(username,token);
        // 登录成功后将用户本次操作时间存入缓存，为了判断非活动退出时应用,60分钟自动失效
        LocalCache.set(CacheConstants.REACTIVE_KEY + token,vtime,1000*60*60);
        ActiveUserDto activeUserDto = new ActiveUserDto();
        activeUserDto.setSysUser(sysUser);
        activeUserDto.setHttpServletRequest(request);
        activeUserDto.setLoginTime(System.currentTimeMillis());
//        CacheConstants.ACTIVE_USER_MAP.put(username,activeUserDto);
        CacheConstants.KICKED_USER_MAP.put(username,request);
        String obj = JSONUtil.toJsonStr(ResponseVO.success(token));
        // token加密处理
        String encrypt = SM2CryptUtils.encrypt(obj, SecretKeyConstants.CLIENT_PUBLIC_KEY);
        // token签名
        String signStr = SM2CryptUtils.sign(SecretKeyConstants.SERVER_PRIVATE_KEY,obj);
        String secretResult = "jy="+encrypt+"&jySign="+signStr;
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setStatus(200);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(secretResult);
    }


}
