//package org.jeecg.config.saas;
//
//import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
//import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
//import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
//import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.jdbc.core.JdbcTemplate;
//
//import javax.annotation.Resource;
//import javax.sql.DataSource;
//import java.util.LinkedHashMap;
//import java.util.List;
//import java.util.Map;
//
//@Configuration(proxyBeanMethods = false)
//public class CustomDynamicDataSourceProvider implements DynamicDataSourceProvider {
//
//    @Autowired
//    private DynamicDataSourceProperties properties;
//    @Autowired
//    private DefaultDataSourceCreator dataSourceCreator;
//    @Resource(name = "dataSource")
//    private DataSource masterDataSource;
//
//    @Override
//    public Map<String, DataSource> loadDataSources() {
//        System.out.println("[DynamicDS] >>> 开始注册静态数据源...");
//        Map<String, DataSourceProperty> yamlProps = properties.getDatasource();
//        Map<String, DataSource> result = new LinkedHashMap<>(yamlProps.size());
//        yamlProps.forEach((name, prop) -> {
//            result.put(name, dataSourceCreator.createDataSource(prop));
//            System.out.println("[DynamicDS] 已注册静态数据源: " + name + ", URL=" + prop.getUrl());
//        });
//
//        try {
//            System.out.println("[DynamicDS] >>> 准备从主库加载动态数据源...");
//            JdbcTemplate jdbc = new JdbcTemplate(masterDataSource);
//            List<Map<String, Object>> tenants = jdbc.queryForList(
//                    "SELECT code, db_url, db_name, db_username, db_password, db_driver FROM sys_data_source WHERE del_flag=0"
//            );
//            for (Map<String, Object> row : tenants) {
//                String code = (String) row.get("code");
//                String dbUrl = (String) row.get("db_url");
//                String dbName = (String) row.get("db_name");
//                String dbUser = (String) row.get("db_username");
//                String dbPass = (String) row.get("db_password");
//                String dbDriver = (String) row.get("db_driver");
//
//                String url = buildFinalJdbcUrl(dbUrl, dbName);
//
//                // ---友好日志---
//                System.out.println("[DynamicDS] 预注册数据源: code=" + code + " url=" + url + " user=" + dbUser);
//
//                if (!result.containsKey(code)) {
//                    try {
//                        DataSourceProperty dsp = new DataSourceProperty();
//                        dsp.setUrl(url);
//                        dsp.setUsername(dbUser);
//                        dsp.setPassword(dbPass);
//                        dsp.setDriverClassName(dbDriver);
//                        // 连接测试（提前失败不会进池）
//                        DataSource ds = dataSourceCreator.createDataSource(dsp);
//                        ds.getConnection().close();
//                        result.put(code, ds);
//                        System.out.println("[DynamicDS] 已注册动态数据源: " + code);
//                    } catch (Exception e) {
//                        // 注册失败友好处理，不死循环
//                        System.err.println("[DynamicDS] 数据源注册失败[" + code + "]，原因: " + e.getMessage());
//                        // 不注册到池里，继续下一个，生产可用日志报警
//                    }
//                } else {
//                    System.out.println("[DynamicDS] 已存在同名数据源，跳过: " + code);
//                }
//            }
//            System.out.println("[DynamicDS] 动态数据源加载完毕，共有 " + result.size() + " 个数据源: " + result.keySet());
//        } catch (Exception e) {
//            System.err.println("[DynamicDS] 加载动态数据源出错: " + e.getMessage());
//            e.printStackTrace();
//        }
//
//        return result;
//    }
//
//    private String buildFinalJdbcUrl(String dbUrl, String dbName) {
//        String baseUrl = dbUrl;
//        String suffix = "characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai";
//        if (!dbUrl.startsWith("jdbc:mysql://")) {
//            throw new IllegalArgumentException("db_url必须以jdbc:mysql://开头: " + dbUrl);
//        }
//
//        String urlLower = dbUrl.toLowerCase();
//        String dbNameLower = dbName == null ? "" : dbName.toLowerCase();
//
//        boolean hasDb = urlLower.matches("jdbc:mysql://[^/]+/[^?]+.*");
//        boolean dbMatches = hasDb && urlLower.contains("/" + dbNameLower);
//
//        String finalUrl;
//
//        if (dbMatches) {
//            if (baseUrl.contains("?")) {
//                finalUrl = baseUrl + "&" + suffix;
//            } else {
//                finalUrl = baseUrl + "?" + suffix;
//            }
//        } else {
//            if (baseUrl.endsWith("/")) {
//                finalUrl = baseUrl + dbName + "?" + suffix;
//            } else {
//                finalUrl = baseUrl + "/" + dbName + "?" + suffix;
//            }
//        }
//        return finalUrl;
//    }
//}
