package com.ff.base.interceptor;

import com.ff.base.constant.Constants;
import com.ff.base.datasource.DynamicDataSourceContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 数据源切换拦截器
 *
 * @author liukang
 */
@Component
public class DataSourceSwitchInterceptor implements HandlerInterceptor {

    /**
     * 请求前切换数据源
     *
     * @param request  请求对象
     * @param response 响应对象
     * @param handler  请求处理器
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 切换数据源
        String tenantId = request.getHeader(Constants.TENANT_ID);
        if (tenantId != null) {
            DynamicDataSourceContextHolder.setDataSourceType(tenantId);
        }
        return true;
    }

    /**
     * 请求结束后清除数据源
     *
     * @param request  请求对象
     * @param response 响应对象
     * @param handler  请求处理器
     * @param ex       异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        DynamicDataSourceContextHolder.clearDataSourceType();
    }


}
