package com.jiayue.ssi.filter;

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

import javax.servlet.FilterChain;
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.backenum.AuditType;
import com.jiayue.ssi.backenum.BusinessStatus;
import com.jiayue.ssi.backenum.BusinessType;
import com.jiayue.ssi.constant.CacheConstants;
import com.jiayue.ssi.constant.Constants;
import com.jiayue.ssi.constant.LoginConstants;
import com.jiayue.ssi.dto.UserVisitInfoDto;
import com.jiayue.ssi.entity.SysOperLog;
import com.jiayue.ssi.entity.SysPolicy;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.factory.LoginFactory;
import com.jiayue.ssi.factory.OperateLogFactory;
import com.jiayue.ssi.service.SysPolicyService;
import com.jiayue.ssi.service.SysUserService;
import com.jiayue.ssi.service.impl.UserServiceImpl;
import com.jiayue.ssi.util.*;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * jwt过滤器
 *
 * @author xsl
 * @since 2023/02/20
 **/
@RequiredArgsConstructor
@Order(12)
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private String defaultFilterProcessUrl = "/user/login";

    UserServiceImpl userServiceImpl;
    JwtTokenUtil jwtTokenUtil;
    SysUserService sysUserService;
    SysPolicyService sysPolicyService;

    public JwtAuthenticationTokenFilter(UserServiceImpl userServiceImpl, JwtTokenUtil jwtTokenUtil,SysUserService sysUserService,SysPolicyService sysPolicyService) {
        this.userServiceImpl = userServiceImpl;
        this.jwtTokenUtil = jwtTokenUtil;
        this.sysUserService = sysUserService;
        this.sysPolicyService = sysPolicyService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws
            ServletException, IOException {
//        SecurityContextHolder.getContext().getAuthentication();
        if (!request.getRequestURI().equals("/getVerifyCode")) {

            String token = request.getHeader("Authorization");
            if (!StringUtils.isEmpty(token)) {
                String username = "";
                try {
                    Claims claims = jwtTokenUtil.getClaimsFromToken(token);
                    if (claims == null) {
                        // 无效token
                        ResponseInfo.doResponse(response, "令牌无效，请重新登录！", 406);
                        return;
                    }

                    username = claims.getSubject();
                    if (username != null) {
                        if (CacheConstants.LOGIN_TOKEN_MAP.get(username) == null) {
                            String killIp = IPUtils.getIpAddr(request);
                            CacheConstants.IP_USER_MAP.remove(killIp);
                            ResponseInfo.doResponse(response, "令牌无效，请重新登录！", 406);
                            return;
                        } else {
                            String cacheToken = CacheConstants.LOGIN_TOKEN_MAP.get(username);
                            //内存token和当前token一致  说明是当前登陆用户访问
                            if (!token.equals(cacheToken)) {
                                String killIp = IPUtils.getIpAddr(request);
                                CacheConstants.IP_USER_MAP.remove(killIp);
                                ResponseInfo.doResponse(response, "账号已在另一台机器登录，请重新登录！", 406);
                                return;
                            }
                        }
                    }

                    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                        UserDetails userDetails = userServiceImpl.loadUserByUsername(username);
                        SysUser user = (SysUser) userDetails;
                        if (user.getStatus().equals("2")) {
                            ResponseInfo.doResponse(response, "账号已注销，不能登录！", 406);
                            return;
                        }
                        if (user.getExpDate() != null) {
                            // 判断账号截止日期
                            Date lastDate = DateUtils.getDayLastTime(user.getExpDate());
                            if (new Date().after(lastDate)) {
                                if ("0".equals(user.getStatus())) {
                                    // 将正常状态变为锁定
//                            user.setLockTime(System.currentTimeMillis());
                                    user.setStatus("1");
                                    Boolean bo = sysUserService.updateUser(user);
                                    if (!bo) {
                                        log.info(user.getUsername() + "账号已过有效期被锁定失败");
                                    } else {
                                        log.info(user.getUsername() + "账号已过有效期被锁定成功");
                                    }
                                }
                                ResponseInfo.doResponse(response, "账号已过有效期被锁定，请联系管理员！", 406);
                                return;
                            }
                        }
                        if ("1".equals(user.getStatus()) && user.getLockTime() == 0) {
                            ResponseInfo.doResponse(response, "账号长期未使用被系统锁定，请联系管理员解锁！", 406);
                            return;
                        }
                        if (jwtTokenUtil.validateToken(token, userDetails)) {
                            final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
                            String ip = IPUtils.getIpAddr(request);
                            // token加入缓存，用于并发会话处理
                            UserVisitInfoDto userVisitInfoDto = new UserVisitInfoDto();
                            userVisitInfoDto.setUsername(username);
                            userVisitInfoDto.setVtime(System.currentTimeMillis());
                            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);

                            // 将用户信息存入 authentication，方便后续校验
                            UsernamePasswordAuthenticationToken
                                    authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                            // 将 authentication 存入 ThreadLocal，方便后续获取用户信息
                            SecurityContextHolder.getContext().setAuthentication(authentication);
                        }
                    }
                } catch (ExpiredJwtException expiredJwtException) {
                    Claims claims = expiredJwtException.getClaims();
                    String cacheToken = CacheConstants.LOGIN_TOKEN_MAP.get(username);
                    //内存token和当前token一致  说明是当前登陆用户访问
                    if (cacheToken != null && !token.equals(cacheToken)) {
                        ResponseInfo.doResponse(response, "账号已在另一台机器登录，请重新登录！", 406);
                        return;
                    } else {
                        // 登录连接超时，保存审计
//                        LoginFactory.recordLogininfor(claims.getSubject(), Constants.LOGIN_FAIL, "连接超时");
                        // 将token存储内存中，便于重复登录比对
                        CacheConstants.LOGIN_TOKEN_MAP.remove(claims.getSubject());
                        LoginConstants.sessionMap.remove(claims.getSubject());
                        ResponseInfo.doResponse(response, "令牌无效，请重新登录！", 406);
                        return;
                    }
                }

                // 先判断非活动时长
                if (LocalCache.get(CacheConstants.REACTIVE_KEY + token) == null) {
                    ResponseInfo.doResponse(response, "超出非活动时长退出！", 406);
                    return;
                } else {
                    Long lastOperTime = (Long) LocalCache.get(CacheConstants.REACTIVE_KEY + token);
                    // 获取非活动配置值
                    SysPolicy sysPolicy = sysPolicyService.getOne(new QueryWrapper<>());
                    Long expiration = sysPolicy.getInactiveLogout().longValue() * 1000 * 60L;
                    if (System.currentTimeMillis() > lastOperTime + expiration) {
                        SysOperLog operLog = new SysOperLog();
                        operLog.setStatus(BusinessStatus.FAIL.ordinal());
                        // 请求的地址
                        String ip = IPUtils.getIpAddr();
                        operLog.setOperIp(ip);
                        String operUrl = org.apache.commons.lang3.StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255);
                        operLog.setOperUrl(operUrl);
                        operLog.setOperatorType(1);
                        operLog.setOperName(username);
                        // 设置请求方式
                        operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
                        operLog.setCreateBy(username);
                        // 设置action动作
                        operLog.setBusinessType(BusinessType.CTO.ordinal());
                        // 设置标题
                        operLog.setTitle("连接超时");
                        // 操作描述
                        operLog.setOperdesc("超出非活动时长");
                        // 审计类型
                        operLog.setAuditType(AuditType.SYS.ordinal());
                        // 保存数据库
                        OperateLogFactory.recordOper(operLog);

                        SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                        // 设置用户离线状态
                        sysUser.setOnlineStatus("1");
                        sysUserService.updateUser(sysUser);
                        CacheConstants.LOGIN_TOKEN_MAP.remove(sysUser.getUsername());
                        LoginConstants.sessionMap.remove(sysUser.getUsername());
                        Iterator<Map.Entry<String, String>> countMap = CacheConstants.IP_USER_MAP.entrySet().iterator();
                        while (countMap.hasNext()) {
                            Map.Entry<String, String> entry1 = countMap.next();
                            String cacheusername = entry1.getValue();
                            if (cacheusername.equals(sysUser.getUsername())) {
                                countMap.remove();
                            }
                        }
                        LocalCache.remove(CacheConstants.REACTIVE_KEY + token);
                        // 超出配置设定值则退出
                        ResponseInfo.doResponse(response, "超出非活动时长退出！", 406);
                        return;
                    } else {
                        LocalCache.set(CacheConstants.REACTIVE_KEY + token, System.currentTimeMillis(), 1000 * 60 * 60);
                    }
                }
            } else {
                if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
                    String currentIp = IPUtils.getIpAddr();
                    String ip = CacheConstants.IP_USER_MAP.get(currentIp);
                    if (ip != null && !"".equals(ip)) {
                        // 判断当前访问的ip是否已经存在，如果存在则不让任何用户访问
                        ResponseInfo.doResponse(response, "您的客户端用户正在使用，请等待一小会登录系统！", 405);
                        return;
                    }

                    // 判断并发会话数是否满足
                    SysPolicy sysPolicy = sysPolicyService.getOne(new QueryWrapper<>());
                    if (LoginConstants.sessionMap.size() + 1 > sysPolicy.getBfhhs()) {
                        ResponseInfo.doResponse(response, "系统会话数已满,不能登录！", 401);
                        return;
                    }
                    // 用户名密码登录提交，判断账号有效期
                    try {
                        UserDetails userDetails = userServiceImpl.loadUserByUsername(request.getParameter("username"));
                        SysUser user = (SysUser) userDetails;
                        if (user.getStatus().equals("2")) {
                            ResponseInfo.doResponse(response, "账号已注销，不能登录！", 406);
                            return;
                        }
                        if (user.getExpDate() != null) {
                            // 判断账号截止日期
                            Date lastDate = DateUtils.getDayLastTime(user.getExpDate());
                            if (new Date().after(lastDate)) {
                                if ("0".equals(user.getStatus())) {
                                    // 将正常状态变为锁定
//                                user.setLockTime(System.currentTimeMillis());
                                    user.setStatus("1");
                                    Boolean bo = sysUserService.updateUser(user);
                                    if (!bo) {
                                        log.info(user.getUsername() + "账号已过有效期被锁定失败");
                                    } else {
                                        log.info(user.getUsername() + "账号已过有效期被锁定成功");
                                    }
                                }
                                ResponseInfo.doResponse(response, "账号已过有效期被锁定，请联系管理员！", 406);
                                return;
                            }
                        }

                        if ("1".equals(user.getStatus()) && user.getLockTime() == 0) {
                            ResponseInfo.doResponse(response, "账号长期未使用被系统锁定，请联系管理员解锁！", 406);
                            return;
                        }

                    } catch (Exception e) {
                        ResponseInfo.doResponse(response, "用户名或密码错误！", 406);
                        return;
                    }
                }
            }
        }
        chain.doFilter(request, response);
    }
}
