package com.ruoyi.framework.config;

import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.solon.MyBatisFlexCustomizer;
import com.ruoyi.common.web.domain.BaseEntity;
import com.ruoyi.framework.impl.DomainInsertListenerImpl;
import com.ruoyi.framework.impl.DomainUpdateListenerImpl;
import org.noear.solon.annotation.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Mybatis-Flex初始化配置
 * @author ruoyi
 */
@Configuration
public class MybatisFlexConfig implements MyBatisFlexCustomizer {

    private static final Logger log = LoggerFactory.getLogger("mybatis-flex-sql");

    @Override
    public void customize(FlexGlobalConfig flexGlobalConfig) {
        globalConfig(flexGlobalConfig);
        sqlLog();
    }

    /**
     * 全局配置
     */
    private void globalConfig(FlexGlobalConfig flexGlobalConfig) {
        // 注册 insertListener
        flexGlobalConfig.registerInsertListener(new DomainInsertListenerImpl<>(), BaseEntity.class);
        // 注册 updateListener
        flexGlobalConfig.registerUpdateListener(new DomainUpdateListenerImpl<>(), BaseEntity.class);
    }

    /**
     * SQL打印
     */
    private void sqlLog() {
        // 开启审计功能（SQL打印分析的功能是使用 SQL审计模块完成的）
        AuditManager.setAuditEnable(true);

        // 设置 SQL审计收集器
        AuditManager.setMessageCollector(auditMessage ->
                log.info("SQL:【{}】, 耗时:【{}ms】", auditMessage.getFullSql(), auditMessage.getElapsedTime())
        );
    }

}
