{% extends "service_monitor/base.html" %}
{% block title %}目标管理{% endblock %}

{% block extra_css %}
<style>
    /* 表格 */
    .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 1fr 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: 200; 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; }

    @media screen and (max-width: 768px) {
        .table-head { display: none; }
        .table-row {
            grid-template-columns: 1fr 1fr;
            gap: 6px; padding: 14px;
            border-bottom: 2px solid var(--gray-200);
        }
        .table-row .name { font-size: 15px; }
        .actions { flex-wrap: wrap; gap: 4px; }
        .btn-sm { padding: 4px 8px; font-size: 11px; }
        .modal { padding: 16px; max-width: 100%; border-radius: 12px; }
        .modal h3 { font-size: 16px; }
        .section-head { flex-direction: column; align-items: flex-start; gap: 10px; }
        .btn-add { width: 100%; text-align: center; }
    }
    @media screen and (max-width: 480px) {
        .table-row { padding: 12px; gap: 4px; }
        .table-row .name { font-size: 14px; }
        .actions { gap: 3px; }
        .btn-sm { padding: 3px 6px; font-size: 10px; }
        .modal { padding: 14px; }
        .modal h3 { font-size: 15px; }
        .form-group input { padding: 7px 10px; font-size: 13px; }
        .btn-cancel, .btn-save { padding: 7px 14px; font-size: 13px; }
        .section-title { font-size: 15px; }
        .btn-add { font-size: 12px; padding: 7px 12px; }
    }
</style>
{% endblock %}

{% block content %}
<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>sudo</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>
        <span>{{ '是' if t.use_sudo else '-' }}</span>
        <div class="actions">
            {% if t.type == 'remote' %}
            <button class="btn-sm btn-edit" onclick="openEdit('{{ t.id }}')">编辑</button>
            <button class="btn-sm btn-del" onclick="deleteTarget('{{ t.id }}')">删除</button>
            {% else %}
            <button class="btn-sm btn-edit" disabled>内置</button>
            <button class="btn-sm btn-del" disabled>删除</button>
            {% endif %}
        </div>
    </div>
    {% endfor %}
</div>

<!-- 新增/编辑弹窗 -->
<div class="modal-mask" id="modal">
    <div class="modal">
        <h3 id="modal-title">新增远程目标</h3>
        <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.1.100">
        </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" placeholder="如：root">
        </div>
        <div class="form-group">
            <label>密码</label>
            <input type="password" id="f-password" placeholder="SSH 登录密码">
            <div class="form-hint">密码将加密存储</div>
        </div>
        <div class="form-group">
            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                <input type="checkbox" id="f-use-sudo" style="width: 16px; height: 16px;">
                <span>需要 sudo 提权</span>
            </label>
            <div class="form-hint">SSH 用户非 root 时勾选，将用 sudo 执行巡检命令</div>
        </div>
        <div class="form-group">
            <label>工作目录（可选）</label>
            <input type="text" id="f-workdir-base" placeholder="/tmp/check_modules">
            <div class="form-hint">巡检脚本上传目录。部分系统（如麒麟）用户只能写入 /home/user/，可设为 /home/openkylin/check_modules</div>
        </div>
        <div style="margin-bottom: 14px;">
            <button class="btn-test" onclick="testConnection()">测试连接</button>
            <div class="test-msg" id="test-msg"></div>
        </div>
        <div class="modal-actions">
            <button class="btn-cancel" onclick="closeModal()">取消</button>
            <button class="btn-save" id="btn-save" onclick="saveTarget()">保存</button>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let editingId = null;

function openCreate() {
    editingId = null;
    document.getElementById('modal-title').textContent = '新增远程目标';
    document.getElementById('f-name').value = '';
    document.getElementById('f-host').value = '';
    document.getElementById('f-port').value = '22';
    document.getElementById('f-username').value = '';
    document.getElementById('f-password').value = '';
    document.getElementById('f-use-sudo').checked = false;
    document.getElementById('f-workdir-base').value = '';
    document.getElementById('test-msg').textContent = '';
    document.getElementById('modal').classList.add('show');
}

async function openEdit(id) {
    editingId = id;
    document.getElementById('modal-title').textContent = '编辑目标';
    document.getElementById('test-msg').textContent = '';

    // 获取目标数据
    try {
        const r = await fetch('/api/service-monitor/targets/' + id, {
            credentials: 'include',
        });
        const d = await r.json();
        if (d.success && d.target) {
            document.getElementById('f-name').value = d.target.name || '';
            document.getElementById('f-host').value = d.target.host || '';
            document.getElementById('f-port').value = d.target.port || 22;
            document.getElementById('f-username').value = d.target.username || '';
            document.getElementById('f-password').value = '';  // 密码不回填，留空表示不修改
            document.getElementById('f-use-sudo').checked = d.target.use_sudo || false;
            document.getElementById('f-workdir-base').value = d.target.workdir_base || '';
        } else {
            alert('获取目标信息失败');
            return;
        }
    } catch (e) {
        alert('请求失败');
        return;
    }

    document.getElementById('modal').classList.add('show');
}

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

async function testConnection() {
    const msg = document.getElementById('test-msg');
    msg.textContent = '测试中...';
    msg.style.color = 'var(--gray-500)';

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

    if (!data.host || !data.username) {
        msg.textContent = '请填写主机和用户名';
        msg.style.color = 'var(--red)';
        return;
    }

    try {
        const r = await fetch('/api/service-monitor/targets/test', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            credentials: 'include',
            body: JSON.stringify(data),
        });
        const d = await r.json();
        if (d.success) {
            msg.textContent = '✓ 连接成功';
            msg.style.color = 'var(--green)';
        } else {
            msg.textContent = '✗ ' + (d.message || '连接失败');
            msg.style.color = 'var(--red)';
            if (d.detail) msg.title = d.detail;
        }
    } catch (e) {
        msg.textContent = '✗ 请求失败';
        msg.style.color = 'var(--red)';
    }
}

async function saveTarget() {
    const workdirBase = document.getElementById('f-workdir-base').value.trim();
    const data = {
        name: document.getElementById('f-name').value,
        host: document.getElementById('f-host').value,
        port: parseInt(document.getElementById('f-port').value) || 22,
        username: document.getElementById('f-username').value,
        password: document.getElementById('f-password').value,
        use_sudo: document.getElementById('f-use-sudo').checked,
        workdir_base: workdirBase || null,  // 空值传 null
    };

    if (!data.name || !data.host || !data.username) {
        alert('请填写名称、主机和用户名');
        return;
    }

    const url = editingId
        ? '/api/service-monitor/targets/' + editingId
        : '/api/service-monitor/targets';
    const method = editingId ? 'PUT' : 'POST';

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

async function deleteTarget(id) {
    if (!confirm('确定删除该目标？')) return;
    try {
        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('删除失败');
        }
    } catch (e) {
        alert('请求失败');
    }
}
</script>
{% endblock %}