package com.fastbee.iot.ruleEngine;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.fastbee.iot.domain.MultipleDataSource;
import com.fastbee.ruleEngine.context.MsgContext;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.SQLException;
import java.sql.Statement;

@Slf4j
@LiteflowComponent("databaseBridge")
public class DatabaseBridge extends NodeComponent {
    @Autowired
    private DataSourceService dataSourceService;

    @Override
    public void process() throws Exception {
        MsgContext cxt = this.getContextBean(MsgContext.class);
        Long id = cxt.getData("databaseBridgeID");
        MultipleDataSource multipleDataSource = dataSourceService.getDataSource(id);
        DruidDataSource dataSource = dataSourceService.createDataSource(multipleDataSource);
        DruidPooledConnection connection = null;
        Statement statement = null;
        String sql = cxt.placeholders(multipleDataSource.getSql());
        log.info("执行sql：{}", sql);
        try {
            connection = dataSource.getConnection();
            statement = connection.createStatement();
            statement.execute(sql);
        } catch (SQLException e) {
            log.error("sql执行失败---------，原因：{ }", e);
        }
        try {
            connection.close();
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            log.error("关闭数据库连接失败，原因：{ }", e);
        }
    }

}
