package com.wms_main.filter;

import com.wms_main.dao.ITSysLogService;
import com.wms_main.model.po.TSysLog;
import com.wms_main.model.pojo.log.RequestLog;
import com.wms_main.repository.utils.UUIDUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import java.io.IOException;
import java.time.LocalDateTime;

import static com.wms_main.repository.utils.StringUtils.formatStringWithMaxLength;

@Slf4j
@Component
@WebFilter(filterName = "requestLogFilter", urlPatterns = "/*")
@RequiredArgsConstructor
public class RequestLogFilter extends HttpFilter {
    /**
     * 日志服务
     */
    private final ITSysLogService sysLogService;

    // 添加对RequestMappingHandlerMapping的注入
    private final RequestMappingHandlerMapping requestMappingHandlerMapping;

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Wrapper封装request和response
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
        // 继续执行请求链
        chain.doFilter(requestWrapper, responseWrapper);
        // 请求方法
        String method = request.getMethod();
        // URI
        String uri = request.getRequestURI();
        // 客户端主机名
        String remoteHost = request.getRemoteHost();
        // 客户端ip地址
        String remoteAddr = request.getRemoteAddr();
        // 请求体
        byte[] requestContent = requestWrapper.getContentAsByteArray();
        // 响应状态
        int status = response.getStatus();
        // 响应体
        byte[] responseContent = responseWrapper.getContentAsByteArray();
        // 记录日志信息
        String requestContentString = formatStringWithMaxLength(new String(requestContent), 2048);
        String responseContentString = formatStringWithMaxLength(new String(responseContent), 2048);
        RequestLog logInfo = new RequestLog(method, uri, remoteHost, remoteAddr, requestContentString, String.valueOf(status), responseContentString);
        if (!"GET".equals(method)) {
            log.info(logInfo.toString());
        }

        // 增加存储数据库的操作
//        new Thread(() -> {
//            try {
//                TSysLog logForDb = new TSysLog(
//                        UUIDUtils.getNewUUID(),
//                        logInfo.getMethod(),
//                        logInfo.getUri(),
//                        logInfo.getRemoteHost(),
//                        logInfo.getRemoteAddr(),
//                        logInfo.getRequestContent(),
//                        logInfo.getStatus(),
//                        logInfo.getResponseContent(),
//                        LocalDateTime.now()
//                );
//                sysLogService.save(logForDb);
//            } catch (Exception e) {
//                log.error("记录日志失败。", e);
//            }
//        }).start();

        // 把缓存的响应数据，响应给客户端
        responseWrapper.copyBodyToResponse();
    }
}
