package com.roma.romaapi.facade;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class MultipleDb {
    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

//    @Value("${spring.datasource.demo.user.url}")
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.url}")
    private String datasourceUrl;
    @Value("${spring.datasource.username}")
    private String datasourceUsername;
    @Value("${spring.datasource.password}")
    private String datasourcePassword;

    // 传入db配置的code,返回对应数据库实例
    public NamedParameterJdbcTemplate getMultipleDatasourceByDbCode(String dbCode) {
        Map dbConfigParams = new HashMap<>();
        dbConfigParams.put("dbCode", dbCode);
        Map<String, Object> dbConfigInfoByDbCode = new HashMap<>();
        // 获取此sql要执行的数据库源
        try {
            String dbSourceInfoStringSql = " SELECT * FROM `datasource_config` WHERE `datasource_code`=:dbCode ";
            dbConfigInfoByDbCode = namedParameterJdbcTemplate.queryForMap(
                    dbSourceInfoStringSql, dbConfigParams);
        } catch (EmptyResultDataAccessException e) {
        }

        // 创建链接信息
        final HikariDataSource customDataConfig = new HikariDataSource();
        customDataConfig.setDriverClassName(driverClassName); // mysql驱动

        // 判断是否使用默认源 dbcode不存在或者没有找到数据库配置,则使用默认源
        if(dbCode == null || dbCode.equals("") || dbConfigInfoByDbCode.isEmpty()) {
            customDataConfig.setJdbcUrl(datasourceUrl);
            customDataConfig.setUsername(datasourceUsername);
            customDataConfig.setPassword(datasourcePassword);
        } else {
            customDataConfig.setJdbcUrl(dbConfigInfoByDbCode.get("datasource_url").toString());
            customDataConfig.setUsername(dbConfigInfoByDbCode.get("datasource_username").toString());
            customDataConfig.setPassword(dbConfigInfoByDbCode.get("datasource_password").toString());
//            customDataConfig.setJdbcUrl("jdbc:mysql://ibs-cn.elken.com:8016/roma?serverTimezone=UTC&tinyInt1isBit=false&transformedBitIsBoolean=false");
//            customDataConfig.setUsername("bi");
//            customDataConfig.setPassword("WxlmPxXuI9sQWvkE");
        }

        NamedParameterJdbcTemplate mulNamedParameterJdbcTemplate = new NamedParameterJdbcTemplate(customDataConfig);

        return mulNamedParameterJdbcTemplate;
    }
}
