package cn.qinys.platform.upms.config.mybatisplus;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import cn.qinys.platform.upms.properties.TenantProperties;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import jakarta.annotation.Resource;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;




/**
 * Description:
 *
 * @author tanlie
 * Date: 2024/2/22 11:27
 */
@Configuration
public class MyBatisPlusConfig {

    @Resource
    private TenantProperties tenantProperties;

    /**
     * 添加租户插件
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(this.tenantLineHandler())); //多租户插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加
        // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
        return interceptor;
    }

    private TenantLineHandler tenantLineHandler() {
        return new TenantLineHandler() {
            @Override
            public Expression getTenantId() {
                String tenantId = TenantContextHolder.getTenantId();
                if (!StringUtils.hasLength(tenantId)) {
                    return new NullValue();
                }
                return new StringValue(tenantId);
            }

            @Override
            public String getTenantIdColumn() {
                return "tenant_id";
            }

            @Override
            public boolean ignoreTable(String tableName) {
                String tenantId = TenantContextHolder.getTenantId();
                // 租户中ID 为空，查询全部，不进行过滤
                if (!StringUtils.hasLength(tenantId)) {
                    return Boolean.TRUE;
                }
                // 这里可以判断是否过滤表
                return tenantProperties.getIgnoreTables().contains(tableName);
            }
        };
    }


}
