package com.cf.imes.module.manage.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import com.cf.imes.module.manage.dal.dataobject.register.RegisterDO;
import com.cf.imes.module.manage.dal.mysql.register.RegisterMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.List;

/**
 * @author there
 */
@Slf4j
@Component
public class DataSourceInitializer {

    @Autowired
    private DefaultDataSourceCreator defaultDataSourceCreator;

    @Autowired
    private RegisterMapper registerMapper;

    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void init(){
        DynamicRoutingDataSource dynamicRoutingDataSource=(DynamicRoutingDataSource)dataSource;
        OrganContextHolder.setOrganId(0L);
        List<RegisterDO> registerDOS=registerMapper.findAll();
        OrganContextHolder.clear();
        for(RegisterDO registerDO:registerDOS){
            DataSourceProperty dataSourceProperty=new DataSourceProperty();
            dataSourceProperty.setPoolName(registerDO.getCode());
            dataSourceProperty.setUrl(registerDO.getDbUrl());
            dataSourceProperty.setUsername(registerDO.getDbUsername());
            dataSourceProperty.setPassword(registerDO.getDbPassword());
            DataSource dataSource=defaultDataSourceCreator.createDataSource(dataSourceProperty);
            dynamicRoutingDataSource.addDataSource(registerDO.getCode(),dataSource);
        }

    }
}
