package com.brilliance.isc.common.aspect;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import com.brilliance.isc.common.component.PtsptaToolComponent;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.common.vo.PtsptaVo;
import com.brilliance.isc.constant.ErrorCode;
import com.brilliance.isc.exception.RestBizException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Aspect
@Component
public class BeforeSwiftAspect {

    @Autowired
    private PtsptaToolComponent ptsptaToolComponent;

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

    @Pointcut("@annotation(com.brilliance.isc.annotation.BeforeSwift)")
    public void pointcut(){}

    @Around("pointcut()")
    public Object handle(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object[] objects = proceedingJoinPoint.getArgs();
        if (objects != null && objects.length >= 2) {
            logger.debug("获取到方法的第二个参数，补充ptspta属性值");
            Object xxxgrp = objects[1];
            Field[] fields = xxxgrp.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                if (PtsptaVo.class.equals(field.getType())) {
                    PtsptaVo ptspta = Utils.getFieldValue(xxxgrp, field.getName());
                    if (ptsptaToolComponent.ptsIsRolSet(ptspta)) {
                        ptsptaToolComponent.fillPtsptaAllProperties(ptspta);
                    }
                }
            }
        }
        logger.debug("切面完成，执行组报方法");
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        String methodName = proceedingJoinPoint.getSignature().getName();
        try {
            return proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            logger.error("组报: an exception has been throwing in "+className+":"+methodName+"():{}",throwable);
            if(throwable instanceof RestBizException){
                throw (RestBizException) throwable;
            }else {
                throw new RestBizException(ErrorCode.BIZ_COMMON_ERROR, throwable.getMessage());
            }
        }
    }
}
