package com.yunzhupaas.visualdata.controller.aop;

/**
 * @author 云筑产品开发平台组
 * @version V3.1.0
 * @copyright 深圳市乐程软件有限公司（http://www.szlecheng.cn）
 * @date 2024-03-26
 */

import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.database.util.TenantDataSourceUtil;
import com.yunzhupaas.util.ServletUtil;
import com.yunzhupaas.util.StringUtil;
import com.yunzhupaas.util.UserProvider;
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 VisualBindAspect {


    
    @Autowired
    private ConfigValueUtil configValueUtil;

    @Pointcut("within(com.yunzhupaas.visualdata.controller.VisualCategoryController || com.yunzhupaas.visualdata.controller.VisualMapController) && (execution(* com.yunzhupaas.*.controller.VisualCategoryController.list(..))  || execution(* com.yunzhupaas.*.controller.VisualMapController.dataInfo(..)))")
    public void bindDataSource() {

    }

    /**
     * NoDataSourceBind 不需要绑定数据库的注解
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("bindDataSource()")
    public Object doAroundService(ProceedingJoinPoint pjp) throws Throwable {
        if (configValueUtil.isMultiTenancy()) {
            String jwtToken = ServletUtil.getRequest().getHeader("Authorization");
            if(StringUtil.isEmpty(jwtToken)){
                //兼容旧版大屏前端
                jwtToken = ServletUtil.getRequest().getParameter("token");
            }
            UserInfo userInfo = UserProvider.getUser(jwtToken);
            if(userInfo.getTenantId() == null){
                throw new RuntimeException("租户信息为空: " + jwtToken);
            }
            //设置租户
            TenantDataSourceUtil.switchTenant(userInfo.getTenantId());
        }
        Object obj = pjp.proceed();
        return obj;
    }
}


