package com.op.system.config;

import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.op.common.datasource.creator.DynamicDatasourceCreator;
import com.op.system.api.domain.SysUser;
import com.op.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 初始化动态数据源
 *
 * @ClassName: DynamicDatasource
 * @Description: TODO
 * @author shichangzhou
 * @date 2023年4月19日 下午1:01:30
 */
@Component
public class DynamicDatasource {

	@Resource
	private DynamicDatasourceCreator dynamicDatasourceCreator;
	@Autowired
	private ISysUserService sysUserService;

	@PostConstruct
	public void init() {
		SysUser sysUser = new SysUser();
		sysUser.setUserId(1L);
		List<Map<String, String>> dateSources = sysUserService.getPoolNameList(sysUser);
		for (Map<String, String> dateSource : dateSources) {
			DataSourceProperty sdp = new DataSourceProperty();
			sdp.setUrl(dateSource.get("url"));
			sdp.setUsername(dateSource.get("userName"));
			sdp.setPassword(dateSource.get("password"));
			sdp.setDriverClassName(dateSource.get("driveClassName"));
			sdp.setPoolName(dateSource.get("poolName"));// 这是数据源的key
			sdp.setLazy(false);
			dynamicDatasourceCreator.createDynamicDataSource(sdp);
		}
	}
}
