<!-- BS5日志模态框组件 -->
<div class="modal fade" id="logModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="logModalTitle">日志详情 - <span id="modalTaskId"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="autoRefreshToggle">
                        <label class="form-check-label" for="autoRefreshToggle">自动刷新</label>
                    </div>
                    <button class="btn btn-sm btn-outline-secondary" id="refreshLogBtn">
                        <i class="bi bi-arrow-clockwise"></i> 手动刷新
                    </button>
                </div>
                
                <!-- 日志显示区域 -->
                <div class="log-container border rounded p-3 bg-light" style="max-height: 400px; overflow-y: auto;">
                    <pre id="logContent" class="mb-0" style="white-space: pre-wrap; word-wrap: break-word; width: 100%; max-width: 100%;">加载中...</pre>
                </div>
                
                <!-- 进度条区域（动态显示） -->
                <div id="progressSection" class="mt-3 d-none">
                    <div class="d-flex justify-content-between">
                        <span id="progressText">处理中...</span>
                        <span id="progressPercent">0%</span>
                    </div>
                    <div class="progress">
                        <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%;"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
// 日志服务JS类
var checkbox = document.getElementById('autoRefreshToggle');
class LogService {
    constructor(taskId, options = {}) {
        this.taskId = taskId;
        this.options = {
            refreshInterval: 2000,// 轮询间隔
            showProgress: false,
            autoRefresh: true,
            ...options
        };
        this.autoRefreshInterval = null;
        this.modalElement = document.getElementById('logModal');
        this.init();
    }
    
    init() {
        // 设置模态框标题
        document.getElementById('modalTaskId').textContent = this.taskId;
        
        // 初始化事件监听
        this.modalElement.addEventListener('show.bs.modal', () => {
            if (this.options.autoRefresh) {
                this.startAutoRefresh();
                
                // 根据 options.autoRefresh 的值设置复选框的 checked 属性
                checkbox.checked = this.options.autoRefresh;

            }
            this.loadLogs();
        });
        
        this.modalElement.addEventListener('hide.bs.modal', () => {
            this.stopAutoRefresh();
        });
        
        // 手动刷新按钮
        document.getElementById('refreshLogBtn').addEventListener('click', () => {
            this.loadLogs();
        });
        
        // 自动刷新切换
        document.getElementById('autoRefreshToggle').addEventListener('change', (e) => {
            if (e.target.checked) {
                this.startAutoRefresh();
            } else {
                this.stopAutoRefresh();
            }
        });
        
        // 根据选项显示/隐藏进度区域
        if (this.options.showProgress) {
            document.getElementById('progressSection').classList.remove('d-none');
        }
    }
    
    async loadLogs() {
        try {
            const response = await fetch(`/api/log_service/read/?task_id=${this.taskId}`);
            const data = await response.json();
            
            if (data.status === 'success') {
                document.getElementById('logContent').innerHTML = '<div class="list-group" id="logContent-list"></div>';
                // 转义HTML字符防止XSS
                const escapedLogs = data.logs.map(line => 
                    '<div class="list-group-item list-group-item-action">'+line.replace(/&/g, '&amp;')
                       .replace(/</g, '&lt;')
                       .replace(/>/g, '&gt;')
                       .replace(/"/g, '&quot;')
                       .replace(/'/g, '&#039;')+'</div>'
                );
                
                document.getElementById('logContent-list').innerHTML =escapedLogs.join('').replace(/\n/g, '');
                
                // 自动滚动到底部
                const logContainer = document.querySelector('.log-container');
                logContainer.scrollTop = logContainer.scrollHeight;
                
                // 如果有进度信息，更新进度条
                if (this.options.showProgress) {
                    this.updateProgress(data.logs);
                }
            } else {
                console.error('加载日志失败:', data.message);
            }
        } catch (error) {
            console.error('日志加载错误:', error);
            document.getElementById('logContent').innerHTML = '加载失败，请检查网络连接';
        }
    }
    
    updateProgress(logs) {
        const progressSection = document.getElementById('progressSection');
        let progressFound = false;
        
        // 从日志中提取进度信息
        for (let i = logs.length - 1; i >= 0; i--) {
            const match = logs[i].match(/(\d+(?:\.\d+)?%)/);
            if (match) {
                const percent = parseInt(match[1]);
                document.getElementById('progressPercent').textContent = `${percent}%`;
                document.getElementById('progressBar').style.width = `${percent}%`;
                
                document.getElementById('progressText').textContent = 
                    percent === 100 ? '处理完成' : '处理中...';
                
                progressFound = true;
                break;
            }
        }
        
        // 如果没有找到进度信息，隐藏进度区域
        if (!progressFound && !this.options.showProgress) {
            progressSection.classList.add('d-none');
        }
    }
    
    startAutoRefresh() {
        this.stopAutoRefresh();
        this.autoRefreshInterval = setInterval(() => {
            this.loadLogs();
        }, this.options.refreshInterval);
    }
    
    stopAutoRefresh() {
        if (this.autoRefreshInterval) {
            clearInterval(this.autoRefreshInterval);
            this.autoRefreshInterval = null;
        }
    }
    
    show() {
        const modal = new bootstrap.Modal(this.modalElement);
        modal.show();
        document.getElementById('logContent').innerHTML = '加载中...';
    }
}

// 全局函数，用于在HTML中直接调用
window.showLogModal = function(taskId, options = {}) {
    const logService = new LogService(taskId, options);
    logService.show();
};
</script>