package com.hzya.frame.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.processor.DsSpelExpressionProcessor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.expression.StandardBeanExpressionResolver;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;

/**
 * @Content
 * @Author 👻👻👻👻👻👻👻👻👻👻 gjh
 * @Date 2023-06-13 17:56
 * @Version 1.0
 */
//@Configuration
public class DataSourceConfig {
    private static final Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
    //dataSource容器
    private static final Map<String, DruidDataSource> DATASOURCEMAP = new HashMap<>();
    private SqlSessionFactory sqlSessionFactory;
    @Resource
    private DataSource dataSource;



    public DruidDataSource dataSource2() {
        DruidDataSource dataSource = createDefaultDataSource(getDataSourceJsonObject());
        return dataSource;
    }


    public DynamicRoutingDataSource dynamicRoutingDataSource(DruidDataSource dataSource1, DruidDataSource dataSource2) {
        DynamicRoutingDataSource dynamicDataSource = (DynamicRoutingDataSource) dataSource;
        dynamicDataSource.addDataSource("dataSource1", dataSource1);
        dynamicDataSource.addDataSource("dataSource2", dataSource2);
        return dynamicDataSource;
    }





    /****
     * @Content:根据数据源管理器DynamicRoutingDataSource 创建SqlSessionFactory
     * @Author 👻👻👻👻👻👻👻👻 gjh
     * @Date  2023-06-14 9:16
     * @Param [dynamicRoutingDataSource]
     * @return org.apache.ibatis.session.SqlSessionFactory
     **/
//    @Bean
    public static SqlSessionFactory mySqlSessionFactory(DataSource dataSource) throws RuntimeException {
        try {
            if (null != dataSource) {
//                StandardBeanExpressionResolver
//                DsSpelExpressionProcessor;
                SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
                //数据源
                sqlSessionFactoryBean.setDataSource(dataSource);
                //mybatis的config文件
                PathMatchingResourcePatternResolver configLocationResolver = new PathMatchingResourcePatternResolver();
                sqlSessionFactoryBean.setConfigLocation(configLocationResolver.getResource("classpath:mybatis/mybatis-config.xml"));
                //xml
                PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
                sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath*:com/hzya/**/*.xml"));

                return sqlSessionFactoryBean.getObject();
            } else {
                logger.info("======================创建sqlSessionFactory失败===========================");
                throw new RuntimeException("创建sqlSessionFactory失败");
            }
        } catch (Exception e) {
            logger.info("======================创建sqlSessionFactory失败===========================");
            throw new RuntimeException("创建sqlSessionFactory失败"+e.getMessage());
        }
    }



//    @Bean
    public DataSourceTransactionManager transactionManager(DynamicRoutingDataSource dynamicRoutingDataSource) {
        return new DataSourceTransactionManager(dynamicRoutingDataSource);
    }


    /****
     * @Content:创建数据源，返回DruidDataSource
     * @Author 👻👻👻👻👻👻👻👻 gjh
     * @Date  2023-06-14 9:11
     * @Param [defaultDataSourceProperties]
     * @return com.alibaba.druid.pool.DruidDataSource
     **/
    private static DruidDataSource createDefaultDataSource(JSONObject defaultDataSourceProperties) throws RuntimeException {
        //根据datasource_code查询数据源配置信息
        String datasource_code = String.valueOf(defaultDataSourceProperties.get("datasource_code"));
        String source_url = String.valueOf(defaultDataSourceProperties.get("source_url"));
        String login_name = String.valueOf(defaultDataSourceProperties.get("login_name"));
        String password = String.valueOf(defaultDataSourceProperties.get("password"));
        String db_name = String.valueOf(defaultDataSourceProperties.get("db_name"));
        String source_type = String.valueOf(defaultDataSourceProperties.get("source_type"));
        if (defaultDataSourceProperties != null) {
            String driveClass = "";
            if ("mysql".equalsIgnoreCase(source_type)) {
                driveClass = DataSourceUtilProperties.MYSQLDRIVER_6;
            } else if ("oracle".equalsIgnoreCase(source_type)) {
                driveClass = DataSourceUtilProperties.ORACLEDRIVER;
            } else if ("sqlserver2000".equalsIgnoreCase(source_type)) {
                driveClass = DataSourceUtilProperties.SQL2000DRIVER;
            } else if ("sqlServer".equalsIgnoreCase(source_type)) {
                driveClass = DataSourceUtilProperties.SQL2005DRIVER;
            }
            try {
                //测试连接
                Class.forName(driveClass);
                Connection connection = DriverManager.getConnection(source_url, login_name, password);// 相当于连接数据库
                if (connection != null) {
                    //初始化数据源信息
                    DruidDataSource druidDataSource = new DruidDataSource();
                    druidDataSource.setUrl(source_url);
                    druidDataSource.setUsername(login_name);
                    druidDataSource.setPassword(password);
                    druidDataSource.setName(db_name);
                    druidDataSource.setDriverClassName(driveClass);
                    druidDataSource.setInitialSize(5);
                    druidDataSource.setMinIdle(5);
                    druidDataSource.setMaxActive(100);
                    druidDataSource.setMaxWait(60000);
                    druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
                    druidDataSource.setMinEvictableIdleTimeMillis(300000);
                    druidDataSource.setMaxEvictableIdleTimeMillis(600000);
                    if ("oracle".equals(source_type)) {
                        druidDataSource.setValidationQuery("select 1 from dual");
                    } else {
                        druidDataSource.setValidationQuery("SELECT 1");
                    }
                    druidDataSource.setTestWhileIdle(true);
                    druidDataSource.setTestOnBorrow(false);
                    druidDataSource.setTestOnReturn(false);
                    druidDataSource.setPoolPreparedStatements(true);
                    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
                    druidDataSource.setRemoveAbandoned(true);
                    druidDataSource.setRemoveAbandonedTimeout(999999);
                    druidDataSource.init();
                    //放到缓存里
                    DATASOURCEMAP.put(datasource_code, druidDataSource);
                    return druidDataSource;
                } else {
                    throw new RuntimeException("测试默认数据库连接失败");
                }
            }
            catch (Exception e) {
                logger.info("==================创建数据源失败===================");
                throw new RuntimeException("创建数据源失败"+e.getMessage());
            }


        } else {
            throw new RuntimeException("source_code:" + datasource_code + "不存在");
        }
    }



    /****
     * @Content:创建第二数据源配置
     * @Author 👻👻👻👻👻👻👻👻 gjh
     * @Date  2023-06-14 9:09
     * @Param []
     * @return com.alibaba.fastjson.JSONObject
     **/
    private static JSONObject getDataSourceJsonObject() {
        JSONObject defaultDataSourceProperties = new JSONObject();
        defaultDataSourceProperties.put("datasource_code", "ya237");
        defaultDataSourceProperties.put("source_url", "jdbc:mysql://hzya.ufyct.com:9022/hut_exchange?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useSSL=false");
        defaultDataSourceProperties.put("source_type", "mysql");
        defaultDataSourceProperties.put("login_name", "root");
        defaultDataSourceProperties.put("password", "hzya1314");
        defaultDataSourceProperties.put("db_name", "hut_exchange");
        return defaultDataSourceProperties;
    }

}

