package com.jiayue.ssi.filter;

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

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

import com.jiayue.ssi.constant.CacheConstants;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.service.SysUserService;
import com.jiayue.ssi.service.impl.UserServiceImpl;
import com.jiayue.ssi.util.DateUtils;
import com.jiayue.ssi.util.ResponseInfo;
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;
import com.jiayue.ssi.util.JwtTokenUtil;

/**
 * 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;

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

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws
            ServletException, IOException {
        SecurityContextHolder.getContext().getAuthentication();
        String token = request.getHeader("Authorization");
        if (!StringUtils.isEmpty(token)) {
            String username = jwtTokenUtil.getUsernameFromToken(token);
            if (username != null) {
                if (CacheConstants.LOGIN_TOKEN_MAP.get(username) == null) {
                    ResponseInfo.doResponse(response, "令牌无效，请重新登录！", 403);
                    return;
                } else {
                    String cacheToken = CacheConstants.LOGIN_TOKEN_MAP.get(username);
                    //内存token和当前token一致  说明是当前登陆用户访问
                    if (!token.equals(cacheToken)) {
                        ResponseInfo.doResponse(response, "账号已在另一台机器登录，请重新登录！", 403);
                        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, "账号已注销，不能登录！", 403);
                    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, "账号已过有效期被锁定，请联系管理员！", 403);
                        return;
                    }
                }
                if (jwtTokenUtil.validateToken(token, userDetails)) {
                    // 将用户信息存入 authentication，方便后续校验
                    UsernamePasswordAuthenticationToken
                            authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    // 将 authentication 存入 ThreadLocal，方便后续获取用户信息
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        } else {
            if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
                // 用户名密码登录提交，判断账号有效期
                try {
                    UserDetails userDetails = userServiceImpl.loadUserByUsername(request.getParameter("username"));
                    SysUser user = (SysUser) userDetails;
                    if (user.getStatus().equals("2")){
                        ResponseInfo.doResponse(response, "账号已注销，不能登录！", 403);
                        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, "账号已过有效期被锁定，请联系管理员！", 403);
                            return;
                        }
                    }
                } catch (Exception e) {
                    ResponseInfo.doResponse(response, "用户名或密码错误！", 403);
                    return;
                }
            }
        }
        chain.doFilter(request, response);
    }
}
