package com.jiayue.ssi.handler;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiayue.ssi.config.SendMailUtil;
import com.jiayue.ssi.constant.CacheConstants;
import com.jiayue.ssi.constant.Constants;
import com.jiayue.ssi.constant.SecretKeyConstants;
import com.jiayue.ssi.entity.SysAlarm;
import com.jiayue.ssi.entity.SysPolicy;
import com.jiayue.ssi.factory.LoginFactory;
import com.jiayue.ssi.service.SysAlarmService;
import com.jiayue.ssi.service.SysPolicyService;
import com.jiayue.ssi.service.SysUserService;
import com.jiayue.ssi.util.*;
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.ssi.entity.SysUser;

import cn.hutool.json.JSONUtil;

/**
* 成功认证处理
* @author xsl
* @date 2023/2/16
*/
@Component("customAuthenticationSuccessHandler")
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 {
        // 验证码验证
        String username = request.getParameter("username");
        // 删除缓存邮箱口令
        LocalCache.remove(CacheConstants.MAIL_CODE_KEY + username);
        SysUser sysUser = (SysUser) authentication.getPrincipal();
        sysUser.setErrNum(0);
        sysUser.setLockTime(0L);
        sysUser.setStatus("0");
        // 加入登录IP和时间
        sysUser.setLoginIp(IPUtils.getIpAddr(request));
        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);
        // 将token存储内存中，便于重复登录比对
        if (CacheConstants.LOGIN_TOKEN_MAP.get(username)!=null){
            // 之前有用户登录过，本次将上次用户踢出下线。并通知管理员
            String noticeWay = "";
            SysPolicy sysPolicy = sysPolicyService.getOne(new QueryWrapper<>());
            if ("0".equals(sysPolicy.getExcLevelSameUser())){
                noticeWay = sysPolicy.getExcNoticeWayA();
            } else if ("1".equals(sysPolicy.getExcLevelSameUser())){
                noticeWay = sysPolicy.getExcNoticeWayB();
            }

            // 通知系统管理员
            if ("0".equals(noticeWay)){
                List<SysUser> sysUserList = sysUserService.selectUserByRole("1");
                if (sysUserList.size()>0){
                    String[] mailArray = new String[sysUserList.size()];
                    for (int i=0;i<sysUserList.size();i++){
                        // 邮箱解密
                        mailArray[i] = AesUtils.decryptStr(sysUserList.get(i).getMailbox());
                    }
                    try {
                        // 发送邮件
                        sendMailUtil.executeSendMail(mailArray,"账号【"+sysUser.getUsername()+"】多点登录","本次登录时间："+DateUtils.getTime()+",登录IP:"+IPUtils.getIpAddr(request));
                    } catch (Exception ex) {
                        System.out.println("邮箱验证码发送失败！");
                    }
                }
            }
            else if ("1".equals(noticeWay)){
                // 告警
                SysAlarm sysAlarm = new SysAlarm();
                sysAlarm.setAlarmContent("账号【"+sysUser.getUsername()+"】多点登录");
                sysAlarm.setReadSign("0");
                // 低于策略设定值则告警
                sysAlarmService.save(sysAlarm);
            }
        }
        CacheConstants.LOGIN_TOKEN_MAP.put(username,token);

        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);
    }


}
