package com.quant.interceptor;

import java.util.Map;
import java.util.Map.Entry;

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

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.quant.comm.CommTool;
import com.quant.comm.LoginSecret;
import com.quant.dao.LogMapper;
import com.quant.entity.Log;
@Component
public class LogInterceptor implements HandlerInterceptor {

	@Resource
	LogMapper logMapper;
	
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}
	// Controller业务方法执行后调用
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object obj, ModelAndView mv) throws Exception {
		String str=request.getRequestURI();
		str=str.substring(str.lastIndexOf("/")+1, str.indexOf("."));
		String operation=CommTool.getTableField(str);
		String content="";
		String user="";
		Map<String, String[]> map=request.getParameterMap();
		
	    if(operation!=""&&operation!=null){
	    	if(operation.equals("登录")){
				for (Entry<String, String[]> entry:map.entrySet()) {
					content+=entry.getKey()+"="+entry.getValue()+";";
				}
				user=request.getParameter("loginName");
			}else{
				for (Entry<String, String[]> entry:map.entrySet()) {
					content+=entry.getKey()+"="+request.getParameter(entry.getKey())+";";
				}
				user=LoginSecret.getCookie(request, response, "name");
			}
	    	content = content.substring(0, 255);
			String ip=CommTool.getIP(request);
	    	Log log=new Log(null, user, operation, null, ip, content);
	    	logMapper.addLog(log);
	    }
	}

	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2) throws Exception {
		return true;
	}

}
