package com.bonus.common.security.config;


import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.global.SystemGlobal;
import com.bonus.common.security.interceptor.ReadHttpRequestWrapper;
import jdk.nashorn.internal.runtime.PropertyDescriptor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

import static cn.hutool.http.Method.POST;
import static jdk.nashorn.internal.runtime.PropertyDescriptor.GET;

@Component
@WebFilter("/*")
public class MyFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
      if (SystemGlobal.POST.equals(request.getMethod()) ||   SystemGlobal.PUT.equals(request.getMethod()) ){
          //去除文件上传
             String header = request.getHeader(HttpHeaders.CONTENT_TYPE);
             if(StringUtils.isNotEmpty(header)){
                    if(header.contains(MediaType.MULTIPART_FORM_DATA_VALUE) ||  header.contains(MediaType.APPLICATION_FORM_URLENCODED_VALUE)){
                        filterChain.doFilter(request, response);
                        return;
                    }
             }
            Map<String, String[]> parameters = request.getParameterMap();
            //解决 无法流重复读取的问题
              request = new ReadHttpRequestWrapper(request,parameters);
            filterChain.doFilter(request, response);
      }else{
          filterChain.doFilter(request, response);
      }
      }

}