package com.ema.admin.config;

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.dialect.DbType;
import com.mybatisflex.core.mybatis.FlexConfiguration;
import com.mybatisflex.spring.boot.ConfigurationCustomizer;
import com.ema.admin.handler.MyBatisFlexInsertListener;
import com.ema.admin.handler.MyBatisFlexUpdateListener;
import com.ema.common.domain.base.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

/**
 * MyBatisFlex配置
 */
@Slf4j
@Configuration
@MapperScan(basePackages = {"com.ema.admin.modules.**.mapper"})
public class MyBatisFlexConfig implements ConfigurationCustomizer {

    public MyBatisFlexConfig() {
//        配置mybatis-flex全局配置
        FlexGlobalConfig globalConfig = FlexGlobalConfig.getDefaultConfig();
        globalConfig.setPrintBanner(true);//是否打印banner
        globalConfig.setDbType(DbType.MYSQL);//数据库方言

//        更新和插入时启用mybatis-flex监听器，设置BaseEntity类
        globalConfig.registerInsertListener(new MyBatisFlexInsertListener(), BaseEntity.class);
        globalConfig.registerUpdateListener(new MyBatisFlexUpdateListener(), BaseEntity.class);

//        逻辑删除的默认值配置，0未删除，1已删除
        globalConfig.setNormalValueOfLogicDelete("0");
        globalConfig.setDeletedValueOfLogicDelete("1");

//        注册自定义主键
//        KeyGeneratorFactory.register("uuid", new UUIDKeyGenerator());

        //        开启审计功能
        AuditManager.setAuditEnable(false);
        //设置 SQL 审计收集器
        AuditManager.setMessageCollector(auditMessage ->
                log.info("\n执行SQL耗时: {} ms  \n执行SQL: {}", auditMessage.getElapsedTime(), auditMessage.getFullSql())
        );
    }

    @Override
    public void customize(FlexConfiguration flexConfiguration) {
//        flexConfiguration.setCacheEnabled(false);//开启或关闭mybatis二级缓存
    }
}