package com.cftech.sys.filter;

import com.cftech.core.util.StringUtils;
import com.cftech.sys.model.MobileViewlog;
import com.cftech.sys.service.MobileViewlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;

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

public class MobileFilter implements Filter{
	
	@Autowired    
	private MobileViewlogService mobileViewlogService;
//	private static MobileViewlogServiceImpl mobileViewlogServiceImpl = new MobileViewlogServiceImpl();
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request= (HttpServletRequest) servletRequest;
		String path=request.getRequestURI();
		if(path.indexOf(".html")!=-1){
			//拦截并且记录此次访问
			MobileViewlog mobileViewlog =new MobileViewlog();
			
			mobileViewlog.setRemoteAddr(StringUtils.getRemoteAddr(request));
			mobileViewlog.setUserAgent(request.getHeader("user-agent"));
			mobileViewlog.setRequestUri(request.getRequestURI());
			mobileViewlog.setAppid(request.getParameter("appid"));
			mobileViewlog.setMethod(request.getDispatcherType().toString());
			mobileViewlog.setType("1");
			if(request.getHeader("REFERER")==null){
				mobileViewlog.setType("0");
			}else{
				mobileViewlog.setParenturl(request.getHeader("REFERER"));
			}
			mobileViewlog.setParams(request.getQueryString());
			ServletContext sc = request.getSession().getServletContext();
	        XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
	        if(cxt != null && cxt.getBean("mobileViewlogService") != null && mobileViewlogService == null)
	        	mobileViewlogService = (MobileViewlogService) cxt.getBean("mobileViewlogService");
			this.mobileViewlogService.save(mobileViewlog);
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
