package com.m2pool.common.security.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@Component
public class CoinInterceptor implements HandlerInterceptor {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("调用Coin拦截器1:" + request);

        // 仅处理 POST、PUT 等有请求体的请求方法
        if ("POST".equalsIgnoreCase(request.getMethod()) || "PUT".equalsIgnoreCase(request.getMethod())) {
            try {
                // 读取请求体内容
                if (request instanceof AuthRequestWrapper){
                    //BufferedReader reader = request.getReader();
                    //System.out.println("调用Coin拦截器2:" + reader);
                    //
                    //if (!requestBody.isEmpty()) {
                    //    // 反序列化请求体为 RequestObject 对象
                    //    RequestObject requestObject = objectMapper.readValue(requestBody, RequestObject.class);
                    //    System.out.println("调用Coin拦截器3:" + requestObject.toString());
                    //    String coin = requestObject.getCoin();
                    //    System.out.println("调用Coin拦截器4:" + coin);
                    //    if ("enx".equals(coin)) {
                    //        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    //        response.getWriter().write("enx币种已下架");
                    //        return false;
                    //    }
                    //}
                }

            } catch (Exception e) {
                // 处理反序列化异常
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("请求体解析失败");
                return false;
            }
        }
        return true;
    }

    /**
     * 读取请求体内容
     */
    private String readRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        return stringBuilder.toString();
    }
}
