package com.bjtdba.gateWay.filter;


import cn.hutool.json.JSONObject;
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.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.ContentDisposition;
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.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;

/**
 * @Date 2022/12/1
 * @Time 01:12
 * @Author 何海强
 * @Description Not Description
 */
@Component
@Slf4j
public class WrapperResponseGlobalFilter implements GlobalFilter, Ordered {

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    private static final List<String> EXTERNAL_PATHS = Collections.singletonList(
            "/external/**"
    );

    private boolean isExternalPath(String path) {
        for (String pattern : EXTERNAL_PATHS) {
            if (pathMatcher.match(pattern, path)) {
                return true;
            }
        }
        return false;
    }

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

        String path = exchange.getRequest().getURI().getPath();
        // 检查是否为外部API路径
        if (isExternalPath(path)) {
            return chain.filter(exchange); // 跳过当前过滤器
        }

        //获取response的 返回数据
        ServerHttpRequest originalRequest = exchange.getRequest();
        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();

        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                JSONObject jsonObject=new JSONObject();
                String path=originalRequest.getPath().toString();
                jsonObject.set("path",path);
                log.info("***********************************响应信息**********************************");
//                log.info("path = {}",originalRequest.getPath());

                HttpHeaders headers=getHeaders();
                ContentDisposition contentDisposition=headers.getContentDisposition();
                // 为附件的响应头 不打印响应日志
                if (HttpStatus.OK.equals(getStatusCode()) && body instanceof Flux && !contentDisposition.isAttachment()) {
                    Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffers);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        String responseData = new String(content, Charset.forName("UTF-8"));

//                        log.info("响应内容:{}", responseData);
                        jsonObject.set("resContext",responseData);
                        log.info("responseId_{}={}",originalRequest.getId(),jsonObject );
                        log.info("****************************************************************************\n");
                        DataBufferUtils.release(join);
                        //byte[] uppedContent = responseData.getBytes();
                        return bufferFactory.wrap(content);
                    }));
                } else if(!contentDisposition.isAttachment()){
                    //保存日志
                    log.info("响应code异常:{}", getStatusCode());
                }
                log.info("响应code异常:{}", getStatusCode());
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

    @Override
    public int getOrder() {
        //-1是响应写入过滤器，必须在此之前调用
        return -2;
    }
}
