package org.wfc.gateway.filter;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.wfc.common.core.utils.ServletUtils;
import org.wfc.common.core.utils.StringUtils;
import org.wfc.gateway.config.properties.CaptchaProperties;
import org.wfc.gateway.service.ValidateCodeService;
import reactor.core.publisher.Flux;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 验证码过滤器
 *
 * @author wfc
 */
@Component
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object>
{
    private final static String[] VALIDATE_URL = new String[] { "/auth/login" };
    private final static String[] MAIL_VALIDATE_URL = new String[] { "/auth/register" };

    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    private CaptchaProperties captchaProperties;

    private static final String CODE = "code";

    private static final String UUID = "uuid";

    private static final String EMAIL = "email";

    @Override
    public GatewayFilter apply(Object config)
    {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();

            // 非登录请求且验证码启用，非注册请求且邮箱验证码启用, 不处理
            boolean enabledLoginCaptcha = StringUtils.equalsAnyIgnoreCase(request.getURI().getPath(), VALIDATE_URL) && captchaProperties.getEnabled();
            boolean enabledRegisterCaptcha = StringUtils.equalsAnyIgnoreCase(request.getURI().getPath(), MAIL_VALIDATE_URL) && captchaProperties.getMailEnabled();
            if (!enabledLoginCaptcha && !enabledRegisterCaptcha)
            {
                return chain.filter(exchange);
            }

            try
            {
                String rspStr = resolveBodyFromRequest(request);
                JSONObject obj = JSON.parseObject(rspStr);
                // 图片验证码启用
                if (enabledLoginCaptcha) {
                    validateCodeService.checkCaptcha(obj.getString(CODE), obj.getString(UUID));
                }
                // 邮箱验证码启用
                if (enabledRegisterCaptcha) {
                    validateCodeService.checkCaptchaEmail(obj.getString(CODE), obj.getString(EMAIL));
                }
            }
            catch (Exception e)
            {
                return ServletUtils.webFluxResponseWriter(exchange.getResponse(), e.getMessage());
            }
            return chain.filter(exchange);
        };
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest)
    {
        // 获取请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }
}
