package com.unis.core.config.log;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName MybatisPlusConfig
 * @Description:
 * @Author geoffrey
 * @Date 2021/10/8
 * @Version V1.0
 **/
@Configuration
@Slf4j
public class MybatisPlusConfig {

    @javax.annotation.Resource
    private LogMapperConfig logMapperConfig;

    /**
     * sql打印日志
     * package命名为mapper方式实现
     *
     * @methodName: configureLoggers
     * @return: void
     * @author: ybw
     * @date: 2024/7/4
     **/
    @Bean
    public void configureLoggers() {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        Set<String> mapperPackages = findPackagesWithMapper();
        if (CollectionUtils.isEmpty(mapperPackages)) {
            return;
        }
        mapperPackages.forEach(packageName -> {
            // 设置packageName包的日志级别为DEBUG
            context.getLogger(packageName).setLevel(Level.DEBUG);
        });
    }

    /**
     * 扫描包下所有mapper
     *
     * @methodName: findPackagesWithMapper
     * @return: java.util.Set<java.lang.String>
     * @author: ybw
     * @date: 2024/7/4
     **/
    public Set<String> findPackagesWithMapper() {
        // 使用Spring的PathMatchingResourcePatternResolver来查找资源
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);

        // 示例资源路径，根据实际情况调整
        String packageSearchPath = "classpath*:**/" + logMapperConfig.getBasePackage() + "/**/*.class";
        try {
            Resource[] resources = resolver.getResources(packageSearchPath);
            Set<String> packagesWithMapper = new HashSet<>();
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                    String packageName = ClassUtils.getPackageName(metadataReader.getClassMetadata().getClassName());
                    if (packageName.contains(logMapperConfig.getPackageKeyword())) {
                        packagesWithMapper.add(packageName);
                    }
                }
            }
            return packagesWithMapper;
        } catch (IOException e) {
            log.error("findPackagesWithMapper error:", e);
        }
        return new HashSet<>();
    }
}
