{% extends "base.html" %}
{% load static %}

{% block title %}投资信号管理 - AgomTradePro{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'css/signal.css' %}">
{% endblock %}

{% block content %}
<div class="signal-container">
    <!-- 头部 -->
    <div class="signal-header">
        <h1>投资信号</h1>
        {% if current_regime %}
        <div class="regime-badge">当前: {{ current_regime.dominant_regime }}</div>
        {% endif %}
    </div>

    <!-- 投资免责声明 -->
    {% include 'components/investment_disclaimer.html' %}

    <!-- 统计 -->
    <div class="stats-row">
        <div class="stat-card"><div class="stat-value">{{ stats.total }}</div><div class="stat-label">总计</div></div>
        <div class="stat-card"><div class="stat-value" style="color: #10b981;">{{ stats.approved }}</div><div class="stat-label">已通过</div></div>
        <div class="stat-card"><div class="stat-value" style="color: #f59e0b;">{{ stats.pending }}</div><div class="stat-label">待审核</div></div>
        <div class="stat-card"><div class="stat-value" style="color: #ef4444;">{{ stats.rejected }}</div><div class="stat-label">已拒绝</div></div>
        <div class="stat-card"><div class="stat-value" style="color: #9ca3af;">{{ stats.invalidated }}</div><div class="stat-label">已证伪</div></div>
    </div>

    <!-- 批量操作 -->
    <div class="batch-actions">
        <span style="font-size: 13px;">💡 系统会自动检查已批准信号是否满足证伪条件</span>
        <button class="btn-batch" onclick="batchCheck()">🔄 立即检查所有信号</button>
    </div>

    <!-- AI 助手 -->
    <div class="ai-assistant">
        <div class="ai-header">
            <span style="font-size: 20px;">🤖</span>
            <h3>AI 证伪助手</h3>
        </div>
        <div class="ai-input-area">
            <textarea id="aiInput" class="ai-input" placeholder="用自然语言描述证伪条件，AI会帮你生成规则&#10;&#10;例如：&#10;- PMI跌破50且连续2个月&#10;- CPI超过3%或者M2低于8%&#10;- 当制造业PMI小于荣枯线时证伪"></textarea>
        </div>
        <div class="ai-actions">
            <button class="btn-ai" onclick="aiGenerate()">✨ AI 生成规则</button>
            <button class="btn-clear" onclick="clearAiResult()">清除</button>
        </div>
        <div id="aiResult" class="ai-result"></div>
        <div id="aiSuggestions" class="ai-suggestions" style="display: none;"></div>
    </div>

    <!-- 创建表单 -->
    <div class="condition-builder">
        <div class="builder-header">
            <h3>新建投资信号</h3>
        </div>

        <form id="createForm">
            <div class="builder-body">
                <input type="text" name="asset_code" class="form-input" placeholder="资产代码 (如 ASSET_CODE)" required>
                <select name="asset_class" class="form-select" required>
                    <option value="">资产类别</option>
                    {% for ac in all_asset_classes %}
                    <option value="{{ ac }}">{{ ac }}</option>
                    {% endfor %}
                </select>
                <select name="direction" class="form-select">
                    <option value="LONG">做多</option>
                    <option value="SHORT">做空</option>
                    <option value="NEUTRAL">中性</option>
                </select>
                <select name="target_regime" class="form-select">
                    <option value="Recovery">Recovery (复苏)</option>
                    <option value="Overheat">Overheat (过热)</option>
                    <option value="Stagflation">Stagflation (滞胀)</option>
                    <option value="Deflation">Deflation (通缩)</option>
                </select>
            </div>

            <input type="text" name="logic_desc" class="form-input" style="width:100%;margin-bottom:12px;" placeholder="投资逻辑描述 (必填)" required>

            <h4 style="margin: 0 0 12px 0; font-size: 14px;">证伪条件</h4>

            <div id="conditionsList" class="conditions-list"></div>

            <div class="builder-body" style="margin-bottom: 12px;">
                <select id="indicatorSelect" class="form-select">
                    <option value="">选择指标</option>
                    {% for ind in available_indicators %}
                    <option value="{{ ind.code }}" data-threshold="{{ ind.suggested_threshold }}">
                        {{ ind.name }} (最新: {{ ind.latest_value|default_if_none:"" }})
                    </option>
                    {% endfor %}
                </select>
                <select id="conditionSelect" class="form-select">
                    <option value="lt">&lt; 小于</option>
                    <option value="lte">&le; 小于等于</option>
                    <option value="gt">&gt; 大于</option>
                    <option value="gte">&ge; 大于等于</option>
                    <option value="eq">= 等于</option>
                </select>
                <input type="number" id="thresholdInput" class="form-input" placeholder="阈值" step="0.01">
                <button type="button" class="btn-add" onclick="addCondition()">+ 添加条件</button>
            </div>

            <div style="display: flex; gap: 12px; margin-bottom: 12px;">
                <label style="font-size: 13px;">
                    <input type="radio" name="logic" value="AND" checked> 所有条件都满足 (AND)
                </label>
                <label style="font-size: 13px;">
                    <input type="radio" name="logic" value="OR"> 任一条件满足 (OR)
                </label>
            </div>

            <div id="rulesPreview" class="rules-preview" style="display: none;"></div>

            <input type="hidden" name="invalidation_rules" id="invalidationRulesInput">

            <button type="submit" class="btn-add" style="width: 100%;">创建信号</button>
        </form>
    </div>

    <!-- 信号列表 -->
    <div class="signal-list">
        {% for signal in signals %}
        <div class="signal-card status-{{ signal.status }}" data-id="{{ signal.id }}">
            <div class="signal-main">
                <div class="signal-title">
                    <span class="signal-code">{{ signal.asset_code }}</span>
                    <span class="signal-name">{{ signal.asset_name }}</span>
                    <span class="signal-tag">{{ signal.asset_class }}</span>
                    <span class="status-badge status-{{ signal.status }}">
                        {% if signal.status == 'pending' %}待审核
                        {% elif signal.status == 'approved' %}已通过
                        {% elif signal.status == 'rejected' %}已拒绝
                        {% elif signal.status == 'invalidated' %}已证伪{% endif %}
                    </span>
                </div>
                <div class="signal-desc">{{ signal.logic_desc }}</div>
                <div class="signal-rules">
                    <span class="label">证伪:</span> {{ signal.invalidation_logic }}
                </div>
                <div class="signal-meta">
                    <span>📅 {{ signal.created_at|date:"Y-m-d" }}</span>
                    <span>🎯 目标: {{ signal.target_regime }}</span>
                    {% if signal.invalidated_at %}
                    <span style="color: #ef4444;">⚠️ 证伪于 {{ signal.invalidated_at|date:"Y-m-d H:i" }}</span>
                    {% endif %}
                </div>
                {% if signal.rejection_reason %}
                <div style="font-size: 12px; color: #ef4444; margin-top: 8px;">🚫 {{ signal.rejection_reason }}</div>
                {% endif %}
            </div>
            <div class="signal-actions">
                {% if signal.status == 'pending' or signal.status == 'rejected' %}
                <button class="action-btn approve" onclick="approveSignal({{ signal.id }})">✓</button>
                {% endif %}
                {% if signal.status == 'pending' or signal.status == 'approved' %}
                <button class="action-btn reject" onclick="rejectSignal({{ signal.id }})">✕</button>
                {% endif %}
                {% if signal.status == 'approved' %}
                <button class="action-btn check" onclick="checkSignal({{ signal.id }})">🔍</button>
                {% endif %}
                <button class="action-btn delete" onclick="deleteSignal({{ signal.id }})">🗑</button>
            </div>
        </div>
        {% endfor %}
    </div>

    {% if not signals %}
    <div class="empty-state">
        <div style="font-size: 48px; margin-bottom: 16px;">📊</div>
        <div>暂无信号，在上方创建第一个信号</div>
    </div>
    {% endif %}
