{% 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: 48px; height: 26px; }
    .toggle-switch input { opacity: 0; width: 0; height: 0; }
    .toggle-slider { position: absolute; cursor: pointer; inset: 0; background: var(--gray-300); border-radius: 13px; transition: .2s; }
    .toggle-slider:before { position: absolute; content: ""; height: 20px; width: 20px; left: 3px; bottom: 3px; background: #fff; border-radius: 50%; transition: .2s; }
    .toggle-switch input:checked + .toggle-slider { background: var(--primary); }
    .toggle-switch input:checked + .toggle-slider:before { transform: translateX(22px); }
    .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) {
        .form-row { flex-direction: column; gap: 0; }
        .form-row .form-group { margin-bottom: 14px; }
    }
</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" placeholder="https://oapi.dingtalk.com/robot/send?access_token=xxx">
        </div>
        <div class="form-group">
            <label>签名密钥（可选）</label>
            <input type="password" id="dingtalk-secret" placeholder="加签机器人的密钥">
            <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="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;
            document.getElementById('dingtalk-webhook').value = cfg.dingtalk?.webhook || '';
            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;
        }
    } 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';
}

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: document.getElementById('dingtalk-webhook').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
        }
    };

    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 %}
