package com.starry.admin.common.mybatis.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.starry.admin.utils.SecurityUtils;
import com.starry.common.utils.StringUtils;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.stereotype.Component;

/**
 * @author admin 多租户处理器
 * @since 2023/3/7
 */
@Slf4j
@Component
public class MyTenantLineHandler implements TenantLineHandler {

    /**
     * 排除过滤的表
     */
    private static final String[] TABLE_FILTER = {"sys_login_log", "sys_menu", "sys_tenant_package", "sys_tenant",
            "sys_dict", "sys_dict_data", "sys_administrative_area_dict_info"};

    /**
     * 排除过滤的表前缀
     */
    private static final String[] TABLE_PRE = {"qrtz", "gen"};

    @Override
    public Expression getTenantId() {
        // 取出当前请求的服务商ID，通过解析器注入到SQL中。
        String tenantId = SecurityUtils.getTenantId();
        // if (!StrUtil.isBlankIfStr(tenantId)) {
        // throw new CustomException("租户信息获取异常");
        // }
        return new StringValue(tenantId);
    }

    /**
     * 跳过不需要加多租户的表
     */
    @Override
    public boolean ignoreTable(String tableName) {
        String threadName = Thread.currentThread().getName();
        if (threadName.contains("schedule")) {
            return true;
        }
        String prefix = StringUtils.substringBefore(tableName, "_");
        return Arrays.asList(TABLE_FILTER).contains(tableName) || Arrays.asList(TABLE_PRE).contains(prefix);
    }
}
