<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5">
    <title>目标管理 - 服务监测</title>
    <style>
        :root {
            --primary: #2563eb; --primary-hover: #1d4ed8;
            --red: #dc2626; --green: #16a34a;
            --gray-50:#f9fafb; --gray-100:#f3f4f6; --gray-200:#e5e7eb;
            --gray-500:#6b7280; --gray-700:#374151; --gray-900:#111827;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Microsoft YaHei", sans-serif; background:#f3f4f6; min-height:100vh; }
        .navbar { background: linear-gradient(135deg,#667eea 0%,#764ba2 100%); padding:14px 24px; display:flex; align-items:center; justify-content:space-between; }
        .navbar-left { display:flex; align-items:center; gap:14px; }
        .navbar-brand { color:#fff; font-size:18px; font-weight:700; text-decoration:none; }
        .navbar-module { color:rgba(255,255,255,.7); font-size:14px; }
        .navbar-home { background:rgba(255,255,255,.2); color:#fff; border:1px solid rgba(255,255,255,.35); padding:6px 14px; border-radius:8px; font-size:13px; font-weight:600; text-decoration:none; }
        .navbar-user { color:#fff; display:flex; align-items:center; gap:14px; font-size:14px; }
        .btn-logout { background:rgba(255,255,255,.15); color:#fff; border:1px solid rgba(255,255,255,.3); padding:8px 16px; border-radius:8px; cursor:pointer; font-size:14px; }

        .container { max-width:1000px; margin:0 auto; padding:28px 24px; }
        .section-head { display:flex; align-items:center; justify-content:space-between; margin-bottom:16px; }
        .section-title { font-size:18px; font-weight:700; color:var(--gray-900); }
        .btn-add { background:var(--primary); color:#fff; border:none; padding:8px 16px; border-radius:8px; font-size:14px; font-weight:600; cursor:pointer; }

        /* 表格 */
        .table { background:#fff; border-radius:12px; box-shadow:0 2px 8px rgba(0,0,0,.06); border:1px solid var(--gray-200); overflow:hidden; }
        .table-head, .table-row { display:grid; grid-template-columns: 1.5fr 2fr 1fr 1.5fr 1.5fr; gap:12px; padding:12px 18px; align-items:center; }
        .table-head { background:var(--gray-50); font-size:13px; color:var(--gray-500); font-weight:600; border-bottom:1px solid var(--gray-200); }
        .table-row { border-bottom:1px solid var(--gray-100); font-size:14px; }
        .table-row:last-child { border-bottom:none; }
        .name { font-weight:600; color:var(--gray-900); }
        .type-badge { font-size:12px; padding:2px 8px; border-radius:4px; }
        .badge-local { background:#dcfce7; color:#15803d; }
        .badge-remote { background:#dbeafe; color:#1d4ed8; }
        .actions { display:flex; gap:8px; }
        .btn-sm { padding:5px 12px; border-radius:6px; font-size:12px; font-weight:600; cursor:pointer; border:none; text-decoration:none; display:inline-block; }
        .btn-edit { background:var(--gray-100); color:var(--gray-700); }
        .btn-del { background:#fee2e2; color:var(--red); }
        .btn-del:disabled { opacity:.4; cursor:not-allowed; }

        /* 弹窗 */
        .modal-mask { display:none; position:fixed; inset:0; background:rgba(0,0,0,.4); z-index:100; align-items:center; justify-content:center; padding:20px; }
        .modal-mask.show { display:flex; }
        .modal { background:#fff; border-radius:14px; padding:28px; width:100%; max-width:460px; max-height:90vh; overflow-y:auto; }
        .modal h3 { font-size:18px; color:var(--gray-900); margin-bottom:18px; }
        .form-group { margin-bottom:14px; }
        .form-group label { display:block; font-size:13px; color:var(--gray-700); margin-bottom:5px; font-weight:600; }
        .form-group input { width:100%; padding:9px 12px; border:1px solid var(--gray-200); border-radius:8px; font-size:14px; }
        .form-group input:focus { outline:none; border-color:var(--primary); }
        .form-hint { font-size:12px; color:var(--gray-500); margin-top:4px; }
        .modal-actions { display:flex; gap:10px; justify-content:flex-end; margin-top:20px; }
        .btn-cancel { background:var(--gray-100); color:var(--gray-700); border:none; padding:9px 18px; border-radius:8px; cursor:pointer; font-size:14px; font-weight:600; }
        .btn-save { background:var(--primary); color:#fff; border:none; padding:9px 18px; border-radius:8px; cursor:pointer; font-size:14px; font-weight:600; }
        .btn-save:disabled { opacity:.6; cursor:not-allowed; }
        .btn-test { background:var(--gray-100); color:var(--gray-700); border:none; padding:9px 14px; border-radius:8px; cursor:pointer; font-size:13px; font-weight:600; }
        .test-msg { font-size:13px; margin-top:8px; min-height:18px; }

        .empty { text-align:center; padding:40px; color:var(--gray-500); }
        .footer { text-align:center; padding:20px; color:var(--gray-500); font-size:12px; }

        @media screen and (max-width:768px) {
            .container { padding:20px 14px; }
            .table-head { display:none; }
            .table-row { grid-template-columns: 1fr 1fr; gap:6px; padding:14px; }
            .navbar-module { display:none; }
        }
    </style>
</head>
<body>
    <div class="navbar">
        <div class="navbar-left">
            <a href="/" class="navbar-brand">🛠️ 运行维护平台</a>
            <span class="navbar-module">/ 服务监测 / 目标管理</span>
            <a href="/service-monitor" class="navbar-home">← 返回</a>
        </div>
        <div class="navbar-user">
            <span>{{ user.username }}（管理员）</span>
            <button class="btn-logout" onclick="handleLogout()">🚪 退出</button>
        </div>
    </div>

    <div class="container">
        <div class="section-head">
            <div class="section-title">⚙️ 监测目标管理</div>
            <button class="btn-add" onclick="openCreate()">+ 新增远程目标</button>
        </div>

        <div class="table">
            <div class="table-head">
                <span>名称</span><span>主机</span><span>类型</span><span>用户名</span><span>操作</span>
            </div>
            {% for t in targets %}
            <div class="table-row">
                <span class="name">{{ t.name }}</span>
                <span>{{ '本机' if t.type == 'local' else (t.host ~ ':' ~ t.port) }}</span>
                <span><span class="type-badge {{ 'badge-local' if t.type == 'local' else 'badge-remote' }}">{{ '本机' if t.type == 'local' else '远程' }}</span></span>
                <span>{{ t.username or '-' }}</span>
                <div class="actions">
                    <button class="btn-sm btn-edit" onclick="openEdit('{{ t.id }}')">编辑</button>
                    <button class="btn-sm btn-del" onclick="delTarget('{{ t.id }}','{{ t.name }}')" {{ '' if not t.built_in else 'disabled' }}>删除</button>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <div class="modal-mask" id="modal">
        <div class="modal">
            <h3 id="modal-title">新增远程目标</h3>
            <input type="hidden" id="f-id">
            <div class="form-group">
                <label>目标名称</label>
                <input type="text" id="f-name" placeholder="如：生产数据库服务器">
            </div>
            <div class="form-group">
                <label>主机地址</label>
                <input type="text" id="f-host" placeholder="192.168.x.x 或 域名">
            </div>
            <div class="form-group">
                <label>SSH 端口</label>
                <input type="number" id="f-port" value="22">
            </div>
            <div class="form-group">
                <label>用户名</label>
                <input type="text" id="f-username" value="root">
            </div>
            <div class="form-group">
                <label>密码 <span id="pw-label" style="font-weight:400;color:var(--gray-500)"></span></label>
                <input type="password" id="f-password" placeholder="SSH 密码">
                <div class="form-hint">密码将加密存储，编辑时不填表示不修改</div>
            </div>
            <div class="test-msg" id="test-msg"></div>
            <div class="modal-actions">
                <button class="btn-test" onclick="testConn()">🔌 测试连接</button>
                <button class="btn-cancel" onclick="closeModal()">取消</button>
                <button class="btn-save" id="btn-save" onclick="saveTarget()">保存</button>
            </div>
        </div>
    </div>

    <div class="footer">运行维护平台 · 服务监测模块</div>

    <script>
        const TARGETS = {{ targets | tojson | safe }};

        function openCreate() {
            document.getElementById('modal-title').textContent = '新增远程目标';
            document.getElementById('f-id').value = '';
            document.getElementById('f-name').value = '';
            document.getElementById('f-host').value = '';
            document.getElementById('f-port').value = '22';
            document.getElementById('f-username').value = 'root';
            document.getElementById('f-password').value = '';
            document.getElementById('f-password').placeholder = 'SSH 密码';
            document.getElementById('pw-label').textContent = '';
            document.getElementById('test-msg').textContent = '';
            document.getElementById('modal').classList.add('show');
        }

        function openEdit(id) {
            const t = TARGETS.find(x => x.id === id);
            if (!t) return;
            document.getElementById('modal-title').textContent = '编辑目标：' + t.name;
            document.getElementById('f-id').value = t.id;
            document.getElementById('f-name').value = t.name;
            document.getElementById('f-host').value = t.host || '';
            document.getElementById('f-port').value = t.port || 22;
            document.getElementById('f-username').value = t.username || '';
            document.getElementById('f-password').value = '';
            document.getElementById('f-password').placeholder = t.has_password ? '已设置，不填则不改' : 'SSH 密码';
            document.getElementById('pw-label').textContent = t.has_password ? '（已加密保存）' : '';
            document.getElementById('test-msg').textContent = '';
            document.getElementById('modal').classList.add('show');
        }

        function closeModal() { document.getElementById('modal').classList.remove('show'); }

        async function testConn() {
            const msg = document.getElementById('test-msg');
            const host = document.getElementById('f-host').value.trim();
            if (!host) { msg.style.color = 'var(--red)'; msg.textContent = '请先填写主机地址'; return; }
            msg.style.color = 'var(--gray-500)'; msg.textContent = '测试中...';
            try {
                const r = await fetch('/api/service-monitor/targets/test', {
                    method: 'POST', headers: {'Content-Type':'application/json'}, credentials:'include',
                    body: JSON.stringify({
                        host, port: parseInt(document.getElementById('f-port').value) || 22,
                        username: document.getElementById('f-username').value.trim(),
                        password: document.getElementById('f-password').value,
                    })
                });
                const d = await r.json();
                msg.style.color = d.success ? 'var(--green)' : 'var(--red)';
                msg.textContent = (d.success ? '✓ ' : '✗ ') + (d.message || '');
            } catch(e) { msg.style.color='var(--red)'; msg.textContent = '✗ 请求失败'; }
        }

        async function saveTarget() {
            const id = document.getElementById('f-id').value;
            const name = document.getElementById('f-name').value.trim();
            const host = document.getElementById('f-host').value.trim();
            const username = document.getElementById('f-username').value.trim();
            const password = document.getElementById('f-password').value;
            if (!name || !host || !username) { alert('请填写完整信息'); return; }
            if (!id && !password) { alert('请填写密码'); return; }

            const body = { name, host, port: parseInt(document.getElementById('f-port').value) || 22, username };
            if (password) body.password = password;

            const url = id ? '/api/service-monitor/targets/' + id : '/api/service-monitor/targets';
            const method = id ? 'PUT' : 'POST';
            try {
                const r = await fetch(url, { method, headers:{'Content-Type':'application/json'}, credentials:'include', body: JSON.stringify(body) });
                const d = await r.json();
                if (d.success) { location.reload(); }
                else { alert(d.error?.message || '保存失败'); }
            } catch(e) { alert('请求失败'); }
        }

        async function delTarget(id, name) {
            if (!confirm('确认删除目标「' + name + '」？')) return;
            const r = await fetch('/api/service-monitor/targets/' + id, { method:'DELETE', credentials:'include' });
            const d = await r.json();
            if (d.success) location.reload(); else alert(d.error?.message || '删除失败');
        }

        async function handleLogout() {
            try { await fetch('/logout', {method:'POST', headers:{'Content-Type':'application/json'}, credentials:'include'}); } catch(e) {}
            window.location.href = '/login';
        }
    </script>
</body>
</html>
