package com.storlead.framework.mybatis.interceptor;

import com.baomidou.mybatisplus.autoconfigure.SpringBootVFS;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.storlead.framework.mybatis.handler.MyMetaObjectHandler;
import com.storlead.framework.mybatis.tenant.StorleadTenantHandler;
import com.storlead.framework.mybatis.tenant.TenantProperties;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.context.ApplicationContext;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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 javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-04-02 09:45
 */
@Configuration
@MapperScan(value={"com.storlead.*.mapper"})
@EnableConfigurationProperties(TenantProperties.class)
@Log4j2
public class MybatisPlusConfig {

    /**
     **  分页 + 多租户行（tenant_id）SQL 解析
     */
    @Bean
    public PaginationInterceptor paginationInterceptor(TenantProperties tenantProperties) {
        PaginationInterceptor interceptor = new PaginationInterceptor().setLimit(-1);
        TenantSqlParser tenantSqlParser = new TenantSqlParser();
        tenantSqlParser.setTenantHandler(new StorleadTenantHandler(tenantProperties));
        List<ISqlParser> sqlParserList = new ArrayList<>();
        sqlParserList.add(tenantSqlParser);
        interceptor.setSqlParserList(sqlParserList);
        return interceptor;
    }
//
//    @Bean
//    public MessageSqlInterceptor messageSqlInterceptor() {
//        // 设置sql的limit为无限制，默认是500
//        return new MessageSqlInterceptor();
//    }

//    public MybatisInterceptor mybatisInterceptor() {
//        // 设置sql的limit为无限制，默认是500
//        return new MybatisInterceptor();
//    }


    @Primary
    @Bean
    public MybatisSqlSessionFactoryBean sqlSessionFactory(DataSource dataSource, ApplicationContext appContext, PaginationInterceptor paginationInterceptor) throws Exception {

        log.error("sqlSessionFactory--先走");

        MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
        mybatisPlus.setDataSource(dataSource);
        mybatisPlus.setVfs(SpringBootVFS.class);

        Resource[] maps = mapperLocations(appContext);
        mybatisPlus.setMapperLocations(maps);

        Interceptor[] plugins = {paginationInterceptor};
        mybatisPlus.setPlugins(plugins);

        MybatisConfiguration mc = new MybatisConfiguration();
        mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        mybatisPlus.setConfiguration(mc);
//        mybatisPlus.setTypeHandlersPackage("com.baomidou.mybatisplus.extension.handlers.MybatisEnumTypeHandler");
//        mybatisPlus.setTypeAliasesPackage("com.storlead..modules.*.pojo");
//        mybatisPlus.setTypeEnumsPackage("com.storlead.sa.modules.console.enums,com.storlead.tems.modules.perform.enums");
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setMetaObjectHandler(new MyMetaObjectHandler());
        mybatisPlus.setGlobalConfig(globalConfig);

        return mybatisPlus;
    }

    /**
     * 获取所有业务包里面的 mybatis的配置
     * 返回所有xml资源
     * **/
    private Resource[] mapperLocations(ApplicationContext appContext) throws IOException {
        String[] basePackages = getBasePackages(appContext);
        List<Resource> resources = new ArrayList<>();
        for (String basePackage : basePackages) {
            // 下面的所有子级
            String packageDir = StringUtils.replace(basePackage, ".", "/");

            System.out.println("packageDir = "+packageDir);
            Resource[] resourcesArray = appContext.getResources("classpath*:mapper/" + packageDir + "/**/*.xml");
            resources.addAll(Arrays.asList(resourcesArray));

            // 项目根级
            Resource[] resourcesArrayRoot = appContext.getResources("classpath*:mapper/" + packageDir + "/*.xml");
            resources.addAll(Arrays.asList(resourcesArrayRoot));
        }

        resources.addAll(Arrays.asList(appContext.getResources("classpath*:mapper/**/*.xml")));
        // 顶根级
        resources.addAll(Arrays.asList(appContext.getResources("classpath*:mapper/*.xml")));

        return resources.toArray(new Resource[resources.size()]);
    }

    /**
     * 获取所有包路径
     * */
    private String[] getBasePackages(ApplicationContext appContext) {
        List<String> basePackages = AutoConfigurationPackages.get(appContext);
        return basePackages.toArray(new String[basePackages.size()]);
    }


}