</div>

<!-- Toast -->
<div id="toast" class="toast"></div>

<script>
// URL 配置
const API_URLS = {
    signalAiParseLogic: "{% url 'signal:ai_parse_logic' %}",
    signalCreate: "{% url 'signal:create' %}",
    signalApprove: "{% url 'signal:approve' %}",
    signalReject: "{% url 'signal:reject' %}",
    signalCheck: (id) => `{% url 'signal:check' 0 %}`.replace('0', id),
    signalDelete: (id) => `{% url 'signal:delete' 0 %}`.replace('0', id),
    signalBatchCheck: "{% url 'signal:batch_check' %}"
};

// 条件数据
let conditions = [];

// AI 生成规则
async function aiGenerate() {
    const input = document.getElementById('aiInput').value.trim();
    if (!input) {
        alert('请输入证伪条件描述');
        return;
    }

    try {
        const res = await fetch(API_URLS.signalAiParseLogic, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ text: input })
        });

        const data = await res.json();

        if (data.success) {
            // 清空现有条件
            conditions = data.conditions;

            // 设置逻辑
            const logicRadio = document.querySelector(`input[name="logic"][value="${data.logic}"]`);
            if (logicRadio) logicRadio.checked = true;

            renderConditions();
            updatePreview();

            // 显示结果
            const resultDiv = document.getElementById('aiResult');
            resultDiv.innerHTML = `
                <div class="ai-result-title">✅ AI 解析成功 (置信度: ${Math.round(data.confidence * 100)}%)</div>
                <div style="font-size: 13px; color: #64748b;">${data.explanation}</div>
                <div style="margin-top: 8px; font-size: 12px; color: #10b981;">
                    👇 条件已添加到下方列表，可以继续编辑或直接创建信号
                </div>
            `;
            resultDiv.classList.add('show');
            document.getElementById('aiSuggestions').style.display = 'none';
        } else {
            // 显示错误和建议
            const resultDiv = document.getElementById('aiResult');
            resultDiv.innerHTML = `<div style="color: #ef4444;">❌ ${data.error}</div>`;
            resultDiv.classList.add('show');

            if (data.suggestions && data.suggestions.length > 0) {
                const suggestDiv = document.getElementById('aiSuggestions');
                suggestDiv.innerHTML = `
                    <div class="ai-suggestions-title">💡 建议:</div>
                    <ul style="margin: 4px 0; padding-left: 16px;">
                        ${data.suggestions.map(s => `<li>${s}</li>`).join('')}
                    </ul>
                `;
                suggestDiv.style.display = 'block';
            }
        }
    } catch (e) {
        showToast('AI 服务异常: ' + e.message, 'error');
    }
}

