package com.brilliance.isc.common.component;

import com.brilliance.isc.bo.Adr;
import com.brilliance.isc.bo.Pta;
import com.brilliance.isc.common.exception.CommonServiceException;
import com.brilliance.isc.constant.ErrorCode;
import com.brilliance.isc.exception.RestBizException;
import com.brilliance.isc.mda.dao.PtaMapper;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AdrCheckAspect {

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

    @Autowired
    private PtaMapper ptaMapper;

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

    @Around("pointcut()")
    public Object handle(ProceedingJoinPoint proceedingJoinPoint) {
        Object[] objects = proceedingJoinPoint.getArgs();
        if (objects != null && objects.length == 1) {
            logger.debug("获取到方法的第一个参数，adr对象");
            Adr adr = (Adr)objects[0];
            if (MdaUtils.isEmpty(adr.getBic())) {
                //如果发现bic为空,需要进一步排查是否为bank
                Pta pta = new Pta();
                pta.setObjinr(adr.getInr());
                pta.setObjtyp("ADR");
                pta = ptaMapper.selectAdrByCon(pta);
                if (pta != null && "B".equals(pta.getPtytyp())) {
                    throw new CommonServiceException("监控到对公客户"+pta.getPtyextkey()+"的BIC更新为空，请联系系统管理员");
                }
            }
        }
        logger.debug("切面完成，执行adr更新方法");
        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());
            }
        }
    }
}
