package org.springblade.flow.visual.base.util;

import org.springblade.flow.base.UserInfo;
import org.springblade.flow.base.util.SourceUtil;
import org.springblade.flow.database.model.DataSourceUtil;
import org.springblade.flow.database.model.DbLinkEntity;
import org.springblade.flow.database.source.impl.DbOracle;
import org.springblade.flow.database.util.DbTypeUtil;
import org.springblade.flow.util.UserProvider;
import org.springblade.flow.util.context.SpringContext;
import org.springblade.flow.visual.onlinedev.common.dynamic.DataSourceService;

import com.baomidou.mybatisplus.generator.config.DataSourceConfig;

/**
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2021年3月17日14:06:29
 */

public class GetGenDataSourceUtil {
	private static DataSourceService dblinkService;
	private static UserProvider userProvider;
	private static DataSourceUtil dataSourceUtil;

	public static DataSourceConfig getGenDataSource(String dataSourceId) {

		// 数据源配置
		SourceUtil sourceUtil = new SourceUtil();

		dblinkService = SpringContext.getBean(DataSourceService.class);
		DataSourceConfig dsc;
		DbLinkEntity linkEntity = dblinkService.getInfo(dataSourceId);
		if (linkEntity != null) {
			return sourceUtil.dbConfig(linkEntity);
		}

		userProvider = SpringContext.getBean(UserProvider.class);
		dataSourceUtil = SpringContext.getBean(DataSourceUtil.class);
		UserInfo userInfo = userProvider.get();
		dsc = sourceUtil.dbConfig(userInfo.getTenantDbConnectionString());
		if (DbTypeUtil.checkDb(dataSourceUtil, DbOracle.DB_ENCODE)) {
			String schema = dataSourceUtil.getUserName();
			// oracle 默认 schema=username
			dsc.setSchemaName(schema.toUpperCase());
		}
		return dsc;
	}

}
