package com.zksy.gateway.filter;

import com.zksy.gateway.config.AuthProperties;
import com.zksy.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("AuthGlobalFilter");
        return chain.filter(exchange);
//        //获取请求
//        ServerHttpRequest request = exchange.getRequest();
//        //判断是否需要拦截
//        if(isExclude(request.getPath().toString())){
//            return chain.filter(exchange);
//        }
//        //拿到token
//        String token = null;
//        String header = request.getHeaders().getFirst("authorization");
//        if(header != null && !header.isEmpty()){
//            token = header;
//        }
//        Long userId;
//        //校验token
//        try {
//            userId = jwtTool.parseToken(token);
//        } catch (UnauthorizedException e) {
//            ServerHttpResponse response = exchange.getResponse();
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();
//        }
//        //保存登录信息到下一个请求
//        ServerWebExchange swe = exchange.mutate()
//                .request(r -> r.header("user-info", userId.toString()))
//                .build();
//        return chain.filter(swe);
    }

    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath,path)){
                return true;
            }
        }
        return false;
    }

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