package com.tofly.common.log.aspect;

import com.tofly.base.api.entity.Log;
import com.tofly.common.core.constant.CommonConstants;
import com.tofly.common.core.util.SpringContextHolder;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.common.log.event.SysLogEvent;
import com.tofly.common.log.util.SysLogUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author Administrator
 * @date 2019/8/30  17:23
 */

@Aspect
@Slf4j
public class LogAspect {
	// 配置织入点
	@Pointcut("@annotation(com.tofly.common.log.annotation.ToFlyAppLog)")
	public void logPointCut() {
	}
	
	@Before(value="logPointCut()")
	public void beforeLog(JoinPoint joinPoint) {
		//handleLog(joinPoint);
	}
	
	@After(value="logPointCut()")
	public void afterLog(JoinPoint joinPoint) {
		//handleLog(joinPoint);
	}
	
	@Around(value="logPointCut()")
	@SneakyThrows
	public Object round(ProceedingJoinPoint joinPoint) {
		return handleLog(joinPoint);
	}


	@SneakyThrows
	public Object handleLog(final ProceedingJoinPoint joinPoint){
//		try {
			ToFlyAppLog controllerLog = getAnnotationLog(joinPoint);
			if(controllerLog==null) {
				return null;
			}
			/*HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			System.out.println("IP:"+request.getRemoteAddr());*/
			long startTime = System.currentTimeMillis();//开始时间

	        Object[] args = joinPoint.getArgs();//获取参数数组

			Object o=null;
			String logg="content:"+controllerLog.title();
			Log sysLog= SysLogUtils.getSysLog();
			if(CommonConstants.LOG_LOGIN.equals(controllerLog.type())){
//				String[] parameterNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
//				for (int i =0 ,len=parameterNames.length;i < len ;i++){
//					log.info("参数名："+ parameterNames[i] + " = " +args[i]);
//					if("username".equals(parameterNames[i])){
//						logg += ":"+args[i];
//					}
//				}
				Map m=(Map)args[1];
				logg += " :"+m.get("username");

				sysLog.setCreateBy((String)m.get("username"));
			}

	        try {
				o = joinPoint.proceed(args); //执行操作
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				sysLog.setException(e.getMessage());
				sysLog.setType(CommonConstants.LOG_EXCEPTION);
				throw e;
			}finally {
				long endTime = System.currentTimeMillis();//结束时间
				sysLog.setTitle(logg);
				sysLog.setTime(endTime-startTime);
				sysLog.setType(controllerLog.type());
				SpringContextHolder.publishEvent(new SysLogEvent(sysLog));
				log.info(logg);
			}


//			String logg="title:"+controllerLog.title();

			// 设置方法名称
//			String className = joinPoint.getTarget().getClass().getName();
//			String methodName = joinPoint.getSignature().getName();


			return o;
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			return null;
//		}
	}

	//判断是否存在注解
	private ToFlyAppLog getAnnotationLog(JoinPoint joinPoint) throws Exception {


		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		Method method = methodSignature.getMethod();
		if (method != null) {
			return method.getAnnotation(ToFlyAppLog.class);
		}
		return null;
	}
}
