package com.njzscloud.common.mvc.support;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.njzscloud.common.core.jackson.Jackson;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ReusableHttpServletRequest extends HttpServletRequestWrapper {
    private final byte[] body;

    public ReusableHttpServletRequest(HttpServletRequest request) {
        super(request);
        try {
            if (ServletFileUpload.isMultipartContent(request)) {
                body = "多部分表单".getBytes(StandardCharsets.UTF_8);
            } else {
                ServletInputStream inputStream = request.getInputStream();
                body = IoUtil.readBytes(inputStream);
            }
            printRequest();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void printRequest() {
        try {
            String method = this.getMethod();
            String requestURI = this.getRequestURI();
            Map<String, String[]> parameterMap = this.getParameterMap();
            Enumeration<String> headerNames = this.getHeaderNames();
            Map<String, String> headerMap = new HashMap<>();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String header = this.getHeader(headerName);
                headerMap.put(headerName, header);
            }
            String body;
            if (method.equalsIgnoreCase("GET")) {
                body = "无";
            } else {
                if (this.body == null || this.body.length == 0) {
                    body = "无";
                } else {
                    body = new String(this.body, StandardCharsets.UTF_8);
                    body = StrUtil.isBlank(body) ? "无" : body;
                }
            }
            if (requestURI.contains("/station/letter")) {
                return;
            }
            log.info("接口：{} {}\n请求头：{}\n请求参数：{}\n请求体：{}",
                    method, requestURI, headerMap.isEmpty() ? "无" : Jackson.toJsonStr(headerMap), parameterMap.isEmpty() ? "无" : Jackson.toJsonStr(parameterMap), body);
        } catch (Throwable e) {
            log.error("接口请求信息打印失败", e);
        }
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }

            @Override
            public int readLine(byte[] b, int off, int len) throws IOException {
                return super.readLine(b, off, len);
            }

            @Override
            public int read(byte[] b) throws IOException {
                return bais.read(b);
            }

            @Override
            public int read(byte[] b, int off, int len) throws IOException {
                return bais.read(b, off, len);
            }

            @Override
            public long skip(long n) throws IOException {
                return bais.skip(n);
            }

            @Override
            public int available() throws IOException {
                return bais.available();
            }

            @Override
            public void close() throws IOException {
                bais.close();
            }

            @Override
            public synchronized void mark(int readlimit) {
                bais.mark(readlimit);
            }

            @Override
            public synchronized void reset() throws IOException {
                bais.reset();
            }

            @Override
            public boolean markSupported() {
                return bais.markSupported();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
}
