package ink.wgink.gateway.filter.global;

import ink.wgink.gateway.dao.log.IRequestLogDao;
import ink.wgink.gateway.handler.log.RequestLogHandler;
import ink.wgink.gateway.pojo.log.RequestLog;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
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.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: CountGolbalFilter
 * @Description: 计数过滤器
 * @Author: WangGeng
 * @Date: 2021/4/13 12:10
 * @Version: 1.0
 **/
@Slf4j
@Component
public class RequestLogGlobalFilter implements GlobalFilter, Ordered {

    private RequestLogHandler requestLogHandler;

    public RequestLogGlobalFilter(RequestLogHandler requestLogHandler) {
        this.requestLogHandler = requestLogHandler;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, GatewayFilterChain gatewayFilterChain) {
        ServerHttpRequest serverHttpRequest = serverWebExchange.getRequest();
        ServerHttpResponse serverHttpResponse = serverWebExchange.getResponse();
        // 其它情况，一律放行，并做日志处理
        RequestLog requestLog = buildRequestLog(serverHttpRequest);
        return gatewayFilterChain.filter(serverWebExchange.mutate().response(new ServerHttpResponseDecorator(serverHttpResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    requestLog.setResponseCode(this.getStatusCode().value());
                    requestLog.setEndTime(System.currentTimeMillis());
                    requestLog.setUsedTime(requestLog.getEndTime() - requestLog.getStartTime());
                    requestLogHandler.save(requestLog);
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.map(dataBuffer -> {
                        byte[] content = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(content);
                        // String responseResult = new String(content, Charset.forName("UTF-8"));
                        return super.bufferFactory().wrap(content);
                    }));
                }
                return super.writeWith(body);
            }
        }).build());
    }

    @Override
    public int getOrder() {
        // 调整到-10保证过滤器在执行时，路径没有被修改
        return -10;
    }

    /**
     * 构建请求日志
     *
     * @param serverHttpRequest
     * @return
     */
    private RequestLog buildRequestLog(ServerHttpRequest serverHttpRequest) {
        URI uri = serverHttpRequest.getURI();
        RequestLog requestLog = new RequestLog();
        requestLog.setMethod(serverHttpRequest.getMethod().name());
        requestLog.setHost(uri.getHost());
        requestLog.setPort(uri.getPort());
        requestLog.setPath(uri.getPath());
        requestLog.setQueryParams(uri.getQuery());
        requestLog.setScheme(uri.getScheme());
        requestLog.setStartTime(System.currentTimeMillis());
        return requestLog;
    }
}
