package com.ruoyi.framework.config;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

/**
 * 数据库初始化组件
 * 在应用启动时执行SQL脚本创建表
 */
@Component
public class DatabaseInitializer implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private ResourceLoader resourceLoader;

    @Override
    public void run(String... args) throws Exception {
        // 执行SQL脚本创建表
        executeSqlScript("classpath:sdgsat1_init.sql");
    }

    /**
     * 执行SQL脚本
     */
    private void executeSqlScript(String scriptPath) throws IOException, SQLException {
        Resource resource = resourceLoader.getResource(scriptPath);
        if (resource.exists()) {
            try (InputStream inputStream = resource.getInputStream()) {
                String sqlScript = new String(FileCopyUtils.copyToByteArray(inputStream));
                executeSqlStatements(sqlScript);
            }
        }
    }

    /**
     * 执行SQL语句
     */
    private void executeSqlStatements(String sqlScript) throws SQLException {
        try (Connection connection = dataSource.getConnection()) {
            String[] statements = sqlScript.split(";");
            for (String statement : statements) {
                statement = statement.trim();
                if (!statement.isEmpty()) {
                    try (PreparedStatement preparedStatement = connection.prepareStatement(statement)) {
                        preparedStatement.execute();
                    }
                }
            }
        }
    }
}