package com.dubh.syslog.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import com.util.RequestUtil;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author 作者姓名: dubaohui
 * @version 创建时间：2015-5-18 下午12:46:28 类说明:切入点
 */
@Aspect
@Component
public class SystemLogAspect {
	// 注入Service用于把日志保存数据库
//	@Resource(name = "syslogservice")
//	private SyslogService syslogservice;

	// Service层切点
	@Pointcut("@annotation(com.dubh.syslog.annotation.SystemServiceLog)")
	public void serviceAspect() {
	}

	// 前置Controller层切点
	@Pointcut("@annotation(com.dubh.syslog.annotation.SystemControllerBeforeLog)")
	public void controllerBeforeAspect() {
	}

	// 后置Controller层切点
	@Pointcut("@annotation(com.dubh.syslog.annotation.SystemControllerAfterLog)")
	public void controllerAfterAspect() {
	}

	/**
	 * 前置通知 用于拦截Controller层记录用户的操作
	 * 
	 * @param joinPoint
	 *            切点
	 */
	@Before("controllerBeforeAspect()")
	public void doBefore(JoinPoint joinPoint) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
//		// 读取session中的用户
//		Tblsysuser user = SessionUser.getsession(request);
//		String loginname = "";
//		String loginkey = "";
//		String loginaccount = "";
//		if (null != user) {
//			loginname = user.getSysusername();
//			loginkey = user.getSysuserkey();
//			loginaccount = user.getSysaccount();
//		}
//		// 请求的IP
//		String ip = RequestUtil.getIpAddr(request);
//		try {
//			Tblsyslog loginfo = new Tblsyslog();
//			loginfo.setSyslogkey(RequestUtil.getid(6));
//			loginfo.setSysuserkey(loginkey);
//			loginfo.setSysuseraccount(loginaccount);
//			loginfo.setSysusername(loginname);
//			loginfo.setSyspagename(joinPoint.getTarget().getClass().getName()
//					+ "." + joinPoint.getSignature().getName());
//			loginfo.setSysclassnameen(joinPoint.getTarget().getClass()
//					.getName());
//			loginfo.setSyslogmothoden(joinPoint.getSignature().getName());
//			loginfo.setSyslogmothodcn(getControllerBeforeMethodDescription(joinPoint));
//			loginfo.setSysipaddress(ip);
//			loginfo.setSyslogdate(RequestUtil.getDateTime());
////			syslogservice.savelog(loginfo);
//		} catch (Exception e) {
//			// 记录本地异常日志
//			System.out.println("==前置通知异常==");
//			System.out.println("异常信息:{}" + e.getMessage());
//		}
	}

	/**
	 * 后置通知 用于拦截Controller层记录用户的操作
	 * 
	 * @param joinPoint
	 *            切点
	 */
	@After("controllerAfterAspect()")
	public void doAfter(JoinPoint joinPoint) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		// 读取session中的用户
//		Tblsysuser user = SessionUser.getsession(request);
//		String loginname = "";
//		String loginaccount = "";
//		String loginkey ="";
//		if(null !=user){
//			 loginname = user.getSysusername();
//			 loginaccount = user.getSysaccount();
//			 loginkey = user.getSysuserkey();
//		}
//		// 请求的IP
//		String ip = RequestUtil.getIpAddr(request);
//		try {
//			Tblsyslog loginfo = new Tblsyslog();
//			loginfo.setSyslogkey(RequestUtil.getid(6));
//			loginfo.setSysuserkey(loginkey);
//			loginfo.setSysuseraccount(loginaccount);
//			loginfo.setSysusername(loginname);
//			loginfo.setSyspagename(joinPoint.getTarget().getClass().getName()
//					+ "." + joinPoint.getSignature().getName());
//			loginfo.setSysclassnameen(joinPoint.getTarget().getClass()
//					.getName());
//			loginfo.setSyslogmothoden(joinPoint.getSignature().getName());
//			loginfo.setSyslogmothodcn(getControllerAfterMethodDescription(joinPoint));
//			loginfo.setSysipaddress(ip);
//			loginfo.setSyslogdate(RequestUtil.getDateTime());
////			syslogservice.savelog(loginfo);
//		} catch (Exception e) {
//			// 记录本地异常日志
//			System.out.println("==后置通知异常==");
//			System.out.println("异常信息:{}" + e.getMessage());
//		}
	}

	/**
	 * 异常通知 用于拦截service层记录异常日志
	 * 
	 * @param joinPoint
	 * @param e
	 */
	@AfterThrowing(pointcut = "serviceAspect()", throwing = "e")
	public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
