package com.tofly.toflygateway.filter;

import com.alibaba.fastjson.JSONObject;
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.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.nio.charset.Charset;

@Component
public class ToflyResponseGlobalFilter implements GlobalFilter, Ordered {

    private static  final String SIGN_HEAD="X-Sign";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
     //   String bgDebug = exchange.getAttributeOrDefault(ConstantFilter.BG_DEBUG_KEY, ConstantFilter.REQ_RES_ENCRYPT);
        boolean sign = exchange.getRequest().getHeaders().getFirst(SIGN_HEAD) == null?false:true;
        ServerHttpResponse originalResponse = exchange.getResponse();
        if(!sign){ //不需要加解密，直接返回即可
            return chain.filter(exchange.mutate().response(originalResponse).build());
        }

        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.buffer().map(dataBuffer -> {

                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffer);

                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        //释放掉内存
                        DataBufferUtils.release(join);
                        // 正常返回的数据
                        String rootData = new String(content, Charset.forName("UTF-8"));
                       boolean checkEncrypt=checkEncrypt(rootData);
                        if(checkEncrypt){
                            String encryptData=SM2Utils.encrypt(rootData,SM2Config.publicKey);
                            rootData=encryptData;

                        }
                        //加密之后的数据
                          byte[] respData = rootData.getBytes();

                        // 加密后的数据返回给客户端
                        byte[] uppedContent = new String(respData, Charset.forName("UTF-8")).getBytes();
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(decoratedResponse).build());

    }

    private  boolean checkEncrypt(String str){
        boolean flag=true;
        try{

           JSONObject toeknResultMap = JSONObject.parseObject(str);
            if(toeknResultMap.get("status")!=null){
                flag=false;
            };
            if(flag){
                if(toeknResultMap.get("code")!=null && !toeknResultMap.get("code").toString().equals("1") && !toeknResultMap.get("code").toString().equals("200")){
                    flag=false;
                }
            }

        }catch (Exception e){

        }
     return flag;

    }

    @Override
    public int getOrder() {
        // 确保此过滤器在其他过滤器之后运行
        return -200;
    }
}