package com.njcn.gather.user.user.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.njcn.common.pojo.constant.SecurityConstants;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.JwtUtil;
import com.njcn.web.utils.HttpResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

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

/**
 * @author caozehui
 * @data 2024/11/18
 */
@Slf4j
@Component
public class AuthGlobalFilter implements Filter, Ordered {
    private final static List<String> IGNORE_URI = Arrays.asList("/doc.html","/v3/api-docs","/admin/login","/admin/getPublicKey", "/report/generateReport", "/resourceManage/stream");

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        res.setCharacterEncoding("UTF-8");
        res.setContentType("application/json; charset=utf-8");

        String requestURI = req.getRequestURI();
        if (IGNORE_URI.contains(requestURI) || requestURI.startsWith("/webjars") || requestURI.startsWith("/swagger-resources")) {
            filterChain.doFilter(req, res);
        } else {
            String accessTokenStr = req.getHeader(SecurityConstants.AUTHORIZATION_KEY);
            String isRefreshToken = req.getHeader(SecurityConstants.IS_REFRESH_TOKEN);
            if (StrUtil.isBlank(accessTokenStr) || !accessTokenStr.startsWith(SecurityConstants.AUTHORIZATION_PREFIX)) {
                HttpResult httpResult = new HttpResult<>(CommonResponseEnum.PARSE_TOKEN_ERROR.getCode(), CommonResponseEnum.PARSE_TOKEN_ERROR.getMessage());
                res.getWriter().write(JSON.toJSONString(httpResult)); //前端重定向到登录页面
                return;
            }
            String accessToken = accessTokenStr.substring(SecurityConstants.AUTHORIZATION_PREFIX.length());
            try {
                if (StrUtil.isBlank(accessToken) || !JwtUtil.verifyToken(accessToken)) {
                    HttpResult httpResult = new HttpResult<>(CommonResponseEnum.PARSE_TOKEN_ERROR.getCode(), CommonResponseEnum.PARSE_TOKEN_ERROR.getMessage());
                    res.getWriter().write(JSON.toJSONString(httpResult));
                } else if (JwtUtil.isExpired(accessToken)) {
                    if ("true".equals(isRefreshToken)) {
                        HttpResult httpResult = new HttpResult<>(CommonResponseEnum.PARSE_TOKEN_ERROR.getCode(), CommonResponseEnum.PARSE_TOKEN_ERROR.getMessage());
                        res.getWriter().write(JSON.toJSONString(httpResult));
                    } else {
                        HttpResult httpResult = new HttpResult<>(CommonResponseEnum.TOKEN_EXPIRE_JWT.getCode(), CommonResponseEnum.TOKEN_EXPIRE_JWT.getMessage());
                        res.getWriter().write(JSON.toJSONString(httpResult));
                    }
                } else {
                    filterChain.doFilter(req, res);
                }
            } catch (Exception e) {
                HttpResult httpResult = new HttpResult<>(CommonResponseEnum.PARSE_TOKEN_ERROR.getCode(), CommonResponseEnum.PARSE_TOKEN_ERROR.getMessage());
                res.getWriter().write(JSON.toJSONString(httpResult));
            }
        }
    }
}

