package com.cf.imes.framework.web.core.filter;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.util.servlet.ServletUtils;
import com.cf.imes.framework.web.config.WebProperties;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.cf.imes.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_SOURCE_CODE_NOT_FOUND;

/**
 * @author there
 * 多数据源过滤器
 */
public class DataSourceFilter extends OncePerRequestFilter {
    //数据源编码
    private static final String DATA_SOURCE_CODE = "dataCode";

    private WebProperties webProperties;

    public DataSourceFilter (WebProperties webProperties) {
        this.webProperties = webProperties;
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        // 只过滤 API 请求的地址
        return !StrUtil.startWithAny(request.getRequestURI(), webProperties.getAdminApi().getPrefix(),
                webProperties.getAppApi().getPrefix());
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String dataSourceCode = request.getHeader(DATA_SOURCE_CODE);
        if(StrUtil.isBlank(dataSourceCode)) {
            ServletUtils.writeJSON(response, CommonResult.error(DATA_SOURCE_CODE_NOT_FOUND));
            return;
        }
        DynamicDataSourceContextHolder.push(dataSourceCode);
        filterChain.doFilter(request, response);
        DynamicDataSourceContextHolder.clear();
    }
}
