package com.ho.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.ho.gateway.config.NativeLibrary;
import com.ho.gateway.config.listnerForNacosServerUpdated.NotificationServerListUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;

/**
 * @author xueweizhi
 * @desc: 网关处加过滤器，看请求是否到达网关
 * @date 2023/4/12
 */
@Component
public class MyGateWayFilter implements GlobalFilter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(NotificationServerListUpdater.class);

    @Value("${isCheckLicence}")
    boolean isCheckLicence;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        URI uri = exchange.getRequest().getURI();
        logger.info("进入网关过滤器,uri:{}", uri);
        //todo 先注销，当需要检查licence,打开
        // -1 失败  0 成功
        if(isCheckLicence){
            int result = NativeLibrary.INSTANCE.CheckLicence();
            logger.info("进入网关过滤器,checkLicence result:{}", result);
            if(0 != result){
                return this.getResponseError(exchange, "请检查是否取得licence授权！");
            }
        }
        return chain.filter(exchange);
    }

    private Mono<Void> getResponseError(ServerWebExchange exchange, String msg) {
        ServerHttpResponse response = exchange.getResponse();
        JSONObject message = new JSONObject();
        message.put("code", HttpStatus.UNAUTHORIZED.value());
        message.put("message", msg);
        message.put("success", false);
        byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

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