/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.cftech.sys.interceptor;

import com.cftech.core.util.SpringContextHolder;
import com.cftech.core.util.StringUtils;
import com.cftech.sys.dao.LogMapper;
import com.cftech.sys.model.Log;
import com.cftech.sys.model.User;
import com.cftech.sys.security.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 系统拦截器
 */
public class LogInterceptor implements HandlerInterceptor {

	private static LogMapper logDao = SpringContextHolder.getBean(LogMapper.class);
	
	protected final Logger logger = LoggerFactory
			.getLogger(LogInterceptor.class);

	
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler) throws Exception {
		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 
			ModelAndView modelAndView) throws Exception {
//		if(modelAndView!=null) {
//			String viewName = modelAndView.getViewName();
//			UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent")); 
//			if(viewName.startsWith("modules/") && DeviceType.MOBILE.equals(userAgent.getOperatingSystem().getDeviceType())){
//				modelAndView.setViewName(viewName.replaceFirst("modules", "mobile"));
//			}
//		}
	}

	@Transactional(readOnly = false)
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
			Object handler, Exception ex) throws Exception {
		String requestRri = request.getRequestURI();
		if (StringUtils.contains(requestRri, "add") || ex!=null || StringUtils.contains(requestRri, "save")
				|| StringUtils.contains(requestRri, "update") || StringUtils.contains(requestRri, "modify")
				|| StringUtils.contains(requestRri, "remove") || StringUtils.contains(requestRri, "delete")
				|| StringUtils.contains(requestRri, "create")
				){
			User user = UserUtils.getUser();
			if (user!=null && user.getId()!=null){
				StringBuilder params = new StringBuilder();
				int index = 0;
				for (Object param : request.getParameterMap().keySet()){ 
					params.append((index++ == 0 ? "" : "&") + param + "=");
					params.append(StringUtils.abbr(StringUtils.endsWithIgnoreCase((String)param, "password")
							? "" : request.getParameter((String)param), 100));
				}
				Log log = new Log();
				log.setType(ex == null ? Log.TYPE_ACCESS : Log.TYPE_EXCEPTION);
				log.setCreateBy(String.valueOf(user.getId()));
				log.setRemoteAddr(StringUtils.getRemoteAddr(request));
				log.setUserAgent(request.getHeader("user-agent"));
				log.setRequestUri(request.getRequestURI());
				log.setAppid(UserUtils.getmpaccounts(request));
				log.setMethod(request.getMethod());
				log.setParams(params.toString());
				log.setException(ex != null ? ex.toString() : "");
				logDao.save(log);
			}
		}
		
//		logger.debug("最大内存: {}, 已分配内存: {}, 已分配内存中的剩余空间: {}, 最大可用内存: {}", 
//				Runtime.getRuntime().maxMemory(), Runtime.getRuntime().totalMemory(), Runtime.getRuntime().freeMemory(), 
//				Runtime.getRuntime().maxMemory()-Runtime.getRuntime().totalMemory()+Runtime.getRuntime().freeMemory()); 
		
	}

}
