package com.yuchen.saas.park.service.annotation;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * @Author: baichaojie
 * @CreateTime: 2024/10/30 14:05
 * @Description: 第三方请求过滤器
 * @Version: 1.0
 */
//@Component 加上@Component注解会导致下面urlPatterns失效 改为启动类添加@ServletComponentScan注解
@WebFilter(filterName = "ThirdFilter", urlPatterns = "/third/*")
public class ThirdFilter implements Filter {


    private static final String FORM_CONTENT_TYPE = "application/json";

    @Override
    public void init(FilterConfig filterConfig) {
    }

    private static final String THIRD_DATA = "third_data";

    /**
     * @param request  request请求
     * @param response response应答
     * @param chain    过滤器链
     * @throws IOException      io异常
     * @throws ServletException servlet异常
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        if (httpServletRequest.getContentType().contains(FORM_CONTENT_TYPE)) {

            BufferedRequestWrapper bufferedRequest = new BufferedRequestWrapper(
                    httpServletRequest);
            BufferedResponseWrapper bufferedResponse = new BufferedResponseWrapper(
                    httpServletResponse);
            String jsonBody = getRequestBody(bufferedRequest);
            String dataString = getDataString(jsonBody);
            if (dataString != null) {
                bufferedRequest.setAttribute(THIRD_DATA, dataString);
            }
            chain.doFilter(bufferedRequest, bufferedResponse);
            return;
        }
        chain.doFilter(request, response);
    }

    /**
     * 获取request请求体
     *
     * @return http请求数据
     * @throws IOException io异常
     */
    private String getRequestBody(BufferedRequestWrapper bufferedResponse) throws IOException {
        // 指定UTF-8编码，避免因为系统的file-encoding不同，导致中文乱码
        BufferedReader reader = new BufferedReader(new InputStreamReader(bufferedResponse.getInputStream(), StandardCharsets.UTF_8));
        String line;
        StringBuilder inputBuffer = new StringBuilder();
        do {
            line = reader.readLine();
            if (null != line) {
                inputBuffer.append(line.trim());
            }

        } while (line != null);
        reader.close();
        return inputBuffer.toString().trim();
    }

    /**
     * 获取签名data
     *
     * @param request http请求
     * @return 签名data
     */
    public static String getSignData(ServletRequest request) {
        Object result = request.getAttribute(THIRD_DATA);
        return result == null ? null : String.valueOf(result);
    }

    /**
     * 获取第三方请求data数据
     *
     * @param str 第三方请求json串
     * @return 第三方请求data数据
     */
    private static String getDataString(String str) {
        int in = str.indexOf("data");
        String dataString = null;
        if (in > 0) {
            str = str.substring(str.indexOf("data"));
            str = str.substring(str.indexOf("{"));
            int m = 0, n = 0;
            int count = 0;
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == '{') {
                    if (count == 0) {
                        m = i;
                    }
                    count++;
                }
                if (str.charAt(i) == '}') {
                    count--;
                    if (count == 0) {
                        n = i;
                        dataString = (str.substring(m, n + 1));
                    }
                }
            }
        }
        return dataString;
    }

    @Override
    public void destroy() {
    }

}