package com.yeejoin.amos.boot.biz.config;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.yeejoin.amos.boot.biz.common.interceptors.PermissionInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *
 **/
@Configuration
public class MyBatisPlusConfig {
    /**
     * 自动填充功能
     *
     * @return
     */
    @Bean
    public GlobalConfig globalConfig(MybatisPlusProperties mybatisPlusProperties, MetaHandler metaHandler, MybatisSqlInjector mybatisSqlInjector) {
        GlobalConfig globalConfig = mybatisPlusProperties.getGlobalConfig();
        if (globalConfig == null) {
            globalConfig = new GlobalConfig();
        }
        if (globalConfig.getMetaObjectHandler() == null) {
            globalConfig.setMetaObjectHandler(metaHandler);
        }
        globalConfig.setSqlInjector(mybatisSqlInjector);
        return globalConfig;
    }

    /**
     * pageHelper插件支持
     *
     * @return
     */
    @Bean
    ConfigurationCustomizer mybatisConfigurationCustomizer() {
        return configuration -> configuration.addInterceptor(new com.github.pagehelper.PageInterceptor());
    }

    @ConditionalOnProperty(name = "mybatis.interceptor.enabled", havingValue = "true", matchIfMissing = true)
    @Bean
    public PermissionInterceptor permissionInterceptor() {
        return new PermissionInterceptor();
    }

    @Bean
    public MybatisSqlInjector mybatisSqlInjector() {
        return new MybatisSqlInjector();
    }
}
