package com.jiuzhekan.cbkj.common.aopConfig;

import com.jiuzhekan.cbkj.common.annotaionUtil.TargetDataSource;
import com.jiuzhekan.cbkj.common.multipleDataSource.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Order(-1)
@Component
@Slf4j
public class DynamicDataSourceAspect {
    //改变数据源
    @Before("@annotation(targetDataSource)")
    public void changeDataSource(JoinPoint joinPoint, TargetDataSource targetDataSource) {
        String dbid = targetDataSource.value();
        if (!DynamicDataSourceContextHolder.isContainsDataSource(dbid)) {
            log.error("数据源 " + dbid + " 不存在使用默认的数据源 -> " + joinPoint.getSignature());
        } else {
            DynamicDataSourceContextHolder.setDataSourceType(dbid);
        }
    }

    @After("@annotation(targetDataSource)")
    public void clearDataSource(TargetDataSource targetDataSource) {
        log.debug("清除数据源 " + targetDataSource.value());
        DynamicDataSourceContextHolder.clearDataSourceType();
    }

    @AfterThrowing("@annotation(targetDataSource)")
    public void  throwClearDataSource(TargetDataSource targetDataSource){
        log.debug("清除数据源 " + targetDataSource.value());
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}