package com.ssm.data;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Order(-10)//保证该AOP在@Transactional之前执行
@Component
public class DataSourceAspect {
    @Before(value = "dataSourceAnnotation()")
    public void before(JoinPoint point) throws Throwable {
        Object target = point.getTarget();
        String method = point.getSignature().getName();
        Class<?> aClass = target.getClass();
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for(Method m:declaredMethods){
            if(m!=null&&m.getName().equals(method) && m.isAnnotationPresent(DataSource.class)) {
                DataSource dataSource = m.getAnnotation(DataSource.class);
                DynamicDataSourceHolder.setDataSourceType(dataSource.value());
            }
        }
        if (StringUtils.isBlank(DynamicDataSourceHolder.getJdbcType())){
            if(StringUtils.startsWithAny(method.toLowerCase(),new String[]{"select","get","count","slave","query"})) {
                DynamicDataSourceHolder.setDataSourceType(DataSourceType.slave.getType());
            }else{
                DynamicDataSourceHolder.setDataSourceType(DataSourceType.master.getType());
            }
        }

//        Method method1 = aClass.getDeclaredMethod(method);
//        boolean annotationPresent = method1.isAnnotationPresent(DataSource.class);
//        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
//            Method m = classz[0].getDeclaredMethod(method, parameterTypes);
//            if (m != null && m.isAnnotationPresent(DataSource.class)) {
//                DataSource data = m.getAnnotation(DataSource.class);
//                DynamicDataSourceHolder.setDataSourceType(data.value());
//                System.out.println(data.value());
//            }
    }


    @Pointcut("@annotation(com.ssm.data.DataSource) || execution(public * com.ssm..dao.impl..*.*(..))")
    public void dataSourceAnnotation(){

    }
}
