{% extends "base.html" %}

{% block title %}编辑策略 - {{ strategy.name }} - AgomTradePro{% endblock %}

{% block content %}
<style>
.strategy-create-container { max-width: 1200px; margin: 0 auto; padding: 20px; }
.page-header { margin-bottom: 24px; }
.page-title { font-size: 28px; margin: 0 0 8px 0; }
.page-subtitle { color: #64748b; font-size: 14px; }

.form-section { background: white; border: 1px solid #e2e8f0; border-radius: 12px; margin-bottom: 20px; overflow: hidden; }
.section-header { padding: 20px; background: #f8fafc; border-bottom: 1px solid #e2e8f0; }
.section-title { font-size: 18px; font-weight: 600; margin: 0; }
.section-body { padding: 24px; }

.form-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; }
.form-group { margin-bottom: 16px; }
.form-group.full { grid-column: span 2; }
.form-label { display: block; font-size: 14px; font-weight: 500; color: #334155; margin-bottom: 8px; }
.form-input, .form-select, .form-textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid #cbd5e1;
    border-radius: 8px;
    font-size: 14px;
    transition: border-color 0.2s;
}
.form-input:focus, .form-select:focus, .form-textarea:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-textarea { min-height: 100px; resize: vertical; }
.form-hint { font-size: 12px; color: #94a3b8; margin-top: 4px; }

.type-selector { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }
.type-card {
    padding: 16px;
    border: 2px solid #e2e8f0;
    border-radius: 8px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s;
}
.type-card:hover { border-color: #667eea; background: #f8fafc; }
.type-card.selected { border-color: #667eea; background: #eff6ff; }
.type-card input { display: none; }
.type-icon { font-size: 32px; margin-bottom: 8px; }
.type-name { font-size: 14px; font-weight: 600; color: #334155; }
.type-desc { font-size: 11px; color: #94a3b8; margin-top: 4px; }
.type-card.disabled { opacity: 0.5; cursor: not-allowed; }

.risk-params { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; }

.btn-primary {
    padding: 12px 32px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
}
.btn-primary:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4); }

.btn-secondary {
    padding: 12px 32px;
    background: white;
    color: #64748b;
    border: 1px solid #cbd5e1;
    border-radius: 8px;
    font-size: 16px;
    cursor: pointer;
}
.btn-secondary:hover { background: #f8fafc; }

.actions { display: flex; justify-content: space-between; align-items: center; margin-top: 24px; }

#rulesEditor { display: none; }
#scriptEditor { display: none; }
#aiEditor { display: none; }
</style>

<div class="strategy-create-container">
    <!-- 页面头部 -->
    <div class="page-header">
        <h1 class="page-title">编辑策略</h1>
        <div class="page-subtitle">{{ strategy.name }}</div>
    </div>

    <form id="strategyForm" onsubmit="return false;">
        <!-- 基本信息 -->
        <div class="form-section">
            <div class="section-header">
                <h2 class="section-title">基本信息</h2>
            </div>
            <div class="section-body">
                <div class="form-grid">
                    <div class="form-group full">
                        <label class="form-label">策略名称</label>
                        <input type="text" name="name" class="form-input" value="{{ strategy.name }}" required>
                    </div>

                    <div class="form-group full">
                        <label class="form-label">策略类型</label>
                        <div class="type-selector">
                            <label class="type-card" onclick="selectType('rule_based')">
                                <input type="radio" name="strategy_type" value="rule_based"
                                    {% if strategy.strategy_type == 'rule_based' %}checked{% endif %}>
                                <div class="type-icon"></div>
                                <div class="type-name">规则驱动</div>
                                <div class="type-desc">基于JSON规则</div>
                            </label>
                            <label class="type-card" onclick="selectType('script_based')">
                                <input type="radio" name="strategy_type" value="script_based"
                                    {% if strategy.strategy_type == 'script_based' %}checked{% endif %}>
                                <div class="type-icon"></div>
                                <div class="type-name">脚本驱动</div>
                                <div class="type-desc">Python脚本</div>
                            </label>
                            <label class="type-card" onclick="selectType('hybrid')">
                                <input type="radio" name="strategy_type" value="hybrid"
                                    {% if strategy.strategy_type == 'hybrid' %}checked{% endif %}>
                                <div class="type-icon"></div>
                                <div class="type-name">混合模式</div>
                                <div class="type-desc">规则+脚本</div>
                            </label>
                            <label class="type-card" onclick="selectType('ai_driven')">
                                <input type="radio" name="strategy_type" value="ai_driven"
                                    {% if strategy.strategy_type == 'ai_driven' %}checked{% endif %}>
                                <div class="type-icon"></div>
                                <div class="type-name">AI驱动</div>
                                <div class="type-desc">AI智能决策</div>
                            </label>
                        </div>
                        <div class="form-hint">注意：策略类型创建后不可修改</div>
                    </div>

                    <div class="form-group full">
                        <label class="form-label">策略描述</label>
                        <textarea name="description" class="form-textarea">{{ strategy.description }}</textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- 风控参数 -->
        <div class="form-section">
            <div class="section-header">
                <h2 class="section-title">风控参数</h2>
            </div>
            <div class="section-body">
                <div class="risk-params">
                    <div class="form-group">
                        <label class="form-label">单资产最大持仓</label>
                        <input type="number" name="max_position_pct" class="form-input" value="{{ strategy.max_position_pct }}" min="0" max="100" step="1">
                        <div class="form-hint">%</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">总持仓上限</label>
                        <input type="number" name="max_total_position_pct" class="form-input" value="{{ strategy.max_total_position_pct }}" min="0" max="100" step="1">
                        <div class="form-hint">%</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">止损比例</label>
                        <input type="number" name="stop_loss_pct" class="form-input" value="{{ strategy.stop_loss_pct|default:'' }}" min="0" max="100" step="1">
                        <div class="form-hint">%（可选）</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">版本号</label>
                        <input type="number" name="version" class="form-input" value="{{ strategy.version }}" min="1" readonly>
                        <div class="form-hint">保存后自动递增</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 仓位规则 -->
        <div class="form-section">
            <div class="section-header">
                <h2 class="section-title">仓位规则</h2>
            </div>
            <div class="section-body">
                {% include "strategy/components/position_rule_editor.html" %}
            </div>
        </div>

        <!-- 策略配置区域（根据类型动态显示） -->
        <div id="rulesEditor" class="form-section">
            <div class="section-header">
                <h2 class="section-title">规则配置</h2>
            </div>
            <div class="section-body">
                {% include "strategy/components/rule_editor.html" %}
            </div>
        </div>

        <div id="scriptEditor" class="form-section">
            <div class="section-header">
                <h2 class="section-title">脚本配置</h2>
            </div>
            <div class="section-body">
                {% include "strategy/components/script_editor.html" %}
            </div>
        </div>

        <div id="aiEditor" class="form-section">
            <div class="section-header">
                <h2 class="section-title">AI配置</h2>
            </div>
            <div class="section-body">
                {% include "strategy/components/ai_config_editor.html" %}
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="actions">
            <button type="button" class="btn-secondary" onclick="history.back()">取消</button>
            <button type="submit" class="btn-primary" onclick="updateStrategy()">保存修改</button>
        </div>
    </form>
</div>

<script>
// 策略类型禁用（不可修改）
const strategyType = '{{ strategy.strategy_type }}';

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 禁用策略类型选择
    document.querySelectorAll('.type-card').forEach(card => {
        card.classList.add('disabled');
    });

    // 显示对应的编辑器
    showEditorForType(strategyType);

    // 加载现有规则数据
    {% if strategy.strategy_type == 'rule_based' or strategy.strategy_type == 'hybrid' %}
    loadExistingRules();
    {% endif %}

    // 加载现有脚本代码
    {% if strategy.script_config %}
    loadExistingScript();
    {% endif %}
});

// 显示对应的编辑器
function showEditorForType(type) {
    if (type === 'rule_based' || type === 'hybrid') {
        document.getElementById('rulesEditor').style.display = 'block';
    }
    if (type === 'script_based' || type === 'hybrid') {
        document.getElementById('scriptEditor').style.display = 'block';
    }
    if (type === 'ai_driven') {
        document.getElementById('aiEditor').style.display = 'block';
    }

    // 选中对应的卡片
    document.querySelectorAll('.type-card').forEach(card => {
        const input = card.querySelector('input');
        if (input.value === type) {
            card.classList.add('selected');
        }
    });
}

// 加载现有规则
function loadExistingRules() {
    // 从后端获取规则数据
    fetch(`/api/strategy/strategies/{{ strategy.id }}/rules/`)
        .then(res => res.json())
        .then(rules => {
            if (Array.isArray(rules)) {
                // 填充规则编辑器
                window.existingRules = rules;
                // 如果有规则编辑器的初始化函数，调用它
                if (typeof initRulesEditor === 'function') {
                    initRulesEditor(rules);
                }
            }
        })
        .catch(e => console.error('加载规则失败:', e));
}

// 加载现有脚本
function loadExistingScript() {
    fetch(`/api/strategy/strategies/{{ strategy.id }}/script_config/`)
        .then(res => res.json())
        .then(config => {
            if (config.script_code && window.editor) {
                window.editor.setValue(config.script_code);
            }
        })
        .catch(e => console.error('加载脚本失败:', e));
}

// 更新策略
async function updateStrategy() {
    const form = document.getElementById('strategyForm');
    const formData = new FormData(form);

    // 验证
    const name = formData.get('name');
    if (!name) {
        showToast('请输入策略名称', 'error');
        return;
    }

    try {
        const res = await fetch('{% url "strategy:edit" strategy.id %}', {
            method: 'POST',
            headers: {'X-CSRFToken': getCookie('csrftoken')},
            body: formData
        });
        const data = await res.json();

        if (data.success) {
            showToast('策略更新成功');
            setTimeout(() => location.href = `/strategy/{{ strategy.id }}/`, 1500);
        } else {
            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 %}
