package com.tashow.cloud.canal.service;


import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

@Service
public class SqlExecutorService {

    private static final Logger log = LoggerFactory.getLogger(SqlExecutorService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void executeBatch(List<SqlTask> tasks) {
        if (tasks == null || tasks.isEmpty()) return;

        DynamicDataSourceContextHolder.push("slave");
        try {
            // 提取所有 SQL 模板（假设它们都是一样的）
            String sqlTemplate = tasks.get(0).getSql();

            // 执行批量更新
            jdbcTemplate.batchUpdate(sqlTemplate, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    SqlTask task = tasks.get(i);
                    Object[] args = task.getArgs();
                    for (int j = 0; j < args.length; j++) {
                        ps.setObject(j + 1, args[j]);
                    }
                }

                @Override
                public int getBatchSize() {
                    return tasks.size();
                }
            });

            log.info("✅ 成功执行 {} 条 SQL", tasks.size());
        } catch (Exception e) {
            log.error("❌ 批量执行 SQL 失败", e);
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
    }
}