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

{% block title %}策略管理 - AgomTradePro{% endblock %}

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

{% block content %}
<div class="strategy-container">
    <!-- 头部 -->
    <div class=”strategy-header”>
        <h1>📊 策略管理</h1>
        <button class=”btn-create” onclick=”location.href='{% url 'strategy:create' %}'”>
            <i class=”bi bi-plus-lg”></i> 创建新策略
        </button>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card total">
            <div class="stat-value">{{ stats.total }}</div>
            <div class="stat-label">总策略数</div>
        </div>
        <div class="stat-card active">
            <div class="stat-value">{{ stats.active }}</div>
            <div class="stat-label">激活中</div>
        </div>
        <div class="stat-card inactive">
            <div class="stat-value">{{ stats.inactive }}</div>
            <div class="stat-label">已停用</div>
        </div>
        <div class="stat-card rule">
            <div class="stat-value">{{ stats.by_type.rule_based }}</div>
            <div class="stat-label">规则策略</div>
        </div>
        <div class="stat-card script">
            <div class="stat-value">{{ stats.by_type.script_based }}</div>
            <div class="stat-label">脚本策略</div>
        </div>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
        <select id="filterType" class="filter-select" onchange="filterStrategies()">
            <option value="">所有类型</option>
            <option value="rule_based">规则驱动</option>
            <option value="script_based">脚本驱动</option>
            <option value="hybrid">混合模式</option>
            <option value="ai_driven">AI驱动</option>
        </select>
        <select id="filterStatus" class="filter-select" onchange="filterStrategies()">
            <option value="">所有状态</option>
            <option value="active">激活</option>
            <option value="inactive">停用</option>
        </select>
        <input type="text" id="searchInput" class="filter-select" placeholder="搜索策略名称..." style="flex: 1;" oninput="filterStrategies()">
    </div>

    <!-- 策略列表 -->
    <div class="strategy-grid" id="strategyGrid">
        {% for strategy in strategies %}
        <div class="strategy-card" data-type="{{ strategy.strategy_type }}" data-status="{% if strategy.is_active %}active{% else %}inactive{% endif %}" data-name="{{ strategy.name|lower }}">
            <div class="card-header">
                <div>
                    <div class="card-title">{{ strategy.name }}</div>
                    <div class="card-meta">
                        <span class="badge badge-type {{ strategy.strategy_type }}">
                            {% if strategy.strategy_type == 'rule_based' %}规则驱动
                            {% elif strategy.strategy_type == 'script_based' %}脚本驱动
                            {% elif strategy.strategy_type == 'hybrid' %}混合模式
                            {% elif strategy.strategy_type == 'ai_driven' %}AI驱动{% endif %}
                        </span>
                        <span class="badge badge-version">v{{ strategy.version }}</span>
                        <span class="badge badge-status {% if not strategy.is_active %}inactive{% endif %}">
                            {% if strategy.is_active %}激活中{% else %}已停用{% endif %}
                        </span>
                    </div>
                </div>
                <div class="card-actions">
                    <button class="btn-action" onclick="toggleStatus({{ strategy.id }}, {% if strategy.is_active %}false{% else %}true{% endif %})">
                        {% if strategy.is_active %}停用{% else %}激活{% endif %}
                    </button>
                </div>
            </div>

            <div class="card-body">
                <div class="card-desc">{{ strategy.description|default:"暂无描述" }}</div>

                <div class="card-stats">
                    <div class="card-stat">
                        <div class="card-stat-value">{{ strategy.rule_count }}</div>
                        <div class="card-stat-label">规则数</div>
                    </div>
                    <div class="card-stat">
                        <div class="card-stat-value">{{ strategy.execution_count }}</div>
                        <div class="card-stat-label">执行次数</div>
                    </div>
                    <div class="card-stat">
                        <div class="card-stat-value">{{ strategy.portfolio_count }}</div>
                        <div class="card-stat-label">绑定账户</div>
                    </div>
                </div>

                {% if strategy.rule_summary %}
                <div class="card-rules">
                    <strong>规则:</strong>
                    {% for rule in strategy.rule_summary %}
                    <div class="rule-item">{{ rule.rule_name }}</div>
                    {% endfor %}
                </div>
                {% endif %}
            </div>

            <div class="card-footer">
                <div class="card-date">
                    <i class="bi bi-clock"></i> {{ strategy.updated_at|date:"Y-m-d H:i" }}
                </div>
                <div class="card-actions">
                    <button class="btn-action" onclick="location.href='{% url 'strategy:detail' strategy.id %}'">
                        <i class="bi bi-eye"></i> 查看
                    </button>
                    <button class="btn-action" onclick="location.href='{% url 'strategy:edit' strategy.id %}'">
                        <i class="bi bi-pencil"></i> 编辑
                    </button>
                    <button class="btn-action" onclick="location.href='{% url 'strategy:detail' strategy.id %}#tab-test'">
                        <i class="bi bi-speedometer2"></i> 评估
                    </button>
                    <button class="btn-action danger" onclick="deleteStrategy({{ strategy.id }}, '{{ strategy.name }}')">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>

    {% if not strategies %}
    <div class="empty-state">
        <div class="empty-icon">📊</div>
        <div class="empty-text">暂无策略</div>
        <div class="empty-hint">点击上方按钮创建您的第一个策略</div>
    </div>
    {% endif %}
</div>

<script>
// 筛选策略
function filterStrategies() {
    const typeFilter = document.getElementById('filterType').value;
    const statusFilter = document.getElementById('filterStatus').value;
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();

    const cards = document.querySelectorAll('.strategy-card');
    cards.forEach(card => {
        const type = card.dataset.type;
        const status = card.dataset.status;
        const name = card.dataset.name;

        const typeMatch = !typeFilter || type === typeFilter;
        const statusMatch = !statusFilter || status === statusFilter;
        const nameMatch = !searchTerm || name.includes(searchTerm);

        card.style.display = typeMatch && statusMatch && nameMatch ? 'block' : 'none';
    });
}

// 切换状态
async function toggleStatus(id, activate) {
    const action = activate ? '激活' : '停用';
    if (!confirm(`确认${action}此策略？`)) return;

    const formData = new FormData();
    formData.append('action', activate ? 'activate' : 'deactivate');

    try {
        const res = await fetch(`/strategy/${id}/toggle-status/`, {
            method: 'POST',
            headers: {'X-CSRFToken': getCookie('csrftoken')},
            body: formData
        });
        const data = await res.json();

        if (data.success) {
            showToast(`${action}成功`);
            location.reload();
        } else {
            showToast(`${action}失败: ${data.error}`, 'error');
        }
    } catch (e) {
        showToast(`操作失败: ${e.message}`, 'error');
    }
}

// 删除策略
async function deleteStrategy(id, name) {
    if (!confirm(`确认删除策略 "${name}"？\n\n此操作不可恢复！`)) return;

    try {
        const res = await fetch(`/api/strategy/strategies/${id}/`, {
            method: 'DELETE',
            headers: {'X-CSRFToken': getCookie('csrftoken')}
        });
        if (res.ok) {
            showToast('删除成功');
            location.reload();
        } else {
            const data = await res.json();
            showToast(`删除失败: ${data.error}`, 'error');
        }
    } catch (e) {
        showToast(`删除失败: ${e.message}`, 'error');
    }
}

// Toast 提示
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;
    toast.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        padding: 12px 20px;
        background: ${type === 'success' ? '#10b981' : '#ef4444'};
        color: white;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 9999;
    `;
    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateY(10px)';
        toast.style.transition = 'all 0.3s';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}
</script>
{% endblock %}
