{% extends "service_monitor/base.html" %}
{% block title %}通知配置{% endblock %}

{% block extra_css %}
<style>
    .config-section { background: #fff; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,.06); border: 1px solid var(--gray-200); margin-bottom: 20px; overflow: hidden; }
    .section-header { display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; background: var(--gray-50); border-bottom: 1px solid var(--gray-200); }
    .section-title { font-size: 16px; font-weight: 700; color: var(--gray-900); display: flex; align-items: center; gap: 8px; }
    .section-body { padding: 20px; }
    .form-row { display: flex; gap: 16px; margin-bottom: 14px; }
    .form-row .form-group { flex: 1; margin-bottom: 0; }
    .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, .form-group select, .form-group textarea { width: 100%; padding: 9px 12px; border: 1px solid var(--gray-200); border-radius: 8px; font-size: 14px; }
    .form-group input:focus, .form-group select:focus, .form-group textarea:focus { outline: none; border-color: var(--primary); }
    .form-hint { font-size: 12px; color: var(--gray-500); margin-top: 4px; }
    .toggle-row { display: flex; align-items: center; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid var(--gray-100); }
    .toggle-row:last-child { border-bottom: none; }
    .toggle-label { font-size: 14px; color: var(--gray-700); }
    .toggle-switch { position: relative; width: 52px; height: 28px; cursor: pointer; display: inline-block; }
    .toggle-switch input { opacity: 0; width: 0; height: 0; position: absolute; }
    .toggle-slider { position: absolute; cursor: pointer; inset: 0; background: #d1d5db; border-radius: 14px; transition: all 0.2s ease; pointer-events: none; border: 1px solid #9ca3af; }
    .toggle-slider:before { position: absolute; content: ""; height: 22px; width: 22px; left: 2px; bottom: 2px; background: #fff; border-radius: 50%; transition: all 0.2s ease; pointer-events: none; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
    .toggle-switch input:checked + .toggle-slider { background: var(--primary); border-color: var(--primary); }
    .toggle-switch input:checked + .toggle-slider:before { transform: translateX(24px); }
    .toggle-switch:hover .toggle-slider { box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.2); }
    .toggle-switch input:checked + .toggle-slider:hover { box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.3); }
    .btn-test { background: var(--gray-100); color: var(--gray-700); border: 1px solid var(--gray-200); padding: 8px 16px; border-radius: 8px; font-size: 13px; font-weight: 600; cursor: pointer; }
    .btn-test:hover { background: var(--gray-200); }
    .btn-test:disabled { opacity: .5; cursor: not-allowed; }
    .btn-save { background: var(--primary); color: #fff; border: none; padding: 10px 24px; border-radius: 8px; font-size: 14px; font-weight: 600; cursor: pointer; }
    .btn-save:hover { background: var(--primary-hover); }
    .test-result { margin-top: 10px; padding: 10px 14px; border-radius: 8px; font-size: 13px; }
    .test-success { background: #dcfce7; color: #15803d; }
    .test-error { background: #fee2e2; color: #b91c1c; }
    .actions { display: flex; gap: 12px; justify-content: flex-end; margin-top: 20px; padding-top: 20px; border-top: 1px solid var(--gray-200); }

    @media screen and (max-width: 768px) {
        .config-section { margin-bottom: 14px; border-radius: 10px; }
        .section-header { padding: 12px 14px; }
        .section-title { font-size: 14px; }
        .section-body { padding: 14px; }
        .form-row { flex-direction: column; gap: 0; }
        .form-row .form-group { margin-bottom: 14px; }
        /* 端口输入框自适应 */
        .form-row .form-group[style*="flex: 0 0"] { flex: 1 1 auto !important; }
        .form-group input, .form-group select, .form-group textarea {
            padding: 8px 10px; font-size: 13px;
        }
        .toggle-row { padding: 10px 0; }
        .toggle-label { font-size: 13px; }
        .btn-test { padding: 6px 12px; font-size: 12px; }
        .btn-save { padding: 8px 16px; font-size: 13px; width: 100%; }
        .actions { flex-direction: column; }
        .section-head { margin-bottom: 12px; }
    }
    @media screen and (max-width: 480px) {
        .config-section { border-radius: 8px; }
        .section-header { padding: 10px 12px; }
        .section-title { font-size: 13px; }
        .section-body { padding: 12px; }
        .form-group input, .form-group select, .form-group textarea {
            padding: 7px 8px; font-size: 12px;
        }
        .form-group label { font-size: 12px; }
        .form-hint { font-size: 11px; }
        .toggle-switch { width: 44px; height: 24px; }
        .toggle-slider:before { height: 18px; width: 18px; }
        .toggle-switch input:checked + .toggle-slider:before { transform: translateX(20px); }
        .toggle-label { font-size: 12px; }
        .btn-test { padding: 5px 10px; font-size: 11px; }
        .btn-save { padding: 7px 14px; font-size: 12px; }
        .section-head { margin-bottom: 10px; }
        .section-title { font-size: 15px; }
    }
</style>
{% endblock %}

{% block content %}
<div class="section-head">
    <div class="section-title">🔔 通知配置</div>
</div>

<!-- 邮件通知 -->
<div class="config-section">
    <div class="section-header">
        <div class="section-title">📧 邮件通知</div>
        <label class="toggle-switch">
            <input type="checkbox" id="email-enabled" onchange="toggleSection('email')">
            <span class="toggle-slider"></span>
        </label>
    </div>
    <div class="section-body" id="email-section" style="display:none;">
        <div class="form-row">
            <div class="form-group">
                <label>SMTP 服务器</label>
                <input type="text" id="email-host" placeholder="如：smtp.qq.com">
            </div>
            <div class="form-group" style="flex: 0 0 120px;">
                <label>端口</label>
                <input type="number" id="email-port" value="465" placeholder="465">
            </div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>发件人邮箱</label>
                <input type="email" id="email-user" placeholder="admin@example.com">
            </div>
            <div class="form-group">
                <label>邮箱授权码</label>
                <input type="password" id="email-password" placeholder="SMTP 认证密码">
            </div>
        </div>
        <div class="form-group">
            <label>收件人列表</label>
            <textarea id="email-recipients" rows="2" placeholder="多个邮箱用英文逗号分隔"></textarea>
            <div class="form-hint">多个收件人用英文逗号分隔，如：user1@example.com, user2@example.com</div>
        </div>
        <div class="toggle-row">
            <span class="toggle-label">使用 SSL 加密</span>
            <label class="toggle-switch">
                <input type="checkbox" id="email-ssl" checked>
                <span class="toggle-slider"></span>
            </label>
        </div>
        <div class="form-group">
            <label>邮件主题模板</label>
            <input type="text" id="email-subject" value="【巡检报告】{target} - {status}">
            <div class="form-hint">支持变量：{target} 目标名称, {status} 状态, {suite} 套件</div>
        </div>
        <div style="display: flex; gap: 10px; align-items: center;">
            <button class="btn-test" onclick="testEmail()">发送测试邮件</button>
            <div id="email-test-result"></div>
        </div>
    </div>
</div>

<!-- 钉钉通知 -->
<div class="config-section">
    <div class="section-header">
        <div class="section-title">📱 钉钉机器人</div>
        <label class="toggle-switch">
            <input type="checkbox" id="dingtalk-enabled" onchange="toggleSection('dingtalk')">
            <span class="toggle-slider"></span>
        </label>
    </div>
    <div class="section-body" id="dingtalk-section" style="display:none;">
        <div class="form-group">
            <label>Webhook 地址</label>
            <input type="text" id="dingtalk-webhook-url" placeholder="https://oapi.dingtalk.com/robot/send?access_token=xxx">
            <div class="form-hint">钉钉群机器人设置页面获取</div>
        </div>
        <div class="form-group">
            <label>签名密钥（可选）</label>
            <input type="password" id="dingtalk-secret" placeholder="加签机器人的密钥"
                   oncopy="return false" oncut="return false"
                   oncontextmenu="return false" autocomplete="off">
            <div class="form-hint">如果机器人设置了加签，需要填写密钥。出于安全考虑，密钥无法复制、剪切</div>
        </div>
        <div class="form-group">
            <label>@人员手机号（可选）</label>
            <input type="text" id="dingtalk-at" placeholder="多个手机号用英文逗号分隔">
        </div>
        <div style="display: flex; gap: 10px; align-items: center;">
            <button class="btn-test" onclick="testDingtalk()">发送测试消息</button>
            <div id="dingtalk-test-result"></div>
        </div>
    </div>
</div>

<!-- 企业微信通知 -->
<div class="config-section">
    <div class="section-header">
        <div class="section-title">💬 企业微信机器人</div>
        <label class="toggle-switch">
            <input type="checkbox" id="wecom-enabled" onchange="toggleSection('wecom')">
            <span class="toggle-slider"></span>
        </label>
    </div>
    <div class="section-body" id="wecom-section" style="display:none;">
        <div class="form-group">
            <label>Webhook 地址</label>
            <input type="text" id="wecom-webhook" placeholder="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx">
        </div>
        <div style="display: flex; gap: 10px; align-items: center;">
            <button class="btn-test" onclick="testWecom()">发送测试消息</button>
            <div id="wecom-test-result"></div>
        </div>
    </div>
</div>

<!-- 触发条件 -->
<div class="config-section">
    <div class="section-header">
        <div class="section-title">⚡ 触发条件</div>
    </div>
    <div class="section-body">
        <div class="toggle-row">
            <span class="toggle-label">报告完成后立即通知</span>
            <label class="toggle-switch">
                <input type="checkbox" id="trigger-complete" checked>
                <span class="toggle-slider"></span>
            </label>
        </div>
        <div class="toggle-row">
            <span class="toggle-label">仅异常（警告/严重）时通知</span>
            <label class="toggle-switch">
                <input type="checkbox" id="trigger-abnormal">
                <span class="toggle-slider"></span>
            </label>
        </div>
        <div class="toggle-row">
            <span class="toggle-label">包含异常详情</span>
            <label class="toggle-switch">
                <input type="checkbox" id="trigger-details" checked>
                <span class="toggle-slider"></span>
            </label>
        </div>
        <div class="toggle-row">
            <span class="toggle-label">包含报告链接</span>
            <label class="toggle-switch">
                <input type="checkbox" id="trigger-link" checked>
                <span class="toggle-slider"></span>
            </label>
        </div>
    </div>
</div>

<!-- 连续异常告警 -->
<div class="config-section">
    <div class="section-header">
        <div class="section-title">🔄 连续异常告警</div>
        <label class="toggle-switch">
            <input type="checkbox" id="alert-consecutive-enabled" onchange="toggleAlertConsecutive()">
            <span class="toggle-slider"></span>
        </label>
    </div>
    <div class="section-body" id="alert-consecutive-section" style="display:none;">
        <div class="form-row">
            <div class="form-group">
                <label>连续次数阈值</label>
                <input type="number" id="alert-consecutive-threshold" value="3" min="2" max="10">
                <div class="form-hint">同一检测项连续 N 次异常时发送告警</div>
            </div>
            <div class="form-group">
                <label>告警级别</label>
                <select id="alert-consecutive-level">
                    <option value="critical">仅严重</option>
                    <option value="all">警告 + 严重</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label>通知渠道</label>
            <div style="display: flex; gap: 16px; margin-top: 6px;">
                <label style="display: flex; align-items: center; gap: 6px; font-size: 14px; font-weight: normal; cursor: pointer;">
                    <input type="checkbox" id="alert-channel-email"> 邮件
                </label>
                <label style="display: flex; align-items: center; gap: 6px; font-size: 14px; font-weight: normal; cursor: pointer;">
                    <input type="checkbox" id="alert-channel-dingtalk"> 钉钉
                </label>
                <label style="display: flex; align-items: center; gap: 6px; font-size: 14px; font-weight: normal; cursor: pointer;">
                    <input type="checkbox" id="alert-channel-wecom"> 企微
                </label>
            </div>
            <div class="form-hint">复用上方已配置的通知渠道</div>
        </div>
    </div>
</div>

<div class="actions">
    <button class="btn-save" onclick="saveConfig()">保存配置</button>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 加载配置
async function loadConfig() {
    try {
        const r = await fetch('/api/service-monitor/notification', { credentials: 'include' });
        const d = await r.json();
        if (d.success) {
            const cfg = d.config;

            // 邮件
            document.getElementById('email-enabled').checked = cfg.email?.enabled || false;
            document.getElementById('email-host').value = cfg.email?.smtp_host || '';
            document.getElementById('email-port').value = cfg.email?.smtp_port || 465;
            document.getElementById('email-user').value = cfg.email?.smtp_user || '';
            document.getElementById('email-password').value = '';  // 密码不回填
            document.getElementById('email-recipients').value = (cfg.email?.recipients || []).join(', ');
            document.getElementById('email-ssl').checked = cfg.email?.use_ssl !== false;
            document.getElementById('email-subject').value = cfg.email?.subject_template || '【巡检报告】{target} - {status}';
            toggleSection('email');

            // 钉钉
            document.getElementById('dingtalk-enabled').checked = cfg.dingtalk?.enabled || false;
            // 兼容旧字段名 webhook -> webhook_url
            const webhookUrl = cfg.dingtalk?.webhook_url || cfg.dingtalk?.webhook || '';
            document.getElementById('dingtalk-webhook-url').value = webhookUrl;
            document.getElementById('dingtalk-secret').value = '';
            document.getElementById('dingtalk-at').value = (cfg.dingtalk?.at_mobiles || []).join(', ');
            toggleSection('dingtalk');

            // 企业微信
            document.getElementById('wecom-enabled').checked = cfg.wecom?.enabled || false;
            document.getElementById('wecom-webhook').value = cfg.wecom?.webhook || '';
            toggleSection('wecom');

            // 触发条件
            document.getElementById('trigger-complete').checked = cfg.trigger?.on_complete !== false;
            document.getElementById('trigger-abnormal').checked = cfg.trigger?.on_abnormal_only || false;
            document.getElementById('trigger-details').checked = cfg.trigger?.include_details !== false;
            document.getElementById('trigger-link').checked = cfg.trigger?.include_link !== false;

            // 连续异常告警
            const alertCfg = cfg.alert_on_consecutive || {};
            document.getElementById('alert-consecutive-enabled').checked = alertCfg.enabled || false;
            document.getElementById('alert-consecutive-threshold').value = alertCfg.consecutive_threshold || 3;
            document.getElementById('alert-consecutive-level').value = alertCfg.alert_level || 'critical';
            const channels = alertCfg.channels || [];
            document.getElementById('alert-channel-email').checked = channels.includes('email');
            document.getElementById('alert-channel-dingtalk').checked = channels.includes('dingtalk');
            document.getElementById('alert-channel-wecom').checked = channels.includes('wecom');
            toggleAlertConsecutive();
        }
    } catch (e) {
        console.error('加载配置失败:', e);
    }
}

function toggleSection(name) {
    const enabled = document.getElementById(name + '-enabled').checked;
    const section = document.getElementById(name + '-section');
    section.style.display = enabled ? '' : 'none';
}

function toggleAlertConsecutive() {
    const enabled = document.getElementById('alert-consecutive-enabled').checked;
    document.getElementById('alert-consecutive-section').style.display = enabled ? '' : 'none';
}

async function testEmail() {
    const btn = event.target;
    btn.disabled = true;
    btn.textContent = '发送中...';
    document.getElementById('email-test-result').innerHTML = '';

    try {
        // 先保存当前配置
        await saveConfig(true);

        const r = await fetch('/api/service-monitor/notification/test-email', {
            method: 'POST',
            credentials: 'include'
        });
        const d = await r.json();
        const el = document.getElementById('email-test-result');
        el.innerHTML = `<div class="test-result ${d.success ? 'test-success' : 'test-error'}">${d.message}</div>`;
    } catch (e) {
        document.getElementById('email-test-result').innerHTML = `<div class="test-result test-error">请求失败</div>`;
    }
    btn.disabled = false;
    btn.textContent = '发送测试邮件';
}

async function testDingtalk() {
    const btn = event.target;
    btn.disabled = true;
    btn.textContent = '发送中...';
    document.getElementById('dingtalk-test-result').innerHTML = '';

    try {
        await saveConfig(true);
        const r = await fetch('/api/service-monitor/notification/test-dingtalk', {
            method: 'POST',
            credentials: 'include'
        });
        const d = await r.json();
        const el = document.getElementById('dingtalk-test-result');
        el.innerHTML = `<div class="test-result ${d.success ? 'test-success' : 'test-error'}">${d.message}</div>`;
    } catch (e) {
        document.getElementById('dingtalk-test-result').innerHTML = `<div class="test-result test-error">请求失败</div>`;
    }
    btn.disabled = false;
    btn.textContent = '发送测试消息';
}

async function testWecom() {
    const btn = event.target;
    btn.disabled = true;
    btn.textContent = '发送中...';
    document.getElementById('wecom-test-result').innerHTML = '';

    try {
        await saveConfig(true);
        const r = await fetch('/api/service-monitor/notification/test-wecom', {
            method: 'POST',
            credentials: 'include'
        });
        const d = await r.json();
        const el = document.getElementById('wecom-test-result');
        el.innerHTML = `<div class="test-result ${d.success ? 'test-success' : 'test-error'}">${d.message}</div>`;
    } catch (e) {
        document.getElementById('wecom-test-result').innerHTML = `<div class="test-result test-error">请求失败</div>`;
    }
    btn.disabled = false;
    btn.textContent = '发送测试消息';
}

async function saveConfig(silent = false) {
    const data = {
        email: {
            enabled: document.getElementById('email-enabled').checked,
            smtp_host: document.getElementById('email-host').value.trim(),
            smtp_port: parseInt(document.getElementById('email-port').value) || 465,
            smtp_user: document.getElementById('email-user').value.trim(),
            smtp_password: document.getElementById('email-password').value,
            use_ssl: document.getElementById('email-ssl').checked,
            recipients: document.getElementById('email-recipients').value.split(',').map(s => s.trim()).filter(Boolean),
            subject_template: document.getElementById('email-subject').value.trim()
        },
        dingtalk: {
            enabled: document.getElementById('dingtalk-enabled').checked,
            webhook_url: document.getElementById('dingtalk-webhook-url').value.trim(),
            secret: document.getElementById('dingtalk-secret').value,
            at_mobiles: document.getElementById('dingtalk-at').value.split(',').map(s => s.trim()).filter(Boolean)
        },
        wecom: {
            enabled: document.getElementById('wecom-enabled').checked,
            webhook: document.getElementById('wecom-webhook').value.trim()
        },
        trigger: {
            on_complete: document.getElementById('trigger-complete').checked,
            on_abnormal_only: document.getElementById('trigger-abnormal').checked,
            include_details: document.getElementById('trigger-details').checked,
            include_link: document.getElementById('trigger-link').checked
        },
        alert_on_consecutive: {
            enabled: document.getElementById('alert-consecutive-enabled').checked,
            consecutive_threshold: parseInt(document.getElementById('alert-consecutive-threshold').value) || 3,
            alert_level: document.getElementById('alert-consecutive-level').value,
            channels: [
                ...(document.getElementById('alert-channel-email').checked ? ['email'] : []),
                ...(document.getElementById('alert-channel-dingtalk').checked ? ['dingtalk'] : []),
                ...(document.getElementById('alert-channel-wecom').checked ? ['wecom'] : [])
            ]
        }
    };

    try {
        const r = await fetch('/api/service-monitor/notification', {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            credentials: 'include',
            body: JSON.stringify(data)
        });
        const d = await r.json();
        if (!silent) {
            if (d.success) {
                alert('配置已保存');
            } else {
                alert(d.error?.message || '保存失败');
            }
        }
        return d.success;
    } catch (e) {
        if (!silent) alert('请求失败');
        return false;
    }
}

// 页面加载时读取配置
loadConfig();
</script>
{% endblock %}
