package com.sv.api.aop;

import com.sv.annotation.NoPlatform;
import com.sv.annotation.PlatformKey;
import com.sv.api.context.PlatformContext;
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.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class PlatformIdAOP {

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

    @Pointcut("execution(* com.sv.mapper..*.*(..))")
    public void beforeDoMapper() {

    }

    @Around(value = "beforeDoMapper()")
    public Object doPlatform(ProceedingJoinPoint pjp) {
        Object result = null;
        try {
            Method method = ((MethodSignature)pjp.getSignature()).getMethod();
            PlatformKey platformKey = method.getAnnotation(PlatformKey.class);
            if(platformKey != null){
                PlatformContext.changeKey(platformKey.value());
            }
            NoPlatform noPlatform = method.getAnnotation(NoPlatform.class);
            if(noPlatform != null){
                PlatformContext.remove();
            }
        }catch (Exception e){
            logger.error("platform 注入失败",e);
            e.printStackTrace();
        }
        try {
            result = pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }

}
