package com.op.mes.config;

import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.op.common.core.domain.R;
import com.op.common.datasource.creator.DynamicDatasourceCreator;
import com.op.system.api.RemoteUserService;
import com.op.system.api.domain.SysUser;


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 RemoteUserService remoteUserService;

	@PostConstruct
	public void init() {
		// 加载sf-cloud库的sys_datasource
		SysUser sysUser = new SysUser();
		sysUser.setUserId(1L);
		R<List<Map<String, String>>> dateSources0 = remoteUserService.getPoolNameList(sysUser);
		List<Map<String, String>> dateSources = dateSources0.getData();
		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);
		}

	}
}
