package com.qiaoba.common.database.util;

import cn.hutool.core.io.IoUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.qiaoba.common.database.context.DynamicDataSourceContext;
import com.qiaoba.common.database.context.PrimaryDatasourceContext;
import com.qiaoba.common.database.context.TenantDbTypeContext;
import com.qiaoba.common.database.entity.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.sql.SQLException;

/**
 * DatasourceUtil
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/7/13 0013 下午 16:20
 */
@Component
@Slf4j
public class DatasourceUtil {

    @Resource
    private DynamicDataSourceContext dataSource;

    private static DynamicDataSourceContext dynamicDataSourceContext;

    @PostConstruct
    public void init() {
        dynamicDataSourceContext = dataSource;
    }

    public static void changePrimaryDatasource(String tenantId, Object datasource) {
        PrimaryDatasourceContext.set(tenantId, datasource);
        // 将数据源的类型保存
        DruidPooledConnection connection = null;
        try {
            connection = ((DruidDataSource) datasource).getConnection();
            TenantDbTypeContext.set(tenantId, connection.getMetaData().getDatabaseProductName());
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 归还 connection
            IoUtil.close(connection);
        }
        dynamicDataSourceContext.freshDataSource(PrimaryDatasourceContext.getAll());
    }

    public static Object buildDataSource(String tenantId, DynamicDataSource dynamicDataSource) {
        log.debug("正在创建数据源DataSource, 租户: {}", tenantId);
        boolean connect = JdbcUtil.checkConnect(dynamicDataSource.getDriver(), dynamicDataSource.getUrl(), dynamicDataSource.getUsername(), dynamicDataSource.getPassword());
        if (!connect) {
            log.error("租户: {} 数据源连接失败, Url: {}", tenantId, dynamicDataSource.getUrl());
            return null;
        }
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(dynamicDataSource.getUrl());
        dataSource.setUsername(dynamicDataSource.getUsername());
        dataSource.setPassword(dynamicDataSource.getPassword());
        dataSource.setDriverClassName(dynamicDataSource.getDriver());
        dataSource.setInitialSize(dynamicDataSource.getInitialSize());
        dataSource.setMinIdle(dynamicDataSource.getMinIdle());
        dataSource.setMaxActive(dynamicDataSource.getMaxActive());

        try {
            dataSource.addFilters("stat");
            // wall 防火墙 切勿开启, 开启后 导入SQL 会失败
            // dataSource.addFilters("wall")
            // 初始化数据源
            dataSource.init();
            return dataSource;
        } catch (Exception e) {
            IoUtil.close(dataSource);
            return null;
        }
    }
}
