package com.erp.tenant.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MyBatis Plus 多租户配置
 * 自动填充 tenant_id、created_at、updated_at 等字段
 */
@Slf4j
@Configuration
public class TenantMybatisConfig {

    /**
     * 租户行级拦截器（可选启用，需要表有 tenant_id 列）
     * 注意：确保 TenantContextFilter 在请求开始时正确设置了租户上下文
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 如果使用租户行级隔离，启用此拦截器
        // interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
        //     @Override
        //     public Expression getTenantId() {
        //         return new LongValue(TenantContext.getCurrentTenantId());
        //     }
        //
        //     @Override
        //     public String getTenantIdColumn() {
        //         return "tenant_id";
        //     }
        //
        //     @Override
        //     public boolean ignoreTable(String tableName) {
        //         // 忽略不需要租户隔离的表
        //         return false;
        //     }
        // }));
        return interceptor;
    }

    /**
     * 自动填充处理器
     * 在插入/更新时自动填充 tenant_id、created_at、updated_at 等字段
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                Long tenantId = TenantContext.getCurrentTenantId();
                if (tenantId != null) {
                    this.strictInsertFill(metaObject, "tenantId", Long.class, tenantId);
                }
                this.strictInsertFill(metaObject, "createdAt", java.time.LocalDateTime.class, java.time.LocalDateTime.now());
                this.strictInsertFill(metaObject, "updatedAt", java.time.LocalDateTime.class, java.time.LocalDateTime.now());
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.strictUpdateFill(metaObject, "updatedAt", java.time.LocalDateTime.class, java.time.LocalDateTime.now());
            }
        };
    }
}
