// 设置页面 JavaScript

// 加载数据库信息
async function loadDatabaseInfo() {
    try {
        const data = await apiRequest('/admin/api/database');
        const configData = await apiRequest('/admin/api/database/config');
        
        document.getElementById('db-type').textContent = data.database.type;
        document.getElementById('db-status').textContent = data.database.status;
        document.getElementById('db-status').className = 'info-value status-badge status-connected';
        
        if (data.database.file) {
            document.getElementById('db-file-item').style.display = 'flex';
            document.getElementById('db-file').textContent = data.database.file;
        }
        
        // 如果是 MySQL，显示密码修改界面
        if (configData.config.type === 'mysql') {
            document.getElementById('database-password-section').style.display = 'block';
        }
        
        // 操作系统信息
        document.getElementById('os-type').textContent = data.os.os;
        document.getElementById('os-arch').textContent = data.os.arch;
    } catch (error) {
        console.error('Load database info error:', error);
    }
}

// 加载系统信息
async function loadSystemInfo() {
    try {
        const data = await apiRequest('/admin/api/system');
        document.getElementById('stat-users').textContent = data.users;
        document.getElementById('stat-routes').textContent = data.routes;
        document.getElementById('stat-logs').textContent = data.logs;
        document.getElementById('stat-time').textContent = data.server_time;
    } catch (error) {
        console.error('Load system info error:', error);
    }
}

// 更新数据库密码
const passwordForm = document.getElementById('password-form');
if (passwordForm) {
    passwordForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const currentPassword = document.getElementById('current-password').value;
        const newPassword = document.getElementById('new-password').value;
        const confirmPassword = document.getElementById('confirm-password').value;
        
        if (newPassword !== confirmPassword) {
            alert('新密码和确认密码不一致！');
            return;
        }
        
        if (!confirm('确定要更新数据库 root 密码吗？\n\n更新后需要修改环境变量 DB_PASSWORD 并重启服务器！')) {
            return;
        }
        
        const resultEl = document.getElementById('password-result');
        resultEl.className = '';
        resultEl.textContent = '正在更新密码...';
        resultEl.style.display = 'block';
        
        try {
            const result = await apiRequest('/admin/api/database/password', {
                method: 'POST',
                body: JSON.stringify({
                    current_password: currentPassword,
                    new_password: newPassword,
                    confirm_password: confirmPassword,
                }),
            });
            
            resultEl.className = 'success';
            resultEl.textContent = result.message || '密码更新成功！';
            passwordForm.reset();
        } catch (error) {
            resultEl.className = 'error';
            resultEl.textContent = '更新失败: ' + error.message;
        }
    });
}

// 转换数据库
const convertDbBtn = document.getElementById('convert-db-btn');
if (convertDbBtn) {
    convertDbBtn.addEventListener('click', async () => {
        const targetType = document.getElementById('target-db-type').value;
        
        if (!confirm(`确定要转换数据库类型吗？\n\n目标类型: ${targetType.toUpperCase()}\n\n此操作会导出当前数据并导入到新数据库。请确保已备份数据！`)) {
            return;
        }
        
        const resultEl = document.getElementById('convert-result');
        resultEl.className = '';
        resultEl.textContent = '正在转换...';
        resultEl.style.display = 'block';
        
        try {
            const result = await apiRequest('/admin/api/database/convert', {
                method: 'POST',
                body: JSON.stringify({
                    target_type: targetType,
                }),
            });
            
            resultEl.className = 'success';
            resultEl.textContent = result.message || '数据库转换成功！';
            loadDatabaseInfo();
        } catch (error) {
            resultEl.className = 'error';
            resultEl.textContent = '转换失败: ' + error.message;
        }
    });
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
    loadDatabaseInfo();
    loadSystemInfo();
    
    // 定期更新系统信息
    setInterval(loadSystemInfo, 30000); // 每30秒更新一次
});
