package shop.alien.config.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 编写拦截器
 **/
@Slf4j
public class RequestInterceptor implements HandlerInterceptor {

    private Environment environment;

    @Autowired
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        StringBuffer requestURL = request.getRequestURL();
        String serviceName = environment.getProperty("server.name");
        if (requestURL.indexOf(serviceName) > -1) {
            if (isJson(request)) {
                log.info("--------------Post请求--------------");
                log.info("请求地址: {}", requestURL);
                // 获取json字符串
                try {
                    String jsonParam = new RequestWrapper(request).getBodyString();
                    log.info("请求参数: {}", jsonParam);
                } catch (Exception e) {
                    log.error("请求参数获取异常: {}", e.getMessage());
                }
            } else {
                log.info("--------------Get请求--------------");
                log.info("请求地址: {}", requestURL);
                //获取请求参数
                String queryString = request.getQueryString();
                if (queryString != null) {
                    log.info("请求参数: {}", queryString);
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }

    /**
     * 判断本次请求的数据类型是否为json
     */
    private boolean isJson(HttpServletRequest request) {
        //判断form-data, application/json, application/json;charset=UTF-8
        if (request.getContentType() != null) {
            return request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE) ||
                    request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE) ||
                    request.getContentType().equals(MediaType.MULTIPART_FORM_DATA_VALUE) ||
                    request.getContentType().equals("application/json; charset=UTF-8");
        }
        return false;
    }
}