package com.dcit.danger.aspect;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.dcit.logging.dto.LoggingDTO;
import com.dcit.logging.support.factory.LogTaskFactory;
import com.dcit.logging.support.manager.LogExeManager;

import lombok.extern.slf4j.Slf4j;

@Aspect
@Component
@Slf4j
public class HttpAspect {

	@Pointcut("execution(public * com.dcit.ioc.controller.*.*(..))")
	public void log(){
	}
	
	@Before("log()")
	public void doBefore(JoinPoint joinPoint){
		
		ServletRequestAttributes attributes =  (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		
		//url
		log.info("url={}", request.getRequestURL());
		
		//method
		log.info("method={}", request.getMethod());
		
		//IP
		log.info("IP={}", request.getRemoteAddr());
		
		//class_method
		log.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() +"."+ joinPoint.getSignature().getName());
		
		//参数
		log.info("args={}", joinPoint.getArgs());
		
				
		LoggingDTO loggingDTO = new LoggingDTO();
		loggingDTO.setUserId(null);
		loggingDTO.setUserIp(request.getRemoteAddr());
		loggingDTO.setRequestApi(request.getRequestURL().toString());
		loggingDTO.setFormMethod(request.getMethod());
		
		Object[] args = joinPoint.getArgs();
		if(args.length>0){
			String params = JSON.toJSONString(args[0]);
			loggingDTO.setRequestArgs(params);
		}
		
		loggingDTO.setClassMethod(joinPoint.getSignature().getDeclaringTypeName() +"."+ joinPoint.getSignature().getName());
		
		LogExeManager.getInstance().executeLogTask(LogTaskFactory.bussinssLog(loggingDTO));
		
	}
	
	@After("log()")
	public void doAfter(){
		log.info("=============Aspect running finished==============");
	}
	
	@AfterReturning(returning="obj",pointcut="log()")
	public void afterReturnning(Object obj){
		log.info("return={}", obj.toString());
	}
}
