package com.mandi.springmvc.logs;

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

import org.springframework.context.ApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.mandi.common.Jacksonmethod;
import com.mandi.common.SessionMethod;
import com.mandi.common.SpringContext;
import com.mandi.system.service.IMOpLogServie;
import com.mandi.system.service.impl.MOpLogServie;
import com.mandi.system.persist.Login;
import com.mandi.system.persist.ModuleEnum;

public class LogsInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest r,
			HttpServletResponse re, Object handler) throws Exception {
		if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
			OpLogs oplog= ((HandlerMethod)handler).getMethodAnnotation(OpLogs.class);
			if(oplog==null){
				return true;
			}
			ApplicationContext ac= SpringContext.getAppContext();
			if(ac==null){
				return true;
			}
			IMOpLogServie imlser=ac.getBean(MOpLogServie.class);
			Login l=SessionMethod.getlogin(r.getSession());
			if(l==null){
				l=new Login();
				l.setUsername("未登录");
				l.setWorkername(r.getRemoteAddr());
				l.setDepartname("不知道");
			}
			String name=oplog.name();
			ModuleEnum module=oplog.module();
			String note="";
			try{
				note=Jacksonmethod.tojson(r.getParameterMap(), false);
				imlser.insert(l, module, name, note);
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		
		return true;
	}
	
}