package com.ruoyi.framework.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.ruoyi.common.enums.DataSourceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.util.Set;

@Service
public class DynamicDataSourceService {
    
    @Autowired
    @Qualifier("dynamicDataSource")
    private DynamicDataSource dynamicDataSource;
    
    @Value("${spring.datasource.druid.master.url}")
    private String masterUrl;
    
    @Value("${spring.datasource.druid.master.username}")
    private String username;
    
    @Value("${spring.datasource.druid.master.password}")
    private String password;
    
    /**
     * 创建并添加数据源
     */
    public boolean createAndAddDataSource(String dataSourceName) {
        try {
            if (dynamicDataSource.containsDataSource(dataSourceName)) {
                return true; // 数据源已存在
            }
            
            // 构建数据库URL
            String newUrl = buildDatabaseUrl(dataSourceName);
            
            // 创建Druid数据源
            DruidDataSource newDataSource = new DruidDataSource();
            newDataSource.setUrl(newUrl);
            newDataSource.setUsername(username);
            newDataSource.setPassword(password);
            newDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
            
            // 设置Druid连接池参数（使用与主数据源相同的配置）
            newDataSource.setInitialSize(5);
            newDataSource.setMinIdle(5);
            newDataSource.setMaxActive(20);
            newDataSource.setMaxWait(60000);
            newDataSource.setTimeBetweenEvictionRunsMillis(60000);
            newDataSource.setMinEvictableIdleTimeMillis(300000);
            
            // 测试连接
            try {
                newDataSource.init();
                Connection connection = newDataSource.getConnection();
                connection.close();
            } catch (Exception e) {
               System.out.println("测试连接数据库失败: "+ dataSourceName+e);;
                newDataSource.close();
                return false;
            }
            
            // 添加到动态数据源
            dynamicDataSource.addTargetDataSource(dataSourceName, newDataSource);

            return true;
            
        } catch (Exception e) {

            return false;
        }
    }
    
    /**
     * 切换数据源
     */
    public boolean switchDataSource(String dataSourceName) {
        try {
            if (!dynamicDataSource.containsDataSource(dataSourceName)) {
                if (!createAndAddDataSource(dataSourceName)) {
                    return false;
                }
            }
            
            DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);

            return true;
            
        } catch (Exception e) {
            System.out.println(e);
            return false;
        }
    }
    
    /**
     * 切换回主数据源
     */
    public void switchToMaster() {
        DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER.name());
    }
    
    /**
     * 移除数据源
     */
    public void removeDataSource(String dataSourceName) {
        try {
            dynamicDataSource.removeTargetDataSource(dataSourceName);

        } catch (Exception e) {

        }
    }

    public void clearDataSource() {
        DynamicDataSourceContextHolder.clearDataSourceType();

    }
    /**
     * 构建数据库URL
     */
    private String buildDatabaseUrl(String databaseName) {
        // 从主URL提取基础部分
        String baseUrl = masterUrl.substring(0, masterUrl.lastIndexOf("/") + 1);
        // 构建新数据库的URL
        return baseUrl + databaseName + "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8";
    }
    
    /**
     * 获取所有数据源名称
     */
    public Set<String> getDataSourceNames() {
        return dynamicDataSource.getDataSourceNames();
    }
}