function clearAiResult() {
    document.getElementById('aiInput').value = '';
    document.getElementById('aiResult').classList.remove('show');
    document.getElementById('aiSuggestions').style.display = 'none';
}

// 添加条件
function addCondition() {
    const indicator = document.getElementById('indicatorSelect').value;
    const condition = document.getElementById('conditionSelect').value;
    const threshold = document.getElementById('thresholdInput').value;

    if (!indicator || !threshold) {
        alert('请选择指标并输入阈值');
        return;
    }

    conditions.push({ indicator, condition, threshold: parseFloat(threshold) });
    renderConditions();
    updatePreview();

    document.getElementById('indicatorSelect').value = '';
    document.getElementById('thresholdInput').value = '';
}

// 渲染条件列表
function renderConditions() {
    const list = document.getElementById('conditionsList');
    const opMap = { lt: '<', lte: '≤', gt: '>', gte: '≥', eq: '=' };

    list.innerHTML = conditions.map((c, i) => `
        <div class="condition-item">
            <span class="condition-text">${c.indicator} ${opMap[c.condition]} ${c.threshold}</span>
            <button type="button" class="btn-remove" onclick="removeCondition(${i})">删除</button>
        </div>
    `).join('');
}

function removeCondition(index) {
    conditions.splice(index, 1);
    renderConditions();
    updatePreview();
}

