package com.chinaitop.depot.intelligent.utils;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import com.chinaitop.depot.intelligent.utils.DataPolicyEngine;
import com.chinaitop.depot.intelligent.utils.ParameterRequestWrapper;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class CustomFilter implements Filter {

	@Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
	
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		ParameterRequestWrapper requestWrapper = new ParameterRequestWrapper((HttpServletRequest) arg0);
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpSession session = request.getSession();
		String orgId = "";
		if (session != null){
			orgId = ObjectUtils.toString(session.getAttribute("orgId"), "");
		}
		if (StringUtils.isNotBlank(orgId)) {
			DataPolicyEngine.set(orgId);
		}

		if (StringUtils.isNotBlank(orgId)) {
			// 将参数追加到request url 之后
			requestWrapper.addParameter("orgId", orgId);
			requestWrapper.addParameter("unitid", orgId);
			requestWrapper.addParameter("unitId", orgId);
			// 将参数追加到request 的body 中
			requestWrapper.addParameterToBody("orgId", orgId);
			requestWrapper.addParameterToBody("unitid", orgId);
			requestWrapper.addParameterToBody("unitId", orgId);
		}

		arg2.doFilter(requestWrapper, arg1);
		DataPolicyEngine.remove();
	}
	
	@Override
    public void destroy() {
 
    }

}
