package com.liquidnet.support.zuul.filter;

import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.core.JwtValidator;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.support.zuul.util.PathMatchUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class GlobalAuthFilter extends ZuulFilter {
    @Value("#{'${global.include.url}'.split(', ')}")
    private List<String> includeUrls;
    @Value("#{'${global.include.url-pattern}'.split(', ')}")
    private List<String> includeUrlPatterns;
    @Value("#{'${global.exclude.url}'.split(', ')}")
    private List<String> excludeUrls;
    @Value("#{'${global.exclude.url-pattern}'.split(', ')}")
    private List<String> excludeUrlPatterns;
    private static final String CONTENT_TYPE = "application/json;charset=utf-8";
    private static final String AUTHORIZATION = "authorization";
    private static final String TOKEN_STATUS = "token_status";
    private static final String TOKEN_ILLEGAL = "40001";
    private static final String TOKEN_KICK = "40002";
    private static final String TOKEN_INVALID = "40003";

    @Autowired
    JwtValidator jwtValidator;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();

        HttpServletRequest ctxRequest = ctx.getRequest();

        String authorization = ctxRequest.getHeader(AUTHORIZATION);

        if (StringUtils.isNotBlank(authorization) && StringUtils.length(authorization) > 7) {
            String token = authorization.substring(7);
            try {
                // 解析没有异常则表示token验证通过，如有必要可根据自身需求增加验证逻辑
                Claims claims = jwtValidator.parse(token);

                ctx.addZuulRequestHeader(CurrentUtil.uID, (String) claims.get(CurrentUtil.uID));
                ctx.addZuulRequestHeader(CurrentUtil.uTag, JsonUtils.toJson(claims));
            } catch (ExpiredJwtException expiredJwtEx) {
                ctx.addZuulRequestHeader(TOKEN_STATUS, TOKEN_INVALID);
            } catch (Exception ex) {
                ctx.addZuulRequestHeader(TOKEN_STATUS, TOKEN_ILLEGAL);
            }
            ctx.addZuulRequestHeader(CurrentUtil.uToken, token);
        }

        String requestURI = ctxRequest.getRequestURI();

        if (excludeUrls.contains(requestURI)) {
            return false;
        }
        if (includeUrls.contains(requestURI)) {
            return true;
        }
        for (String urlPattern : includeUrlPatterns) {
            if (PathMatchUtil.isPathMatch(urlPattern, requestURI)) {
                return true;
            }
        }
        for (String urlPattern : excludeUrlPatterns) {
            if (PathMatchUtil.isPathMatch(urlPattern, requestURI)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();

        Map<String, String> zuulRequestHeaders = ctx.getZuulRequestHeaders();

        String uToken = zuulRequestHeaders.get(CurrentUtil.uToken);

        log.info("headers:{}", JsonUtils.toJson(ctx.getRequest().getHeaderNames()));
        log.info("uToken:{}", uToken);

        if (StringUtils.isEmpty(uToken)) {
            respHandler(ctx, TOKEN_ILLEGAL);
        } else {
            String uid = zuulRequestHeaders.get(CurrentUtil.uID);

            if (StringUtils.isEmpty(uid)) {
                respHandler(ctx, zuulRequestHeaders.get(TOKEN_STATUS));
            } else {
                String ssoKeyUidM5Token = jwtValidator.getSsoRedisKey().concat(uid).concat(
                        DigestUtils.md5DigestAsHex(uToken.getBytes(StandardCharsets.UTF_8))
                );

                if (redisUtil.hasKey(ssoKeyUidM5Token)) {// 是否存在SSO

                    if ((boolean) redisUtil.get(ssoKeyUidM5Token)) {// 是否在线

                        ctx.setSendZuulResponse(true);
                    } else {

                        respHandler(ctx, TOKEN_INVALID);
                    }
                } else {
                    respHandler(ctx, TOKEN_KICK);
                }
            }
        }
        return null;
    }

    private void respHandler(RequestContext requestContext, String code) {
        requestContext.setSendZuulResponse(false);
        ResponseDto<Object> responseDto = ResponseDto.failure(ErrorMapping.get(code));
        requestContext.setResponseBody(JsonUtils.toJson(responseDto));
        HttpServletResponse response = requestContext.getResponse();
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(CONTENT_TYPE);
    }
}
