package com.zkqy.datamodeling.service.impl;

import com.ruoyi.common.config.datamodeling.DynamicDataSource;
import com.ruoyi.common.core.domain.entity.DataSource;
import com.ruoyi.common.utils.datamodeling.DataSourceUtils;
import com.zkqy.datamodeling.mapper.DataSourceMapper;
import com.zkqy.datamodeling.service.IDataSourceService;
import org.springframework.stereotype.Service;

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

@Service
public class DataSourceServiceImpl implements IDataSourceService {

    @Resource
    private DynamicDataSource dynamicDataSource;

    @Resource
    private DataSourceMapper dataSourceMapper;

    @Override
    public void changeDataSource(DataSource dataSource) throws Exception {
        //切换数据源之前先清空
        DynamicDataSource.clearDataSource();
        //切换数据源
        dynamicDataSource.changeDataSource(DataSourceUtils.changeDataSource(dataSource), false);
        // redisTemplate.opsForValue().set("DataSource", JSON.toJSONString(dataSource));
        System.err.println("当前数据源:" + dataSource.toString());
    }

    @Override
    public List<String> querySelectDatasource(DataSource dataSource) throws Exception {
        List<String> retList = new ArrayList<>();
        // 在执行前需要创建数据源
        dynamicDataSource.changeDataSource(DataSourceUtils.changeDataSource(dataSource), true);
        // 得到当前数据源中的所有库信息
        switch (dataSource.getDatabaseType()) {
            case "mysql":
                retList = dataSourceMapper.querySelectDatasource("SHOW DATABASES;");
                break;
            case "sqlserver":
                retList = dataSourceMapper.querySelectDatasource("select name from sys.databases;");
                break;
            case "dm":
                retList = dataSourceMapper.querySelectDatasource("select   a.name schename from SYS.SYSOBJECTS a, SYS.SYSOBJECTS b where a.\"TYPE$\"='SCH' and a.pid=b.id;");
                break;
            case "oracle":
                retList = dataSourceMapper.querySelectDatasource("SELECT DISTINCT object_name FROM ALL_OBJECTS WHERE OBJECT_TYPE = 'SCH';");
                break;
        }
        return retList;
    }

}
