package com.yunzhupaas.aop;

import cn.dev33.satoken.context.SaHolder;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.database.util.NotTenantPluginHolder;
import com.yunzhupaas.database.util.TenantDataSourceUtil;
import com.yunzhupaas.util.TenantHolder;
import com.yunzhupaas.util.StringUtil;
import com.yunzhupaas.util.UserProvider;
import com.yunzhupaas.util.data.DataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 *
 * @author 云筑产品开发平台组
 * @version V3.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date 2024/3/15 17:12
 */
@Slf4j
@Aspect
@Component
@Order(1)
public class DataSourceBindAspect {

    @Autowired
    private ConfigValueUtil configValueUtil;

    @Pointcut("within(com.yunzhupaas.*.controller.* || com.yunzhupaas.controller.*)")
    public void bindDataSource() {

    }

    /**
     * NoDataSourceBind 不需要绑定数据库的注解
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("bindDataSource() && !@annotation(com.yunzhupaas.util.NoDataSourceBind)")
    public Object doAroundService(ProceedingJoinPoint pjp) throws Throwable {
//        System.out.println(SaHolder.getRequest().getRequestPath());
        if (configValueUtil.isMultiTenancy()) {
            if(StringUtil.isEmpty(TenantHolder.getDatasourceId())){
                UserInfo userInfo = UserProvider.getUser();
                String url = null;
                try{
                    url = SaHolder.getRequest().getRequestPath();
                }catch (Exception ee){ }
                log.error("租户" + userInfo.getTenantId() + "数据库不存在, URL: {}, TOKEN: {}", url, userInfo.getToken());
                return null;
            }
            return pjp.proceed();
        }
        Object obj = pjp.proceed();
        return obj;
    }


    /**
     * NoDataSourceBind 不需要绑定数据库的注解 加入不切租户库标记
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("bindDataSource() && @annotation(com.yunzhupaas.util.NoDataSourceBind)")
    public Object doAroundService2(ProceedingJoinPoint pjp) throws Throwable {
        try{
            NotTenantPluginHolder.setNotSwitchAlwaysFlag();
            //Filter中提前设置租户信息, 不需要切库的方法进行清除切库
            TenantDataSourceUtil.clearLocalTenantInfo();
            return pjp.proceed();
        }finally {
            NotTenantPluginHolder.clearNotSwitchAlwaysFlag();
        }
    }
}

