package com.ruoyi.component.tenant.filter;


import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.ruoyi.component.core.constant.TenantConstants;
import com.ruoyi.component.core.domain.R;
import com.ruoyi.component.core.util.ServletUtils;
import com.ruoyi.component.core.util.StringUtils;
import com.ruoyi.component.satoken.utils.LoginHelper;
import com.ruoyi.component.tenant.helper.TenantHelper;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class TenantFilter implements Filter {
    public static final String TENANT_ID_HEADER = "Tenant-ID";

    private static final Set<String> IGNORE_URL = new HashSet<>();
    static {
        IGNORE_URL.add("/login");
        IGNORE_URL.add("/captchaImage");
    }
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(!(servletRequest instanceof HttpServletRequest)){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        try {
            String requestURI = request.getRequestURI();
            for (String ignoreUrlMatch : IGNORE_URL) {
                boolean match = ANT_PATH_MATCHER.match(ignoreUrlMatch, requestURI);
                if(match){
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
            String tenantHeader = request.getHeader(TENANT_ID_HEADER);
            boolean login = TenantHelper.isLogin();
            if(login){ // 已经登录
                String tenantId = LoginHelper.getTenantId();
                if("/getInfo".equals(requestURI)){ // 特殊放权接口
                    TenantHelper.setTenantId(tenantId);
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
                Long userId = LoginHelper.getUserId();
                if(TenantConstants.SUPER_ADMIN_ID.equals(userId)){ // 超管前端给什么用什么
                    TenantHelper.setTenantId(tenantHeader);
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
                if(tenantId == null || !tenantId.equals(tenantHeader)){ // 非超管 如果当前用户和前端给的不支持 返回异常
                    ServletUtils.renderString(response, JSONUtil.toJsonStr(R.fail("平台错误")));
                    return;
                }
                TenantHelper.setTenantId(tenantId);
            }else{
                TenantHelper.setTenantId(tenantHeader);
            }
            if(StringUtils.isBlank(TenantHelper.getTenantId())){
                ServletUtils.renderString(response, JSONUtil.toJsonStr(R.fail("未找到对应的平台")));
                return;
            }
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            TenantHelper.clearTenant();
        }


    }
}
