package com.yfd.platform.datasource;

import cn.hutool.core.util.StrUtil;
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.springframework.stereotype.Component;

import java.lang.reflect.Method;

/******************************
 * 用途说明:
 * 作者姓名: wxy
 * 创建时间: 2022/9/23 17:50
 ******************************/
@Aspect
@Component
public class DataSourceAspect {

    @Pointcut("@annotation(com.yfd.platform.datasource.DataSource)")
    public void dataSourcePointCut() {

    }

    private String DataBaseName;

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        if (StrUtil.isNotBlank(DataBaseName)){
            DynamicDataSource.setDataSource(DataBaseName);
        }else {
            DynamicDataSource.setDataSource("master");
        }

        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
        }
    }

    public String getDataBase(Integer type){
        if (type == 1){
            DataBaseName="master";
        }else {
            DataBaseName="slave";
        }
        return DataBaseName;
    }

}