function updatePreview() {
    const preview = document.getElementById('rulesPreview');
    const logic = document.querySelector('input[name="logic"]:checked').value;

    if (conditions.length === 0) {
        preview.style.display = 'none';
        return;
    }

    const opMap = { lt: '<', lte: '≤', gt: '>', gte: '≥', eq: '=' };
    const logicText = logic === 'AND' ? ' 且 ' : ' 或 ';
    const text = conditions.map(c => `${c.indicator} ${opMap[c.condition]} ${c.threshold}`).join(logicText);

    preview.textContent = `📋 证伪规则: 当 ${text} 时自动证伪`;
    preview.style.display = 'block';
}

// 指标选择时自动填充阈值
document.getElementById('indicatorSelect').addEventListener('change', function() {
    const option = this.selectedOptions[0];
    const threshold = option.dataset.threshold;
    if (threshold) {
        document.getElementById('thresholdInput').value = threshold;
    }
});

// 表单提交
document.getElementById('createForm').addEventListener('submit', async function(e) {
    e.preventDefault();

    if (conditions.length === 0) {
        alert('请至少添加一个证伪条件');
        return;
    }

    const formData = new FormData(this);
    const logic = document.querySelector('input[name="logic"]:checked').value;

    formData.set('invalidation_rules', JSON.stringify({ conditions, logic }));

    const res = await fetch(API_URLS.signalCreate, { method: 'POST', body: formData });
    const data = await res.json();

    if (data.success) {
        showToast(data.is_approved ? '✓ 创建成功' : '⚠️ 创建但未通过准入');
        this.reset();
        conditions = [];
        renderConditions();
        updatePreview();
        clearAiResult();
        location.reload();
    } else {
        showToast('❌ ' + (data.error || '创建失败'), 'error');
    }
});

function showToast(msg, type = 'success') {
    const toast = document.getElementById('toast');
    toast.textContent = msg;
    toast.className = `toast ${type} show`;
    setTimeout(() => toast.classList.remove('show'), 3000);
}

async function approveSignal(id) {
    const formData = new FormData();
    formData.append('signal_id', id);
    const res = await fetch(API_URLS.signalApprove, { method: 'POST', body: formData });
    const data = await res.json();
    if (data.success) {
        showToast('✓ 已批准');
        location.reload();
    }
}

async function rejectSignal(id) {
    const reason = await window.uiPrompt('拒绝原因', '', {
        title: '拒绝信号',
        required: true,
        requiredMessage: '请填写拒绝原因',
        placeholder: '请输入拒绝原因'
    });
    if (!reason) return;
    const formData = new FormData();
    formData.append('signal_id', id);
    formData.append('reason', reason);
    const res = await fetch(API_URLS.signalReject, { method: 'POST', body: formData });
    const data = await res.json();
    if (data.success) {
        showToast('✕ 已拒绝');
        location.reload();
    }
}

async function checkSignal(id) {
    const res = await fetch(API_URLS.signalCheck(id), { method: 'POST' });
    const data = await res.json();

    if (data.success) {
        if (data.is_invalidated) {
            showToast(`⚠️ 信号已证伪：${data.reason}`, 'warning');
            location.reload();
        } else {
            showToast(`✓ 检查完成：${data.reason}`, 'success');
        }
    }
}

async function deleteSignal(id) {
    if (!await window.uiConfirm('确认删除该信号？', { title: '删除信号', icon: 'warning' })) return;
    const res = await fetch(API_URLS.signalDelete(id), { method: 'DELETE' });
    const data = await res.json();
    if (data.success) {
        showToast('🗑 已删除');
        document.querySelector(`[data-id="${id}"]`).remove();
    }
}

async function batchCheck() {
    const res = await fetch(API_URLS.signalBatchCheck, { method: 'POST' });
    const data = await res.json();

    if (data.success) {
        showToast(`🔄 检查完成: ${data.checked} 个信号，${data.invalidated} 个被证伪`);
        if (data.invalidated > 0) {
            location.reload();
        }
    }
}
</script>
{% endblock %}
