package com.ff.config;

import com.ff.base.datasource.DynamicDataSource;
import com.ff.base.system.domain.SysDatasource;
import com.ff.base.system.mapper.SysDatasourceMapper;
import com.ff.base.system.service.ISysConfigService;
import com.ff.base.system.service.ISysDictTypeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

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

/**
 * 启动项目时加载多数据源
 *
 * @author liukang
 */
@Slf4j
@Component
public class ContentRefreshedEventListener implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    private DynamicDataSource dynamicDataSource;

    @Resource
    private SysDatasourceMapper dataSourceMapper;

    @Resource
    private ISysConfigService sysConfigService;

    @Resource
    private ISysDictTypeService sysDictTypeService;
    /**
     * 项目加载时运行
     *
     * @param event
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 创建所有数据源
        SysDatasource sysDatasource = new SysDatasource();
        sysDatasource.setStatus("1");
        List<SysDatasource> dataourceList = dataSourceMapper.selectSysDatasourceList(sysDatasource);
        if (!CollectionUtils.isEmpty(dataourceList)) {
            dynamicDataSource.createDataSource(dataourceList);
        }
        sysConfigService.loadingConfigCache();
        sysDictTypeService.loadingDictCache();
    }
}
