package com.ruoyi.common.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.MimeHeaders;
import org.springframework.context.i18n.LocaleContextHolder;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * Repeatable 过滤器
 * 
 * @author ruoyi
 */
@Slf4j
public class RequestFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException
    {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        //定义一个新的request(名称是wrapper)
        ParameterRequestWrapper wrapper = new ParameterRequestWrapper(request);
        //重新赋值userId,塞到request里面去
//        Map paramter = new HashMap(16);
//        paramter.put("beginTime", "2024-10-11");
        //返回
        chain.doFilter(wrapper, servletResponse);






//        // 修改请求头
//        Map<String, String> map = new HashMap<>();
//        modifyHeaders(map, request);
//
//        // 修改cookie
//        ModifyHttpServletRequestWrapper requestWrapper = new ModifyHttpServletRequestWrapper(request);
//        String token = request.getHeader("token");
//        if (token != null && !"".equals(token)) {
//            requestWrapper.putCookie("SHIROSESSIONID", token);
//        }

        // finish
        //chain.doFilter(request, servletResponse);
    }

    @Override
    public void destroy()
    {

    }

    /**
     * 修改请求头信息
     * @param headerses
     * @param request
     */
    private void modifyHeaders(Map<String, String> headerses, HttpServletRequest request) {
        if (headerses == null || headerses.isEmpty()) {
            return;
        }
        Class<? extends HttpServletRequest> requestClass = request.getClass();
        try {
            Field request1 = requestClass.getDeclaredField("request");
            request1.setAccessible(true);
            Object o = request1.get(request);
            Field coyoteRequest = o.getClass().getDeclaredField("coyoteRequest");
            coyoteRequest.setAccessible(true);
            Object o1 = coyoteRequest.get(o);
            Field headers = o1.getClass().getDeclaredField("headers");
            headers.setAccessible(true);
            MimeHeaders o2 = (MimeHeaders)headers.get(o1);
            for (Map.Entry<String, String> entry : headerses.entrySet()) {
                o2.removeHeader(entry.getKey());
                o2.addValue(entry.getKey()).setString(entry.getValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
