package com.boman.web.core.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.RequestWrapper;
import java.util.Map;

/**拦截器计算接口用时
 * @author tjf
 * @Date: 2022/03/20/16:42
 */
@Component
public class ControllerTimeInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER  = LoggerFactory.getLogger(ControllerTimeInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String url = httpServletRequest.getRequestURL().toString();
        long start = System.currentTimeMillis();
        httpServletRequest.setAttribute("start", start);
        StringBuilder sb = new StringBuilder();
        sb .append("【开始请求】：\n-------------------------------------------------------------\n");
        HandlerMethod h = (HandlerMethod) o;
        sb.append("Controller: ").append(h.getBean().getClass().getName()).append("\n");
        sb.append("URL       : ").append(url).append("\n");
        // 打印请求参数
        if (isJsonRequest(httpServletRequest)) {
            Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
            if (parameterMap !=null && parameterMap.size() > 0) {
                String jsonParam = JSONObject.toJSONString(parameterMap);
                LOGGER.info("[**]开始请求 => URL[{}],参数类型[json],参数:[{}]", url, jsonParam);
            }
        } else {
            Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
            if (parameterMap !=null && parameterMap.size() > 0) {
                String parameters = JSONObject.toJSONString(parameterMap);
                LOGGER.info("[**]开始请求 => URL[{}],参数类型[param],参数:[{}]", url, parameters);
            } else {
                LOGGER.info("[**]开始请求 => URL[{}],无参数", url);
            }
        }
        sb .append("-------------------------------------------------------------\n");
        LOGGER.info(sb.toString());
        // 填入当前接口的调用开始时间
        httpServletRequest.setAttribute("startTime",System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        String url = httpServletRequest.getRequestURL().toString();
        Long startTime=(Long)httpServletRequest.getAttribute("startTime");
        Long expireTime=System.currentTimeMillis()-startTime;
        StringBuilder sb = new StringBuilder();
        sb .append("【结束请求】：\n-------------------------------------------------------------\n");
        HandlerMethod h = (HandlerMethod) o;
        sb.append("Controller: ").append(h.getBean().getClass().getName()).append("\n");
        sb.append("URL       : ").append(url).append("\n");
        sb.append("EXPIRETIME耗时: ").append(expireTime).append("(ms)\n");
        sb .append("-------------------------------------------------------------\n");
        //判断接口时间
        if (expireTime > 2000L){
            LOGGER.warn(sb.toString(),"接口时间大于2秒");
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 判断本次请求的数据类型是否为json
     *
     * @param request request
     * @return boolean
     */
    private boolean isJsonRequest(HttpServletRequest request) {
        String contentType = request.getContentType();
        if (contentType != null) {
            return StringUtils.startsWithIgnoreCase(contentType, MediaType.APPLICATION_JSON_VALUE);
        }
        return false;
    }
}