//		// 读取session中的用户
//		Tblsysuser user = SessionUser.getsession(request);
//		// 获取请求ip
//		String ip = request.getRemoteAddr();
//		// 获取用户请求方法的参数并序列化为JSON格式字符串
//		String params = "";
//		if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
//			for (int i = 0; i < joinPoint.getArgs().length; i++) {
//				params += joinPoint.getArgs()[i] + ";";
//			}
//		}
//		try {
//			/* ========控制台输出========= */
//			System.out.println("=====异常通知开始=====");
//			System.out.println("异常代码:" + e.getClass().getName());
//			System.out.println("异常信息:" + e.getMessage());
//			System.out.println("异常方法:"
//					+ (joinPoint.getTarget().getClass().getName() + "."
//							+ joinPoint.getSignature().getName() + "()"));
//			System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));
//			System.out.println("请求人:" + user.getSysusername());
//			System.out.println("请求IP:" + ip);
//			System.out.println("请求参数:" + params);
//			/* ==========数据库日志========= */
//			System.out.println("=====异常通知结束=====");
//		} catch (Exception ex) {
//			// 记录本地异常日志
//			System.out.println("==异常通知异常==");
//			System.out.println("异常信息:{}" + ex.getMessage());
//		}
//		/* ==========记录本地异常日志========== */
//		System.out.println("异常方法:" + joinPoint.getTarget().getClass().getName()
//				+ joinPoint.getSignature().getName());
//		System.out.println("异常代码:" + e.getClass().getName());
//		System.out.println("异常信息:" + e.getMessage());
//		System.out.println("参数:" + params);
	}

	/**
	 * 获取注解中对方法的描述信息 用于service层注解
	 * 
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	public static String getServiceMthodDescription(JoinPoint joinPoint)
			throws Exception {
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		Class targetClass = Class.forName(targetName);
		Method[] methods = targetClass.getMethods();
		String description = "";
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					description = method.getAnnotation(SystemServiceLog.class)
							.description();
					break;
				}
			}
		}
		return description;
	}

	/**
	 * 获取注解中对方法的描述信息 用于Controller层注解
	 * 
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	public static String getControllerAfterMethodDescription(JoinPoint joinPoint)
			throws Exception {
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		Class targetClass = Class.forName(targetName);
		Method[] methods = targetClass.getMethods();
		String description = "";
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					description = method.getAnnotation(
							SystemControllerAfterLog.class).description();
					break;
				}
			}
		}
		return description;
	}

	/**
	 * 获取注解中对方法的描述信息 用于Controller层注解
	 * 
	 * @param joinPoint
	 *            切点
	 * @return 方法描述
	 * @throws Exception
	 */
	public static String getControllerBeforeMethodDescription(
			JoinPoint joinPoint) throws Exception {
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		Object[] arguments = joinPoint.getArgs();
		Class targetClass = Class.forName(targetName);
		Method[] methods = targetClass.getMethods();
		String description = "";
		for (Method method : methods) {
			if (method.getName().equals(methodName)) {
				Class[] clazzs = method.getParameterTypes();
				if (clazzs.length == arguments.length) {
					description = method.getAnnotation(
							SystemControllerBeforeLog.class).description();
					break;
				}
			}
		}
		return description;
	}
}
