package com.huimv.gateway.filter;


import com.huimv.common.exception.RRException;
import com.huimv.common.utils.TokenUtil;
import com.huimv.gateway.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.List;
import java.util.Map;

/**
 * @Author yinhao
 * @Date 2021/4/30 18:37
 * @Description
 */
@Slf4j
@Component
public class TokenSignFilter implements GlobalFilter, Ordered {


    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {



        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response =  exchange.getResponse();



        if (request.getURI().getPath().contains("/getToken") ||request.getURI().getPath().contains("/api")) {
            return chain.filter(exchange);
        }


//        Map<String,String> requestBody = exchange.getAttribute("cachedRequestBodyObject");
        String token = request.getQueryParams().getFirst("token");
        if (token == null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
//            throw new RRException("身份信息有误",HttpStatus.UNAUTHORIZED.value());
        }
        if (!TokenUtil.verify(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
//            throw new RRException("身份信息有误",HttpStatus.UNAUTHORIZED.value());
        }



        //登录接口不参与过滤
//        if (request.getURI().getPath().contains("/login")) {
//            return chain.filter(exchange);
//        }
//
//        String token = request.getHeaders().getFirst(jwtUtils.getHeader());
//        if (StringUtils.isEmpty(token)) {
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();
//        }
//
//        try {
//
//            Claims claims = jwtUtils.getClaimByToken(token);
//            if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
//                response.setStatusCode(HttpStatus.UNAUTHORIZED);
//                return response.setComplete();
//                //throw new RRException(jwtUtils.getHeader() + "失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
//            }
//
//            Long id = Long.parseLong(claims.getSubject());
//            log.info("find userId: {} from uri: {}", id, request.getURI());
//            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> httpHeaders.add("userId", id + "")).build();
//            exchange.mutate().request(serverHttpRequest).build();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            //向客户端返回错误提示信息
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();
//        }

        return chain.filter(exchange);
    }


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