package com.artfess.base.dataway;

import com.alibaba.druid.pool.DruidDataSource;

import com.artfess.base.exception.ApplicationException;
import com.artfess.base.util.DataSourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * @author 陈实
 * @date 2020/12/9 18:04
 * @Description: Dataway动态数据源获取
 */
@Component()
@Slf4j
public class DatawayDataSourceConfig {
    private static Map<String, DataSource> dataSourceMap=new HashMap<>();

    public DataSource getDataSource(String alias) {
        DataSource dataSource = null;
        try {
            if (StringUtils.isEmpty(alias)) {
                throw new ApplicationException("数据源别名不能空");
            }
            if (dataSourceMap.containsKey(alias)) {
                dataSource=dataSourceMap.get(alias);
            } else {
                dataSource = DataSourceUtil.getDataSourceByAlias(alias);
                dataSourceMap.put(alias, dataSource);
            }
            if(dataSource == null){
                throw new ApplicationException("【"+alias+"】数据源不存在！");
            }
        }catch (Exception e){
            throw new ApplicationException("创建连接失败");
        }
        return  dataSource;
    }

}
