package com.mortals.xhx.base.framework.aspect;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.mortals.framework.service.ILogService;
import com.mortals.framework.service.impl.FileLogServiceImpl;
import com.mortals.xhx.base.system.oper.service.OperLogService;

/**
 * 操作日志记录
 */
@Component
public class OperlogAspect extends FileLogServiceImpl   implements ILogService {

    private final static Logger logger = LoggerFactory.getLogger(OperlogAspect.class);

    @Autowired
    private OperLogService operLogService;

    @Override
    public void doHandlerLog(String platformMark, Long userId, String userName, String loginName, String requestUrl,
            String content, String ip, Date logDate) {
        super.doHandlerLog(platformMark, userId, userName, loginName, requestUrl, content, ip, logDate);
        operLogService.insertOperLog(ip, requestUrl, userId, userName, loginName, content);
    }

    @Override
    public void doHandlerLog(String platformMark, String loginName, String requestUrl, String content, String ip) {
        // operLogService.insertOperLog(ip, requestUrl, null, "", loginName,
        // content);
        this.doHandlerLog(platformMark, null, "", loginName, requestUrl, content, ip, new Date());
    }

    @Pointcut("execution(public  * com.mortals.xhx..*Controller.*(..))")
    public void accessLog() {
    }

    @Before("accessLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // url
        logger.info("ip[{}]url[{}]", request.getRemoteAddr(), request.getRequestURL());
        // 参数第1和第2个参数为HttpServletRequest request, HttpServletResponse
        // response
        if (joinPoint.getArgs().length > 2) {
            logger.info("args={}", joinPoint.getArgs()[2]);
        } else {
            logger.info("args={}", joinPoint.getArgs());
        }
    }


    @AfterReturning(returning = "object", pointcut = "accessLog()")
    public void doAfterReturning(Object object) {
        if (null != object) {
            logger.info("response={}", object.toString());
        }
    }
}
