package com.loan.system.utils.logUtils;


import com.alibaba.fastjson.JSON;
import com.loan.system.domain.entity.ExceptionLog;
import com.loan.system.service.ExceptionLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 操作日志、异常日志处理
 *
 * @author chen
 * @date 2019/10/01
 */
@Aspect
@Component
public class OperLogAspect {
    
    @Autowired
    ExceptionLogService exceptionService;

    /**
     * 异常日志切入点
     */
    @Pointcut("execution(* com.hdu.maintenance.controller..*.*(..))")
    public void exceptionLogPoint() {
    }

    @AfterThrowing(pointcut = "exceptionLogPoint()", throwing = "e")
    public void exceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        ExceptionLog exceptionLog = new ExceptionLog();
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = method.getName();
            methodName = className + "." + methodName;

            String[] paraNames = signature.getParameterNames();
            Object[] args = joinPoint.getArgs();
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            if (paraNames != null && paraNames.length > 0 && args != null && args.length > 0) {
                for (int i = 0; i < paraNames.length; i++) {
                    sb.append("\"" + paraNames[i] + "\":" + JSON.toJSONString(args[i]) + ",");
                }
            }
            sb.delete(sb.length() - 1, sb.length() + 1);
            sb.append("}");
            String me_param = sb.toString();
            exceptionLog.setMethodParam(me_param);
            exceptionLog.setExceptionMethod(methodName); // 请求方法名
            exceptionLog.setExceptionName(e.getClass().getName()); // 异常名称
            exceptionLog.setExceptionMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())); // 异常信息
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (!(authentication instanceof AnonymousAuthenticationToken)) {
                String currentUserName = authentication.getName();
                exceptionLog.setOperUserName(currentUserName); // 用户名
            }
            exceptionLog.setOperUri(request.getRequestURI()); // 操作URI
            exceptionLog.setOperIp(IPUtils.getIpAddr(request)); // 操作员IP
            exceptionLog.setOperTime(new Date());
            exceptionService.insertExceptionLog(exceptionLog);
        } catch (Exception exception) {
            e.printStackTrace();
        }
    }


    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }


}