package com.YuyeTech.TPlat.aspect;

import com.YuyeTech.TPlat.VO.ResultVO;
import com.YuyeTech.TPlat.constant.RedisConstant;
import com.YuyeTech.TPlat.enums.RedisType;
import com.YuyeTech.TPlat.enums.ResultEnum;
import com.YuyeTech.TPlat.utils.JsonUtils;
import com.YuyeTech.TPlat.utils.RedisSettingMap;
import com.YuyeTech.TPlat.utils.ResultVOUtil;
import com.YuyeTech.TPlat.utils.TokenRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author:slambb
 * @date:2019/12/27
 */
@Slf4j
//@WebFilter(filterName = "authorizeFilter", urlPatterns = "/*")
public class AuthorizeFilter implements Filter {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedisSettingMap redisSettingMap;

    @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 , token");
//        log.info("********进入过滤器********");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String method = req.getMethod();
//        log.info("method:{}",method);
        if (method.equals("OPTIONS")) {
            response.setStatus(200);
            return;
        }
        String token = req.getHeader("token");
        Integer platform = req.getIntHeader("platform");

        boolean isFilter = false;
        String userId;
        String path = req.getServletPath();
        //静态资源放行
        String reg = ".+(.JPEG|.jpeg|.JPG|.jpg|.png|.PNG|.js|.css|.woff|.woff2|.ttf)$";
        Matcher matcher = Pattern.compile(reg).matcher(path);
        //登录，获取验证码，不用登录的接口
        if (path.indexOf("login") > -1 ||
                path.indexOf("getCode") > -1 ||
                path.indexOf("dontLogin") > -1 ||
                path.indexOf("client_game") > -1 ||
                path.indexOf("backstage") > -1 ||
//                path.indexOf("css") > -1 ||
                matcher.find()||
                path.indexOf("bundles") > -1||
                path.indexOf("plugins") > -1||
                path.indexOf("angular.min.js") > -1 ||
                /**
                 * 3D视界接口放行
                 */
                path.indexOf("td") > -1
        ) {
            //登录情况直接放行
//            log.info("********登录情况直接放行********");
            filterChain.doFilter(servletRequest, response);
            return;
        }
        if (null == token || token.isEmpty()) {
//            log.info("Url =={} == {}",req.getRequestURI(),req.getServletPath());
//          throw new AuthorizeException(ResultEnum.TOKEN_DOES_NOT_EXIST.getCode(), ResultEnum.TOKEN_DOES_NOT_EXIST.getMessage());
            ResultVO resultVO = ResultVOUtil.error(ResultEnum.TOKEN_IS_ILLEGAL.getCode(), ResultEnum.TOKEN_IS_ILLEGAL.getMessage());
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(JsonUtils.toJson(resultVO));
            return;
        } else {
            //String.format(RedisConstant.TOKEN_PREFIX, token)
            userId = redisSettingMap.getValue(RedisType.TOKEN, token);
            if (StringUtils.hasText(userId)) {
                isFilter = true;
            } else {
                ResultVO resultVO = ResultVOUtil.error(ResultEnum.TOKEN_IS_ILLEGAL.getCode(), ResultEnum.TOKEN_IS_ILLEGAL.getMessage());
                response.setCharacterEncoding("utf-8");
                response.getWriter().print(JsonUtils.toJson(resultVO));
                return;
            }
        }
        if (isFilter) {
            filterChain.doFilter(new TokenRequestWrapper((HttpServletRequest) servletRequest, userId,platform), response);
        }

    }
}
