<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>AJAX演示 - Struts2异步交互</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f7fa; padding: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        
        .header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 15px; margin-bottom: 30px; text-align: center; }
        .header h1 { font-size: 2em; margin-bottom: 10px; }
        
        .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 20px; margin-bottom: 30px; }
        
        .card { background: white; border-radius: 12px; padding: 25px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); }
        .card h3 { color: #333; margin-bottom: 15px; border-bottom: 2px solid #eee; padding-bottom: 10px; }
        
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; color: #555; font-weight: 500; }
        .form-group input { width: 100%; padding: 10px 12px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; transition: border-color 0.3s; }
        .form-group input:focus { outline: none; border-color: #667eea; }
        
        .btn { padding: 10px 20px; border: none; border-radius: 6px; cursor: pointer; font-size: 14px; transition: all 0.3s; }
        .btn-primary { background: #667eea; color: white; }
        .btn-primary:hover { background: #5a6fd6; }
        .btn-success { background: #27ae60; color: white; }
        .btn-success:hover { background: #219a52; }
        .btn-info { background: #3498db; color: white; }
        .btn-info:hover { background: #2980b9; }
        
        .result { background: #1e1e1e; color: #d4d4d4; padding: 15px; border-radius: 8px; margin-top: 15px; font-family: 'Monaco', 'Menlo', monospace; font-size: 13px; overflow-x: auto; max-height: 300px; overflow-y: auto; display: none; }
        .result.show { display: block; }
        .result.success { border-left: 4px solid #27ae60; }
        .result.error { border-left: 4px solid #e74c3c; }
        
        .status { padding: 10px 15px; border-radius: 6px; margin-top: 10px; font-size: 14px; display: none; }
        .status.show { display: block; }
        .status.success { background: #d4edda; color: #155724; }
        .status.error { background: #f8d7da; color: #721c24; }
        .status.loading { background: #d1ecf1; color: #0c5460; }
        
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 10px; margin-top: 15px; }
        .stat-item { background: #f8f9fa; padding: 15px; border-radius: 8px; text-align: center; }
        .stat-item .value { font-size: 24px; font-weight: bold; color: #667eea; }
        .stat-item .label { font-size: 12px; color: #666; margin-top: 5px; }
        
        .realtime-data { background: #f8f9fa; padding: 15px; border-radius: 8px; margin-top: 15px; }
        .realtime-data .item { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #e0e0e0; }
        .realtime-data .item:last-child { border-bottom: none; }
        .realtime-data .label { color: #666; }
        .realtime-data .value { font-weight: 500; color: #333; }
        
        .lab { background: #fff7e6; border-left: 4px solid #fa8c16; padding: 15px; border-radius: 8px; margin-bottom: 20px; }
        .lab strong { color: #874d00; }
        
        code { background: #f0f0f0; padding: 2px 6px; border-radius: 4px; font-size: 13px; }
        
        .nav { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }
        .nav a { padding: 10px 20px; background: white; border-radius: 20px; text-decoration: none; color: #333; font-size: 0.9em; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .nav a:hover { background: #667eea; color: white; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 AJAX演示 - Struts2异步交互</h1>
            <p>学习Struts2如何处理AJAX请求并返回JSON数据</p>
        </div>
        
        <div class="nav">
            <a href="index.jsp">← 返回首页</a>
            <a href="learn">学习中心</a>
            <a href="user">用户管理</a>
        </div>
        
        <div class="lab">
            <strong>🧪 实验任务</strong>
            <ul>
                <li>在"用户名检查"中输入"admin"或"root"，观察AJAX实时验证</li>
                <li>点击"获取统计数据"，查看后端返回的JSON数据</li>
                <li>使用"AJAX表单提交"，体验无刷新表单提交</li>
                <li>观察"实时数据"面板，了解如何定时获取服务器数据</li>
            </ul>
        </div>
        
        <div class="grid">
            <!-- 用户名实时检查 -->
            <div class="card">
                <h3>👤 用户名实时检查</h3>
                <div class="form-group">
                    <label>输入用户名（试试 admin 或 root）:</label>
                    <input type="text" id="checkUsername" placeholder="输入用户名" onblur="checkUsername()">
                </div>
                <div id="usernameStatus" class="status"></div>
                <div id="usernameResult" class="result"></div>
            </div>
            
            <!-- 获取统计数据 -->
            <div class="card">
                <h3>📊 获取统计数据</h3>
                <button class="btn btn-info" onclick="getStats()">获取统计数据</button>
                <div id="statsContainer" style="margin-top: 15px;"></div>
                <div id="statsResult" class="result"></div>
            </div>
            
            <!-- AJAX表单提交 -->
            <div class="card">
                <h3>📝 AJAX表单提交</h3>
                <div class="form-group">
                    <label>用户名:</label>
                    <input type="text" id="ajaxUsername" placeholder="请输入用户名">
                </div>
                <div class="form-group">
                    <label>邮箱:</label>
                    <input type="email" id="ajaxEmail" placeholder="请输入邮箱">
                </div>
                <div class="form-group">
                    <label>年龄:</label>
                    <input type="number" id="ajaxAge" placeholder="请输入年龄">
                </div>
                <button class="btn btn-success" onclick="submitAjaxForm()">AJAX提交</button>
                <div id="ajaxFormStatus" class="status"></div>
                <div id="ajaxFormResult" class="result"></div>
            </div>
            
            <!-- 实时数据 -->
            <div class="card">
                <h3>⏱️ 实时数据监控</h3>
                <button class="btn btn-primary" onclick="startRealtime()">开始监控</button>
                <button class="btn" onclick="stopRealtime()" style="margin-left: 10px; background: #95a5a6; color: white;">停止监控</button>
                <div id="realtimeContainer" class="realtime-data" style="display: none;">
                    <div class="item">
                        <span class="label">服务器时间:</span>
                        <span class="value" id="serverTime">--</span>
                    </div>
                    <div class="item">
                        <span class="label">每秒请求数:</span>
                        <span class="value" id="requestsPerSecond">--</span>
                    </div>
                    <div class="item">
                        <span class="label">内存使用:</span>
                        <span class="value" id="memoryUsage">--</span>
                    </div>
                    <div class="item">
                        <span class="label">活跃会话:</span>
                        <span class="value" id="activeSessions">--</span>
                    </div>
                </div>
                <div id="realtimeResult" class="result"></div>
            </div>
        </div>
        
        <div class="card">
            <h3>📚 学习要点</h3>
            <ul>
                <li><strong>返回JSON:</strong> Action中通过 <code>ServletActionContext.getResponse().getWriter()</code> 直接输出JSON</li>
                <li><strong>不返回result:</strong> AJAX Action返回 <code>NONE</code>，不经过视图层</li>
                <li><strong>异步验证:</strong> 使用 <code>onblur</code> 事件触发AJAX验证，提升用户体验</li>
                <li><strong>定时刷新:</strong> 使用 <code>setInterval</code> 实现实时数据监控</li>
                <li><strong>Fetch API:</strong> 现代浏览器推荐使用 <code>fetch</code> 替代 <code>XMLHttpRequest</code></li>
            </ul>
        </div>
    </div>
    
    <script>
        let realtimeInterval = null;
        
        // 显示状态
        function showStatus(elementId, message, type) {
            const statusEl = document.getElementById(elementId);
            statusEl.textContent = message;
            statusEl.className = 'status show ' + type;
        }
        
        // 显示结果
        function showResult(elementId, data, isSuccess) {
            const resultEl = document.getElementById(elementId);
            resultEl.textContent = JSON.stringify(data, null, 2);
            resultEl.className = 'result show ' + (isSuccess ? 'success' : 'error');
        }
        
        // 检查用户名
        async function checkUsername() {
            const username = document.getElementById('checkUsername').value.trim();
            if (!username) return;
            
            showStatus('usernameStatus', '检查中...', 'loading');
            
            try {
                const response = await fetch('ajax_checkUsername?username=' + encodeURIComponent(username));
                const data = await response.json();
                
                showResult('usernameResult', data, data.available);
                
                if (data.available) {
                    showStatus('usernameStatus', '✓ ' + data.message, 'success');
                } else {
                    showStatus('usernameStatus', '✗ ' + data.message, 'error');
                }
            } catch (error) {
                showStatus('usernameStatus', '请求失败: ' + error.message, 'error');
            }
        }
        
        // 获取统计数据
        async function getStats() {
            showStatus('statsContainer', '加载中...', 'loading');
            
            try {
                const response = await fetch('ajax_getStats');
                const data = await response.json();
                
                // 显示统计卡片
                const statsHtml = `
                    <div class="stats-grid">
                        <div class="stat-item">
                            <div class="value">${data.totalUsers}</div>
                            <div class="label">总用户数</div>
                        </div>
                        <div class="stat-item">
                            <div class="value">${data.activeUsers}</div>
                            <div class="label">活跃用户</div>
                        </div>
                        <div class="stat-item">
                            <div class="value">${data.newUsersToday}</div>
                            <div class="label">今日新增</div>
                        </div>
                    </div>
                `;
                document.getElementById('statsContainer').innerHTML = statsHtml;
                
                showResult('statsResult', data, true);
            } catch (error) {
                showStatus('statsContainer', '请求失败: ' + error.message, 'error');
            }
        }
        
        // AJAX表单提交
        async function submitAjaxForm() {
            const username = document.getElementById('ajaxUsername').value.trim();
            const email = document.getElementById('ajaxEmail').value.trim();
            const age = document.getElementById('ajaxAge').value;
            
            if (!username || !email) {
                showStatus('ajaxFormStatus', '请填写完整信息', 'error');
                return;
            }
            
            showStatus('ajaxFormStatus', '提交中...', 'loading');
            
            try {
                const params = new URLSearchParams();
                params.append('username', username);
                params.append('email', email);
                if (age) params.append('age', age);
                
                const response = await fetch('ajax_saveUser', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: params.toString()
                });
                
                const data = await response.json();
                showResult('ajaxFormResult', data, data.success);
                
                if (data.success) {
                    showStatus('ajaxFormStatus', '✓ ' + data.message, 'success');
                    // 清空表单
                    document.getElementById('ajaxUsername').value = '';
                    document.getElementById('ajaxEmail').value = '';
                    document.getElementById('ajaxAge').value = '';
                } else {
                    showStatus('ajaxFormStatus', '✗ ' + (data.error || '保存失败'), 'error');
                }
            } catch (error) {
                showStatus('ajaxFormStatus', '请求失败: ' + error.message, 'error');
            }
        }
        
        // 开始实时监控
        async function startRealtime() {
            if (realtimeInterval) return;
            
            document.getElementById('realtimeContainer').style.display = 'block';
            
            async function fetchRealtime() {
                try {
                    const response = await fetch('ajax_getRealtimeData');
                    const data = await response.json();
                    
                    document.getElementById('serverTime').textContent = data.serverTime;
                    document.getElementById('requestsPerSecond').textContent = data.requestsPerSecond.toFixed(2);
                    document.getElementById('memoryUsage').textContent = data.memoryUsage.toFixed(2) + ' MB';
                    document.getElementById('activeSessions').textContent = data.activeSessions;
                    
                    showResult('realtimeResult', data, true);
                } catch (error) {
                    console.error('获取实时数据失败:', error);
                }
            }
            
            fetchRealtime(); // 立即执行一次
            realtimeInterval = setInterval(fetchRealtime, 3000); // 每3秒刷新
        }
        
        // 停止实时监控
        function stopRealtime() {
            if (realtimeInterval) {
                clearInterval(realtimeInterval);
                realtimeInterval = null;
            }
            document.getElementById('realtimeContainer').style.display = 'none';
        }
    </script>
</body>
</html>
