package com.yfd.platform.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.yfd.platform.constant.Constant;
import com.yfd.platform.system.domain.LoginUser;
import com.yfd.platform.utils.StringUtils;
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.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 {
        String referer = httpServletRequest.getHeader("referer");
        //        String serverName = httpServletRequest.getServerName();
        String serverName = StringUtils.getIpAddr(httpServletRequest);
        // 是否开启referer验证
        boolean isOpen = false;
        if (isOpen && null != referer && !referer.contains(serverName)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.putOnce("code", "1");
            jsonObject.putOnce("msg", "系统不支持当前域名的访问");
            httpServletResponse.setContentType("application/json; charset=utf-8");
            httpServletResponse.getWriter().write(jsonObject.toString());
            return;
        }
        //获取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();
            //从cachekey中获取用户信息失效时间
            String cachekey = "expire_time:" + userid;
            if (StrUtil.isNotEmpty(webConfig.loginuserCache().get(cachekey)) && false) {
                long expire_time = Long.parseLong(webConfig.loginuserCache().get(cachekey));
                if (System.currentTimeMillis() > expire_time) {
                    //                    webConfig.loginuserCache().remove("login:" + userid);
                    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);
        //更新了超期时间
        long expireTime = System.currentTimeMillis() + (30L * 60L * 1000L);
        webConfig.loginuserCache().put("expire_time:" + userid, String.valueOf(expireTime));

        //放行过滤器
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

}
