package com.czg.config;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.audit.AuditManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

/**
 * @author Administrator
 */
@Configuration
@Slf4j(topic = "mybatis-flex-sql")
public class MybatisFlexConfig {
    public MybatisFlexConfig() {
        //开启审计功能
        AuditManager.setAuditEnable(true);

        //设置 SQL 审计收集器
        AuditManager.setMessageCollector(auditMessage ->
                log.info("[sql] time: {}, size: {}, sql:\n{}",
                        auditMessage.getElapsedTime(), auditMessage.getQueryCount(), compressSql(auditMessage.getFullSql())));
    }

    /**
     * 精简SQL：去除多余换行、制表符、连续空格，保留语法必需空格
     *
     * @param originalSql 原始带换行/空格的SQL
     * @return 精简后的SQL
     */
    public static String compressSql(String originalSql) {
        if (StrUtil.isBlank(originalSql)) {
            return "";
        }
        // 1. 替换所有换行、制表符为单个空格
        String tempSql = originalSql.replaceAll("\\r\\n|\\r|\\n|\\t", " ");
        // 2. 替换多个连续空格为单个空格
        tempSql = tempSql.replaceAll("\\s+", " ");
        // 3. 去除首尾空格
        return tempSql.trim();
    }
}
