/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.config
 * @ClassName: DatabaseMigration
 * @Description: 数据库迁移配置 - 启动时自动添加缺失的字段
 * @Author: 张志锋
 * @Date: 2025-12-02
 * @Version: 1.0
 */
package com.zhpb.gdyd_zhpb_zgf.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * 数据库迁移 - 自动添加缺失的字段
 */
@Component
public class DatabaseMigration implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(DatabaseMigration.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(ApplicationArguments args) {
        logger.info("开始执行数据库迁移检查...");
        
        try {
            // 添加目录摘取相关字段
            addCatalogExtractionFields();
            
            logger.info("数据库迁移检查完成");
        } catch (Exception e) {
            logger.error("数据库迁移失败", e);
            // 不抛出异常，避免影响应用启动
        }
    }

    /**
     * 添加目录摘取相关字段
     */
    private void addCatalogExtractionFields() {
        try {
            // 检查并添加 catalog_extraction_status 字段
            if (!columnExists("t_file", "catalog_extraction_status")) {
                logger.info("添加字段: t_file.catalog_extraction_status");
                jdbcTemplate.execute(
                    "ALTER TABLE t_file ADD COLUMN catalog_extraction_status VARCHAR(32) DEFAULT 'processing'"
                );
                logger.info("字段添加成功: catalog_extraction_status");
            } else {
                logger.info("字段已存在: catalog_extraction_status");
            }

            // 检查并添加 catalog_extraction_retry_count 字段
            if (!columnExists("t_file", "catalog_extraction_retry_count")) {
                logger.info("添加字段: t_file.catalog_extraction_retry_count");
                jdbcTemplate.execute(
                    "ALTER TABLE t_file ADD COLUMN catalog_extraction_retry_count INT DEFAULT 0 NOT NULL"
                );
                logger.info("字段添加成功: catalog_extraction_retry_count");
            } else {
                logger.info("字段已存在: catalog_extraction_retry_count");
            }

            // 检查并添加 catalog_extraction_time 字段
            if (!columnExists("t_file", "catalog_extraction_time")) {
                logger.info("添加字段: t_file.catalog_extraction_time");
                jdbcTemplate.execute(
                    "ALTER TABLE t_file ADD COLUMN catalog_extraction_time TIMESTAMP"
                );
                logger.info("字段添加成功: catalog_extraction_time");
            } else {
                logger.info("字段已存在: catalog_extraction_time");
            }

            // 添加字段注释
            try {
                jdbcTemplate.execute(
                    "COMMENT ON COLUMN t_file.catalog_extraction_status IS '目录摘取状态：not_started-未开始, processing-处理中, completed-已完成'"
                );
                jdbcTemplate.execute(
                    "COMMENT ON COLUMN t_file.catalog_extraction_retry_count IS '目录摘取重试次数（最多重试3次）'"
                );
                jdbcTemplate.execute(
                    "COMMENT ON COLUMN t_file.catalog_extraction_time IS '目录摘取完成时间'"
                );
                logger.info("字段注释添加成功");
            } catch (Exception e) {
                logger.warn("添加字段注释失败（可忽略）: {}", e.getMessage());
            }

            // 为已有数据设置初始状态
            try {
                int updatedRows = jdbcTemplate.update(
                    "UPDATE t_file f SET catalog_extraction_status = 'completed', " +
                    "catalog_extraction_time = f.update_time " +
                    "WHERE EXISTS (SELECT 1 FROM t_file_directory fd WHERE fd.file_id = f.file_id) " +
                    "AND (catalog_extraction_status IS NULL OR catalog_extraction_status = 'not_started')"
                );
                logger.info("更新已有数据状态，影响行数: {}", updatedRows);
            } catch (Exception e) {
                logger.warn("更新已有数据状态失败（可忽略）: {}", e.getMessage());
            }

            // 创建索引
            try {
                jdbcTemplate.execute(
                    "CREATE INDEX IF NOT EXISTS idx_file_catalog_status ON t_file(catalog_extraction_status)"
                );
                logger.info("索引创建成功: idx_file_catalog_status");
            } catch (Exception e) {
                logger.warn("创建索引失败（可忽略）: {}", e.getMessage());
            }

        } catch (Exception e) {
            logger.error("添加目录摘取字段失败", e);
            throw new RuntimeException("数据库迁移失败: " + e.getMessage(), e);
        }
    }

    /**
     * 检查字段是否存在
     */
    private boolean columnExists(String tableName, String columnName) {
        try {
            String sql = "SELECT COUNT(*) FROM information_schema.columns " +
                        "WHERE table_name = ? AND column_name = ?";
            Integer count = jdbcTemplate.queryForObject(sql, Integer.class, tableName, columnName);
            return count != null && count > 0;
        } catch (Exception e) {
            logger.warn("检查字段是否存在时出错: {}", e.getMessage());
            return false;
        }
    }
}
