package com.ycwl.basic.stats.interceptor;

import com.ycwl.basic.annotation.IgnoreLogReq;
import com.ycwl.basic.constant.BaseContextHandler;
import com.ycwl.basic.stats.service.StatsService;
import com.ycwl.basic.stats.util.StatsUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashSet;

@Component
public class StatsInterceptor implements HandlerInterceptor {
    @Autowired
    private StatsService statsService;

    // 在请求处理前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
//        HandlerMethod handlerMethod = (HandlerMethod) handler;
//        request.setAttribute("startTime", System.currentTimeMillis());
//        String requestURI = request.getRequestURI();
//        String method = request.getMethod();
        String traceId = request.getHeader("traceId");
        if (StringUtils.isEmpty(traceId)) {
            return true;
//            traceId = StatsUtil.createUuid();
//            response.setHeader("Set-TraceId", traceId);
//            statsService.addStats(traceId, null);
        }
//        if (handlerMethod.getMethodAnnotation(IgnoreLogReq.class) == null) {
//            statsService.addRecord(traceId, "REQUEST",method + " " + requestURI, null);
//        }
        if (StringUtils.isNotEmpty(BaseContextHandler.getUserId())) {
            statsService.updateStats(traceId, Long.valueOf(BaseContextHandler.getUserId()));
        }
        // 返回 true 继续后续流程，false 终止请求
        return true;
    }

    // 控制器方法执行后，渲染视图前
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    // 请求完全完成后执行（无论是否异常）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        long startTime = (Long) request.getAttribute("startTime");
//        long endTime = System.currentTimeMillis();
//        System.out.println("【AfterCompletion】请求结束，耗时：" + (endTime - startTime) + "ms");
    }
}
