package com.crm.rely.backend.aspect;

import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.exception.*;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ServiceExceptionAop {
    Logger logger = LoggerFactory.getLogger(RuntimeException.class);

    @Autowired
    private Environment environment;

    private static final String logStr = "class：%s%n,method: %s%n%s,row: %d";

    @Pointcut("execution(* com.*.*.service.*.*(..))")
    public void log() {
    }

    @AfterThrowing(value = "log()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Throwable e) {

        /**
         * 日志打印出错方法+原因
         */
        for (int i = 0; i < environment.getActiveProfiles().length; i++) {
            if (environment.getActiveProfiles()[i].equals("dev")) {
                e.printStackTrace();
                break;
            }
        }
        String declaringClass = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();

        int lineNumber = -1;
        for (int i = 0; i < e.getStackTrace().length; i++) {
            if (declaringClass.equals(e.getStackTrace()[i].getClassName())
                    && methodName.equals(e.getStackTrace()[i].getMethodName())) {

                lineNumber = e.getStackTrace()[i].getLineNumber();
                break;
            }
        }


        logger.error(String.format(logStr, declaringClass, methodName, e, lineNumber));
        if (!(e instanceof ServiceException)
                && !(e instanceof ControllerException)
                && !(e instanceof PayValidatedException)
                && !(e instanceof DataNotFoundException)
                && !(e instanceof LoginException)) {
            /**
             *
             * 抛出系统异常
             */
            throw new RuntimeException(Constants.SYSTEM_ERROR);
        }
    }
}

