package com.jiayue.ssi.handler;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
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.LoginConstants;
import com.jiayue.ssi.constant.SecretKeyConstants;
import com.jiayue.ssi.dto.ActiveUserDto;
import com.jiayue.ssi.dto.UserVisitInfoDto;
import com.jiayue.ssi.entity.SysLogininfor;
import com.jiayue.ssi.entity.SysPolicy;
import com.jiayue.ssi.factory.LoginFactory;
import com.jiayue.ssi.service.SysAlarmService;
import com.jiayue.ssi.service.SysLogininforService;
import com.jiayue.ssi.service.SysPolicyService;
import com.jiayue.ssi.service.SysUserService;
import com.jiayue.ssi.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.ssi.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);

        // 将token存储内存中，便于重复登录比对
        if (CacheConstants.LOGIN_TOKEN_MAP.get(username)!=null){
            // 将之前用户登录过的ip删除掉
            Iterator<Map.Entry<String, String>> countMap = CacheConstants.IP_USER_MAP.entrySet().iterator();
            String kickedIp = "";
            while (countMap.hasNext()) {
                Map.Entry<String, String> entry = countMap.next();
                String cacheusername = entry.getValue();
                if (cacheusername.equals(username)){
                    kickedIp = entry.getKey();
                    countMap.remove();
                }
            }
            // 之前有用户登录过，本次将上次用户踢出下线。并通知管理员
            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)){
                log.info("发送邮箱多点登录\r\n" +
                        "↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓邮箱内容↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓"+
                        "\r\n  账号："+sysUser.getUsername()+"多点登录,本次登录时间："+DateUtils.getTime()+",登录IP:"+IPUtils.getIpAddr(request)+" \r\n"     +
                        "↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑邮箱内容↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");
//                log.info("发送邮箱通知系统管理员后台输出======> "+"账号【"+sysUser.getUsername()+"】多点登录","本次登录时间："+DateUtils.getTime()+",登录IP:"+IPUtils.getIpAddr(request));
//                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)){
                log.info("发送邮箱多点登录\r\n" +
                        "↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓邮箱内容↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓"+
                        "\r\n  账号："+sysUser.getUsername()+"多点登录,本次登录时间："+DateUtils.getTime()+",登录IP:"+IPUtils.getIpAddr(request)+" \r\n"     +
                        "↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑邮箱内容↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");
//                log.info("发送邮箱通知系统管理员后台输出======> "+"账号【"+sysUser.getUsername()+"】多点登录","本次登录时间："+DateUtils.getTime()+",登录IP:"+IPUtils.getIpAddr(request));
            }

            // 封装被下线的对象退出信息
            SysLogininfor logininfor = new SysLogininfor();
            logininfor.setUserName(sysUser.getUsername());
            logininfor.setIpaddr(kickedIp);
            String address = AddressUtils.getRealAddressByIP(kickedIp);
            logininfor.setLoginLocation(address);
            HttpServletRequest kickedRequest = CacheConstants.KICKED_USER_MAP.get(sysUser.getUsername());
            // 获取被踢用户的request
            final UserAgent kickedUserAgent = UserAgent.parseUserAgentString(kickedRequest.getHeader("User-Agent"));
            logininfor.setBrowser(kickedUserAgent.getBrowser().getName());
            logininfor.setOs(kickedUserAgent.getOperatingSystem().getName());
            logininfor.setMsg("退出成功");
            logininfor.setLoginTime(new Date());
            logininfor.setCreateBy(sysUser.getUsername());
            // 日志状态
            logininfor.setStatus(Constants.SUCCESS);
            // 插入数据
            SpringUtils.getBean(SysLogininforService.class).insertLogininfor(logininfor);

//            System.out.println(CacheConstants.SESSIONID_USER_MAP.toString());
//            System.out.println("被踢用户的sessionid:"+kickedRequest.getSession().getId());
//            CacheConstants.SESSIONID_USER_MAP.put(kickedRequest.getSession().getId(),sysUser.getUsername());
        }
        CacheConstants.LOGIN_TOKEN_MAP.put(username,token);
        // 登录成功后将用户本次操作时间存入缓存，为了判断非活动退出时应用,60分钟自动失效
        LocalCache.set(CacheConstants.REACTIVE_KEY + token,vtime,1000*60*60);
        // 将登录成功的用户ip加入缓存中
        CacheConstants.IP_USER_MAP.put(ip,username);
        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);
    }


}
