package shop.alien.gateway.config;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * MyBatis Plus 自定义配置
 * 解决 fat jar 环境下 mapper XML 重复加载问题
 */
@Configuration
public class MybatisPlusConfig {

    @Autowired
    private DataSource dataSource;

    @Autowired(required = false)
    private MybatisPlusProperties properties;

    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
        factory.setDataSource(dataSource);

        // 配置 MyBatis
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        configuration.setCallSettersOnNulls(true);
        factory.setConfiguration(configuration);

        // 去重加载 mapper XML 文件（按文件名去重，解决 fat jar 中的重复加载问题）
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Map<String, Resource> resourceMap = new LinkedHashMap<>();
        Resource[] resources = resolver.getResources("classpath*:mapper/**/*.xml");
        for (Resource resource : resources) {
            String filename = resource.getFilename();
            if (filename != null && !resourceMap.containsKey(filename)) {
                resourceMap.put(filename, resource);
            }
        }
        factory.setMapperLocations(resourceMap.values().toArray(new Resource[0]));

        // 设置类型别名包
        if (properties != null && properties.getTypeAliasesPackage() != null) {
            factory.setTypeAliasesPackage(properties.getTypeAliasesPackage());
        }

        return factory.getObject();
    }

    @Bean
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
