package com.td.boss.filter;


import com.td.boss.common.pojo.Result;
import com.td.boss.config.enums.ResultEnum;
import com.td.boss.util.JsonUtils;
import com.td.boss.util.JwtTokenUtil;
import com.td.boss.util.TokenRequestWrapper;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author:slambb
 * @date:2021/03/27
 */
@Slf4j
public class gameFilter implements Filter {
    @Value("${jwt.token}")
    private String tokenHeader;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //处理跨域请求
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept , Authorization");
//        log.info("********进入过滤器********");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String method = req.getMethod();
        if (method.equals("OPTIONS")) {
            response.setStatus(200);
            response.flushBuffer();
            return;
        }
        String token = req.getHeader(tokenHeader);
        String path = req.getServletPath();
        //登录，获取验证码，不用登录的接口
        if (!(path.indexOf("game") > -1) || path.indexOf("loginToken") > -1) {
            //登录情况直接放行
            filterChain.doFilter(servletRequest, response);
            return;
        }
        if (null == token || token.isEmpty() || !token.startsWith("Bearer ")) {
            //没有token信息
            response.setCharacterEncoding("utf-8");
            response.getWriter().print( JsonUtils.toJson (Result.of(null,false,ResultEnum.TOKEN_DOES_NOT_EXIST.getMessage(),ResultEnum.TOKEN_DOES_NOT_EXIST.getCode())));
            return;
        } else {
            String authToken = token.substring(7);
            try {
                String userId = jwtTokenUtil.getUserIdFromToken(authToken);
                log.info("userId:{}", userId);
                //todo 后面需要校验时间，加入可切换 secret 校验
                log.info("validateToken:{}", jwtTokenUtil.validateToken(authToken, userId));
                if (!StringUtils.isEmpty(userId)) {
                    filterChain.doFilter(new TokenRequestWrapper((HttpServletRequest) servletRequest, userId), response);
                } else {
                    //不存在用户信息
                    response.setCharacterEncoding("utf-8");
                    response.getWriter().print(JsonUtils.toJson(Result.of(authToken,false,ResultEnum.TOKEN_DOES_NOT_HAVE_USER_ID.getMessage(),ResultEnum.TOKEN_DOES_NOT_HAVE_USER_ID.getCode())));
                }
            } catch (ExpiredJwtException e) {
                //token过期
                response.setCharacterEncoding("utf-8");
                response.getWriter().print(JsonUtils.toJson(Result.of(null,false,ResultEnum.TOKEN_OUT_OF_DATE.getMessage(), ResultEnum.TOKEN_OUT_OF_DATE.getCode())));
            }

        }

    }
}
