package com.qiuguo.iot.user.api.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
// import org.springframework.web.servlet.HandlerMapping;
import reactor.core.publisher.Mono;

/**
 * XXX
 *
 * @author weiyachao
 * @since 2023/9/20 16:06
 */
@Configuration
@Slf4j
@Order(-1)
public class AuthFilter implements WebFilter {

    // @Autowired
    private ReactiveStringRedisTemplate  reactiveRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        // HandlerMethod handlerMethod = exchange.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
        Object attribute = exchange.getAttribute("org.springframework.web.server.ServerWebExchange.LOG_ID");
        System.out.println("attribute = " + attribute);
        // if (handlerMethod != null && handlerMethod.getMethod().isAnnotationPresent(Auth.class)) {
        //     // 如果请求方法上有 Auth 注解，执行登录验证逻辑
        //     String api_token = exchange.getRequest().getHeaders().getFirst(UserAuthContains.API_TOKEN);
        //     String api_type = exchange.getRequest().getHeaders().getFirst(UserAuthContains.API_TYPE);
        //     if (ObjectUtils.isEmpty(api_token) || ObjectUtils.isEmpty(api_type)) {
        //         return Mono.error(new RuntimeException("未登录"));
        //     }
        //     String key = RedisConstans.IOT_TOKEN.concat(api_token);
        //     return reactiveRedisTemplate.getExpire(key).map(Duration::getSeconds).flatMap(ttl -> {
        //         if (ttl == -1) {
        //             // 用户没登陆
        //             return Mono.error(new RuntimeException("未登录"));
        //         } else if (ttl <= 3600) {
        //             // token 将要失效
        //             return reactiveRedisTemplate.expire(key, Duration.ofDays(7))
        //                     .then(chain.filter(exchange));
        //         } else {
        //             // 正常登录
        //             return chain.filter(exchange);
        //         }
        //     });
        // }

        return chain.filter(exchange);
    }
    
}
