package com.tykj.workflowcore.ds.service;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.BasicDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.tykj.workflowcore.ds.entity.DataSourceInfo;
import com.tykj.workflowcore.ds.repository.DataSourceInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class DataSourceManager {

    @Autowired
    private DataSourceInfoRepository dataSourceInfoRepository;
    @Autowired
    private DataSource dataSource;

    private BasicDataSourceCreator dataSourceCreator = new BasicDataSourceCreator();


    private void save(DataSourceInfo dataSourceInfo) {
        dataSourceInfoRepository.save(dataSourceInfo);
    }

    private void deleteById(Integer id) {

    }

    private List<DataSourceInfo> findAll() {
        return dataSourceInfoRepository.findAll();
    }

    private DataSourceInfo findById(Integer id) {
        return dataSourceInfoRepository.findById(id).orElseThrow(() -> new RuntimeException("未找到该id的数据"));
    }

    public void init() {
        List<DataSourceInfo> dataSourceInfos = dataSourceInfoRepository.findAll();
        dataSourceInfos.forEach(this::initDataSource);
    }

    public void initDataSource(DataSourceInfo dataSourceInfo) {
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        dataSourceProperty.setUrl(dataSourceInfo.getUrl());
        dataSourceProperty.setUsername(dataSourceInfo.getUsername());
        dataSourceProperty.setPassword(dataSourceInfo.getPassword());
        dataSourceProperty.setDriverClassName(dataSourceInfo.getDriverClassName());
        DataSource basicDataSource = dataSourceCreator.createDataSource(dataSourceProperty);
        ((DynamicRoutingDataSource) dataSource).addDataSource(dataSourceInfo.getName(), basicDataSource);
    }


    public void switchToDataSource(String dataSourceName) {
        DynamicDataSourceContextHolder.push(dataSourceName);
    }

    public void clear() {
        DynamicDataSourceContextHolder.clear();
    }

}
