package com.zd.common.security.aspect;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static com.zd.common.core.constant.SecurityConstants.DB;

/**
 * @author hanson
 */
@Aspect
@Component
@Slf4j
public class ServiceAspect {

    @Pointcut("execution(* com.zd.*.service.impl..*.*(..))")
    public void pointcut() {}

    @Before("pointcut()")
    public void before(){
        // 请求开始时间
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (sra != null) {
            HttpServletRequest request = sra.getRequest();
            String db = request.getHeader(DB);
            if (StringUtils.hasLength(db)) {
                DynamicDataSourceContextHolder.push(db);
            }
        }
    }

    @After("pointcut()")
    public void after() {
        DynamicDataSourceContextHolder.poll();
    }
}
