<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单管理 - OpenClaw</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #0f1419;
            color: #e6e6e6;
            line-height: 1.6;
        }
        .header {
            background: linear-gradient(135deg, #1a2332 0%, #0f1419 100%);
            padding: 20px 30px;
            border-bottom: 1px solid #2d3a4a;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 { font-size: 24px; font-weight: 600; color: #00d4aa; }
        .nav-links { display: flex; gap: 20px; align-items: center; }
        .nav-links a { color: #8b9aad; text-decoration: none; font-weight: 500; }
        .nav-links a:hover, .nav-links a.active { color: #00d4aa; }
        .container { padding: 20px 30px; max-width: 1400px; margin: 0 auto; }
        .card { background: #1a2332; border-radius: 12px; border: 1px solid #2d3a4a; overflow: hidden; margin-bottom: 20px; }
        .card-header { background: #222d3d; padding: 15px 20px; border-bottom: 1px solid #2d3a4a; display: flex; justify-content: space-between; align-items: center; }
        .card-title { font-size: 16px; font-weight: 600; color: #fff; }
        .card-body { padding: 20px; }
        .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; }
        .form-group { display: flex; flex-direction: column; }
        .form-group label { font-size: 13px; color: #8b9aad; margin-bottom: 5px; text-transform: uppercase; }
        .form-group input, .form-group select { background: #0f1419; border: 1px solid #2d3a4a; border-radius: 6px; padding: 10px 12px; color: #e6e6e6; font-size: 14px; }
        .btn { padding: 10px 20px; border: none; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; transition: all 0.2s; }
        .btn-primary { background: #00d4aa; color: #0f1419; }
        .btn-primary:hover { background: #00b894; }
        .btn-danger { background: #ff4444; color: #fff; }
        .btn-danger:hover { background: #cc3333; }
        .btn-secondary { background: #2d3a4a; color: #e6e6e6; }
        .btn-small { padding: 5px 12px; font-size: 12px; }
        .data-table { width: 100%; border-collapse: collapse; font-size: 13px; }
        .data-table th, .data-table td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #2d3a4a; }
        .data-table th { background: #222d3d; font-size: 11px; text-transform: uppercase; color: #8b9aad; font-weight: 600; }
        .badge { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 500; }
        .badge-pending { background: rgba(255, 193, 7, 0.15); color: #ffc107; }
        .badge-open { background: rgba(0, 212, 170, 0.15); color: #00d4aa; }
        .badge-filled { background: rgba(76, 175, 80, 0.15); color: #4caf50; }
        .badge-cancelled { background: rgba(255, 68, 68, 0.15); color: #ff4444; }
        .side-buy { color: #00d4aa; font-weight: 600; }
        .side-sell { color: #ff4444; font-weight: 600; }
        .two-column { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        @media (max-width: 1200px) { .two-column { grid-template-columns: 1fr; } }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; margin-bottom: 20px; }
        .stat-card { background: #1a2332; border-radius: 8px; padding: 15px; border: 1px solid #2d3a4a; }
        .stat-label { font-size: 11px; color: #8b9aad; text-transform: uppercase; }
        .stat-value { font-size: 20px; font-weight: 700; color: #fff; }
        .stat-value.positive { color: #00d4aa; }
        .stat-value.negative { color: #ff4444; }
        .filter-bar { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-bottom: 15px; }
        .notification { position: fixed; top: 80px; right: 20px; padding: 15px 20px; border-radius: 8px; color: #fff; font-weight: 500; z-index: 1000; animation: slideIn 0.3s ease-out; }
        .notification.success { background: #00d4aa; }
        .notification.error { background: #ff4444; }
        @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
    </style>
</head>
<body>
    <div class="header">
        <h1>🦀 OpenClaw 交易仪表盘</h1>
        <div class="nav-links" style="display: flex; gap: 20px; align-items: center;">
            <a href="/" style="color: #8b9aad; text-decoration: none; font-weight: 500;">仪表盘</a>
            <a href="/orders" style="color: #00d4aa; text-decoration: none; font-weight: 500;">订单</a>
            <a href="/config" style="color: #8b9aad; text-decoration: none; font-weight: 500;">配置</a>
            <a href="/exchanges" style="color: #8b9aad; text-decoration: none; font-weight: 500;">交易所</a>
        </div>
        <div class="connection-status">
            <span class="status-dot" id="statusDot"></span>
            <span id="statusText">连接中...</span>
        </div>
    </div>
    <div class="container">
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-label">总订单数</div>
                <div class="stat-value" id="totalOrders">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">待处理订单</div>
                <div class="stat-value" id="openOrders">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">持仓数量</div>
                <div class="stat-value" id="positionsCount">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">持仓市值</div>
                <div class="stat-value" id="positionsValue">\$0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">未实现盈亏</div>
                <div class="stat-value" id="unrealizedPnL">\$0</div>
            </div>
        </div>
        <div class="two-column">
            <div class="card">
                <div class="card-header">
                    <span class="card-title">创建订单</span>
                    <span class="badge badge-open">模拟交易</span>
                </div>
                <div class="card-body">
                    <form id="orderForm" class="form-grid">
                        <div class="form-group">
                            <label>交易对</label>
                            <select id="symbol" required>
                                <option value="BTC/USDT">BTC/USDT</option>
                                <option value="ETH/USDT">ETH/USDT</option>
                                <option value="AAPL">AAPL</option>
                                <option value="GOOGL">GOOGL</option>
                                <option value="MSFT">MSFT</option>
                                <option value="AMZN">AMZN</option>
                                <option value="TSLA">TSLA</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>方向</label>
                            <select id="side" required>
                                <option value="buy">买入</option>
                                <option value="sell">卖出</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>订单类型</label>
                            <select id="orderType" required>
                                <option value="market">市价单</option>
                                <option value="limit">限价单</option>
                                <option value="stop_loss">止损单</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>数量</label>
                            <input type="number" id="amount" step="0.0001" min="0.0001" placeholder="0.00" required>
                        </div>
                        <div class="form-group" id="priceGroup" style="display: none;">
                            <label>价格</label>
                            <input type="number" id="price" step="0.01" min="0" placeholder="0.00">
                        </div>
                    </form>
                    <div style="margin-top: 20px;">
                        <button type="button" class="btn btn-primary" onclick="createOrder()">创建订单</button>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-header">
                    <span class="card-title">当前持仓</span>
                    <button class="btn btn-secondary btn-small" onclick="refreshPositions()">刷新</button>
                </div>
                <div class="card-body" style="padding: 0;">
                    <table class="data-table">
                        <thead>
                            <tr><th>交易对</th><th>方向</th><th>数量</th><th>入场价</th><th>当前价</th><th>未实现盈亏</th></tr>
                        </thead>
                        <tbody id="positionsTableBody">
                            <tr><td colspan="6" style="text-align: center; color: #8b9aad;">暂无持仓</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="card">
            <div class="card-header">
                <span class="card-title">订单列表</span>
                <div class="filter-bar">
                    <select id="filterStatus" onchange="loadOrders()">
                        <option value="">所有状态</option>
                        <option value="pending">待处理</option>
                        <option value="open">挂单中</option>
                        <option value="filled">已成交</option>
                        <option value="cancelled">已取消</option>
                    </select>
                    <select id="filterSide" onchange="loadOrders()">
                        <option value="">所有方向</option>
                        <option value="buy">买入</option>
                        <option value="sell">卖出</option>
                    </select>
                    <button class="btn btn-secondary btn-small" onclick="loadOrders()">刷新</button>
                </div>
            </div>
            <div class="card-body" style="padding: 0;">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>订单ID</th><th>时间</th><th>交易对</th><th>方向</th><th>类型</th>
                            <th>数量</th><th>价格</th><th>成交数量</th><th>状态</th><th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="ordersTableBody">
                        <tr><td colspan="10" style="text-align: center; color: #8b9aad;">暂无订单</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <script>
        function formatCurrency(value) { return '\$' + Number(value).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); }
        function formatTime(timestamp) { return new Date(timestamp).toLocaleString('zh-CN'); }
        function getStatusBadge(status) {
            const badges = { 'pending': '<span class="badge badge-pending">待处理</span>', 'open': '<span class="badge badge-open">挂单中</span>', 'partially_filled': '<span class="badge badge-open">部分成交</span>', 'filled': '<span class="badge badge-filled">已成交</span>', 'cancelled': '<span class="badge badge-cancelled">已取消</span>' };
            return badges[status] || '<span class="badge">' + status + '</span>';
        }
        function showNotification(message, type) {
            const n = document.createElement('div'); n.className = 'notification ' + (type || 'success'); n.textContent = message;
            document.body.appendChild(n); setTimeout(() => n.remove(), 3000);
        }
        document.getElementById('orderType').addEventListener('change', function() {
            const pg = document.getElementById('priceGroup');
            pg.style.display = this.value === 'limit' ? 'flex' : 'none';
        });
        async function createOrder() {
            const data = { symbol: document.getElementById('symbol').value, side: document.getElementById('side').value, order_type: document.getElementById('orderType').value, amount: parseFloat(document.getElementById('amount').value) };
            if (data.order_type === 'limit') data.price = parseFloat(document.getElementById('price').value);
            if (!data.amount || data.amount <= 0) { showNotification('请输入有效的数量', 'error'); return; }
            try {
                const r = await fetch('/api/orders', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
                const result = await r.json();
                if (result.status === 'success') { showNotification('订单创建成功'); document.getElementById('orderForm').reset(); document.getElementById('priceGroup').style.display = 'none'; loadOrders(); refreshPositions(); }
                else showNotification(result.message || '订单创建失败', 'error');
            } catch (e) { showNotification('网络错误', 'error'); }
        }
        async function loadOrders() {
            try {
                let url = '/api/orders?limit=100';
                const status = document.getElementById('filterStatus').value;
                const side = document.getElementById('filterSide').value;
                if (status) url += '&status=' + status; if (side) url += '&side=' + side;
                const r = await fetch(url); const result = await r.json();
                const tbody = document.getElementById('ordersTableBody');
                if (result.status === 'success' && result.orders.length > 0) {
                    tbody.innerHTML = result.orders.map(o => '<tr><td>' + o.order_id + '</td><td>' + formatTime(o.created_at) + '</td><td><strong>' + o.symbol + '</strong></td><td class="side-' + o.side + '">' + o.side.toUpperCase() + '</td><td>' + o.order_type + '</td><td>' + o.amount.toFixed(4) + '</td><td>' + (o.price ? formatCurrency(o.price) : '-') + '</td><td>' + o.filled_amount.toFixed(4) + '</td><td>' + getStatusBadge(o.status) + '</td><td>' + (o.status === 'open' || o.status === 'pending' ? '<button class="btn btn-danger btn-small" onclick="cancelOrder(\'' + o.order_id + '\')">取消</button>' : '-') + '</td></tr>').join('');
                } else tbody.innerHTML = '<tr><td colspan="10" style="text-align: center; color: #8b9aad;">暂无订单</td></tr>';
            } catch (e) { console.error('Error loading orders:', e); }
        }
        async function cancelOrder(orderId) {
            if (!confirm('确定要取消此订单吗？')) return;
            try {
                const r = await fetch('/api/orders/' + orderId, { method: 'DELETE' });
                const result = await r.json();
                if (result.status === 'success') { showNotification('订单已取消'); loadOrders(); }
                else showNotification(result.message || '取消失败', 'error');
            } catch (e) { showNotification('网络错误', 'error'); }
        }
        async function refreshPositions() {
            try {
                const r = await fetch('/api/positions'); const result = await r.json();
                const tbody = document.getElementById('positionsTableBody');
                if (result.status === 'success' && result.positions.length > 0) {
                    tbody.innerHTML = result.positions.map(p => '<tr><td><strong>' + p.symbol + '</strong></td><td class="side-' + p.side + '">' + p.side.toUpperCase() + '</td><td>' + p.amount.toFixed(4) + '</td><td>' + formatCurrency(p.entry_price) + '</td><td>' + (p.current_price ? formatCurrency(p.current_price) : '-') + '</td><td class="' + (p.unrealized_pnl >= 0 ? 'positive' : 'negative') + '">' + (p.unrealized_pnl >= 0 ? '+' : '') + formatCurrency(p.unrealized_pnl) + '</td></tr>').join('');
                } else tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #8b9aad;">暂无持仓</td></tr>';
            } catch (e) { console.error('Error loading positions:', e); }
        }
        async function loadAccountSummary() {
            try {
                const r = await fetch('/api/account/summary'); const result = await r.json();
                if (result.status === 'success') {
                    const s = result.summary;
                    document.getElementById('totalOrders').textContent = s.total_orders;
                    document.getElementById('openOrders').textContent = s.open_orders;
                    document.getElementById('positionsCount').textContent = s.positions_count;
                    document.getElementById('positionsValue').textContent = formatCurrency(s.positions_value);
                    const pnlEl = document.getElementById('unrealizedPnL');
                    pnlEl.textContent = (s.unrealized_pnl >= 0 ? '+' : '') + formatCurrency(s.unrealized_pnl);
                    pnlEl.className = 'stat-value ' + (s.unrealized_pnl >= 0 ? 'positive' : 'negative');
                }
            } catch (e) { console.error('Error loading summary:', e); }
        }
        document.addEventListener('DOMContentLoaded', () => { loadOrders(); refreshPositions(); loadAccountSummary(); setInterval(() => { loadOrders(); refreshPositions(); loadAccountSummary(); }, 5000); });
    </script>
</body>
</html>
