/**
 *
 */
package org.springblade.core.mp.tenant;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import lombok.RequiredArgsConstructor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springblade.core.constant.BladeConstant;
import org.springblade.core.mp.properties.TenantProperties;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.SmartInitializingSingleton;

import java.util.Arrays;
import java.util.List;

/**
 * @author wookvn
 *
 */
@RequiredArgsConstructor
public class PlatomixTenantHandler implements TenantLineHandler, SmartInitializingSingleton {

    private final TenantProperties tenantProperties;

    /**
     * 需要排除进行自定义的多租户表
     */
    private final List<String> defaultExcludeTableList = Arrays.asList(
            "blade_user", "blade_user_dept", "blade_dict", "blade_dict_biz", //"blade_dept", "blade_role",
            "blade_tenant", "blade_user_web", "blade_user_other", "blade_param",
            "blade_role_menu", "blade_role_scope");

    /**
     * 需要排除自定义的多租户表前缀
     */
    private final List<String> defaultExcludeTablePrefixList = Arrays.asList("sys_");

    @Override
    public Expression getTenantId() {
        return new StringValue(Func.toStr(AuthUtil.getTenantId(), BladeConstant.UNKNOWN_TENANT_ID));
    }

    @Override
    public String getTenantIdColumn() {
        return tenantProperties.getTenantIdColumn();
    }

    @Override
    public boolean ignoreTable(String tableName) {
        return ( AuthUtil.isRealAdministrator()
        		|| tenantProperties.isIgnoreTable()
                || defaultExcludeTableList.contains(tableName)
                || tenantProperties.getExclusionTableNames().contains(tableName)
                || defaultExcludeTablePrefixList.stream().anyMatch(f -> tableName.startsWith(f))
                || tenantProperties.getExclusionTableNamePrefix().stream().anyMatch(f -> tableName.startsWith(f)))
                && !tenantProperties.getIncludeTableNames().contains(tableName);
    }

    @Override
    public void afterSingletonsInstantiated() {

    }
}
