package com.yfd.platform.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yfd.platform.component.ServerSendEventServer;
import com.yfd.platform.constant.Constant;
import com.yfd.platform.system.domain.LoginUser;
import com.yfd.platform.system.domain.Message;
import com.yfd.platform.system.service.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private WebConfig webConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String uri = httpServletRequest.getRequestURI();
        String token = httpServletRequest.getHeader("token");
        if (StrUtil.isEmpty(token) || "/user/login".equals(uri)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //解析token
        boolean isok = JWTUtil.verify(token, "12345678".getBytes());
        String userid = "";
        if (isok) {
            final JWT jwt = JWTUtil.parseToken(token);
            userid = jwt.getPayload("userid").toString();
            long expire_time = (Long) jwt.getPayload("expire_time");
            if (System.currentTimeMillis() > expire_time) {
                httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Token超过期限！");
                return;
            }
        }

        //从cachekey中获取用户信息
        String cachekey = "login:" + userid;
        String jsonstr = webConfig.loginuserCache().get(cachekey);
        LoginUser loginUser = JSON.parseObject(jsonstr, LoginUser.class);
        if (ObjectUtil.isEmpty(loginUser)) {
            httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "登录用户已失效！");
            return;
        }
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null,
                        loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        webConfig.loginuserCache().put(Constant.TOKEN + userid, token);
        //放行过滤器
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

}
