package com.fjhx.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springblade.core.secure.utils.AuthUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

@Configuration
public class MybatisConfig {

    /**
     * 排除租户表集合
     */
    private static final List<String> excludeTenantTableName = Arrays.asList("logistics_company", "system_config");

    /**
     * 租户插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptorPage() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 拼接逻辑删除字段
        interceptor.addInnerInterceptor(new LogicDeleteInterceptor());

        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
            @Override
            public Expression getTenantId() {
                return new StringValue(AuthUtil.getTenantId());
            }

            @Override
            public boolean ignoreTable(String tableName) {
                return excludeTenantTableName.contains(tableName);
            }

        }));

        // 分页
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        // 乐观锁
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        return interceptor;
    }

}
