package com.yonge.log.interceptor;

import java.io.IOException;
import java.util.Date;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ym.mec.util.json.JsonUtil;
import com.ym.mec.util.web.WebUtil;
import com.yonge.log.dal.model.AuditLog;
import com.yonge.log.model.AuditLogAnnotation;
import com.yonge.log.service.AuditLogService;

/**
 * 日志审计的拦截器
 */
public class AuditLogInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private AuditLogService auditLogService;

	private String username;

	public AuditLogInterceptor(String username) {
		this.username = username;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {

		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		AuditLogAnnotation anno = handlerMethod.getMethodAnnotation(AuditLogAnnotation.class);

		if (anno != null) {
			AuditLog auditLog = new AuditLog();
			auditLog.setOperateName(anno.operateName());
			auditLog.setInterfaceUrl(anno.interfaceURL());
			auditLog.setUserIp(WebUtil.getRemoteIp(request));
			auditLog.setInputParams(JsonUtil.toJSONString(WebUtil.getParameterMap(request)));
			// 操作人
			auditLog.setUsername(username);
			auditLog.setOperateTime(new Date());
			auditLogService.insert(auditLog);
		}

	}

	public void setUsername(String username) {
		this.username = username;
	}

}
