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

{% block title %}我的账户 - AgomTradePro{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'css/account.css' %}">
<!-- Chart.js -->
<script src="{% static 'vendor/chartjs/chart.umd.min.js' %}"></script>
{% endblock %}

{% block content %}
<div class="account-container">
    <div class="account-header">
        <h1>我的账户</h1>
        <p class="subtitle">管理您的投资组合和持仓</p>
    </div>

    <!-- 账户概览 -->
    <section class="account-section">
        <h2 class="section-title">账户概览</h2>
        <div class="account-stats">
            <div class="stat-card">
                <span class="stat-label">用户名</span>
                <span class="stat-value">{{ profile.display_name|default:user.username }}</span>
            </div>
            <div class="stat-card">
                <span class="stat-label">当前总资产</span>
                <span class="stat-value">¥{{ total_assets|floatformat:2|default:"0.00" }}</span>
                {% if not profile.real_account %}
                <span class="stat-hint">💡 创建实仓后可记录真实投资</span>
                {% endif %}
            </div>
            <div class="stat-card">
                <span class="stat-label">风险偏好</span>
                <span class="stat-value">{{ profile.get_risk_tolerance_display }}</span>
            </div>
            <div class="stat-card">
                <span class="stat-label">投资组合</span>
                <span class="stat-value">{{ portfolios.count }} 个</span>
            </div>
        </div>
        {% if not investment_accounts and total_assets > 0 %}
        <div class="info-notice">
            <span class="notice-icon">ℹ️</span>
            <span class="notice-text">当前显示的是旧系统的资产数据。创建投资组合后，账户概览将切换到新系统显示。</span>
        </div>
        {% endif %}
    </section>

    <!-- 投资组合概览（⭐ 重构：支持多个实仓/模拟仓） -->
    <section class="account-section">
        <h2 class="section-title">我的投资组合</h2>
        <div class="account-stats">
            {% if investment_accounts %}
                <!-- 实仓列表 -->
                {% for account in investment_accounts %}
                {% if account.account_type == 'real' %}
                <div class="stat-card stat-card-real">
                    <span class="stat-label">实仓</span>
                    <a href="{% url 'simulated_trading:my-account-detail' account.id %}" class="stat-value-link">
                        {{ account.account_name }}
                    </a>
                    <span class="stat-sub">
                        总资产: ¥{{ account.total_value|floatformat:2 }}
                    </span>
                    <span class="stat-sub {% if account.total_return >= 0 %}positive{% else %}negative{% endif %}">
                        收益率: {{ account.total_return|floatformat:2 }}%
                    </span>
                </div>
                {% endif %}
                {% endfor %}

                <!-- 模拟仓列表 -->
                {% for account in investment_accounts %}
                {% if account.account_type == 'simulated' %}
                <div class="stat-card stat-card-simulated">
                    <span class="stat-label">模拟仓</span>
                    <a href="{% url 'simulated_trading:my-account-detail' account.id %}" class="stat-value-link">
                        {{ account.account_name }}
                    </a>
                    <span class="stat-sub">
                        总资产: ¥{{ account.total_value|floatformat:2 }}
                    </span>
                    <span class="stat-sub {% if account.total_return >= 0 %}positive{% else %}negative{% endif %}">
                        收益率: {{ account.total_return|floatformat:2 }}%
                    </span>
                </div>
                {% endif %}
                {% endfor %}

                <!-- 创建新投资组合按钮 -->
                <div class="stat-card stat-card-empty">
                    <span class="stat-label">添加</span>
                    <span class="stat-value-empty">创建新投资组合</span>
                    <div class="mt-2">
                        <a href="{% url 'simulated_trading:my-accounts' %}" class="btn btn-create-real">
                            + 创建投资组合
                        </a>
                    </div>
                </div>
            {% else %}
                <!-- 未创建任何投资组合 -->
                <div class="stat-card stat-card-empty">
                    <span class="stat-label">实仓</span>
                    <span class="stat-value-empty">未创建</span>
                    <div class="mt-2">
                        <a href="{% url 'simulated_trading:my-accounts' %}" class="btn btn-create-real">
                            + 创建实仓
                        </a>
                    </div>
                </div>
                <div class="stat-card stat-card-empty">
                    <span class="stat-label">模拟仓</span>
                    <span class="stat-value-empty">未创建</span>
                    <div class="mt-2">
                        <a href="{% url 'simulated_trading:my-accounts' %}" class="btn btn-create-simulated">
                            + 创建模拟仓
                        </a>
                    </div>
                </div>
            {% endif %}
        </div>
        <div class="mt-3">
            <a href="{% url 'simulated_trading:my-accounts' %}" class="btn btn-primary btn-sm">
                管理我的投资组合
            </a>
        </div>
    </section>

    <!-- 我的持仓 -->
    <section id="positions" class="account-section">
        <h2 class="section-title">我的持仓</h2>
        {% for portfolio in portfolios %}
        {% regroup portfolio.positions.all by is_closed as closed_groups %}
        {% for group in closed_groups %}
        {% if group.grouper == False %}
        <h3 class="subsection-title">{{ portfolio.name }}</h3>
        <table class="table">
            <thead>
                <tr>
                    <th>资产代码</th>
                    <th>资产名称</th>
                    <th>数量</th>
                    <th>成本价</th>
                    <th>现价</th>
                    <th>市值</th>
                    <th>盈亏</th>
                    <th>盈亏%</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for position in group.list %}
                <tr>
                    <td><strong>{{ position.asset_code }}</strong></td>
                    <td>-</td>
                    <td>{{ position.shares|floatformat:2 }}</td>
                    <td>¥{{ position.avg_cost|floatformat:2 }}</td>
                    <td>{% if position.current_price %}¥{{ position.current_price|floatformat:2 }}{% else %}-{% endif %}</td>
                    <td>¥{{ position.market_value|floatformat:2 }}</td>
                    <td class="{% if position.unrealized_pnl >= 0 %}positive{% else %}negative{% endif %}">
                        ¥{{ position.unrealized_pnl|floatformat:2 }}
                    </td>
                    <td class="{% if position.unrealized_pnl_pct >= 0 %}positive{% else %}negative{% endif %}">
                        {{ position.unrealized_pnl_pct|floatformat:2 }}%
                    </td>
                    <td>
                        <a href="#" class="btn btn-sm btn-secondary">平仓</a>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        <br>
        {% endif %}
        {% endfor %}
        {% endfor %}

        {% if portfolios.0.positions.count == 0 %}
        <div class="empty-state">
            <p>暂无持仓</p>
            <p class="empty-hint">通过<a href="/signal/manage/">创建投资信号</a>或<a href="/backtest/">回测引擎</a>开始投资</p>
        </div>
        {% endif %}
    </section>

    <!-- 波动率分析 -->
    <section class="account-section">
        <h2 class="section-title">波动率分析</h2>
        <div class="volatility-overview">
            <div class="volatility-stat">
                <span class="volatility-label">30天波动率</span>
                <span class="volatility-value" id="vol30d">-</span>
            </div>
            <div class="volatility-stat">
                <span class="volatility-label">60天波动率</span>
                <span class="volatility-value" id="vol60d">-</span>
            </div>
            <div class="volatility-stat">
                <span class="volatility-label">90天波动率</span>
                <span class="volatility-value" id="vol90d">-</span>
            </div>
            <div class="volatility-stat">
                <span class="volatility-label">目标波动率</span>
                <span class="volatility-value volatility-target" id="volTarget">-</span>
            </div>
        </div>
        <div class="volatility-chart-container">
            <canvas id="volatilityChart"></canvas>
        </div>
        <div id="volatilityAlert" class="volatility-alert" style="display: none;"></div>
    </section>

    <!-- 我的投资组合 -->
    <section class="account-section">
        <h2 class="section-title">我的投资组合</h2>
        {% if portfolios %}
        <div class="portfolio-list">
            {% for portfolio in portfolios %}
            <div class="portfolio-card {% if portfolio.is_active %}active{% endif %}">
                <div class="portfolio-header">
                    <h3>{{ portfolio.name }}</h3>
                    {% if portfolio.is_active %}
                    <span class="badge badge-success">活跃</span>
                    {% else %}
                    <span class="badge badge-secondary">已归档</span>
                    {% endif %}
                </div>
                <div class="portfolio-stats">
                    <span>持仓数: {{ portfolio.positions.count }}</span>
                    <span>市值: ¥{{ portfolio.total_value|floatformat:2|default:"0.00" }}</span>
                </div>
            </div>
            {% endfor %}
        </div>
        {% else %}
        <p class="empty-state">暂无投资组合</p>
        {% endif %}
    </section>

    <!-- 快捷操作 -->
    <section class="account-section">
        <h2 class="section-title">快捷操作</h2>
        <div class="action-buttons">
            <a href="/signal/create/" class="btn btn-primary">创建投资信号</a>
            <a href="/backtest/create/" class="btn btn-secondary">新建回测</a>
            <a href="{% url 'account:mcp_guide' %}" class="btn btn-secondary">MCP 接入说明</a>
            <a href="/account/settings/" class="btn btn-secondary">账户设置</a>
        </div>
    </section>
</div>

<style>
.account-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 24px;
}

.account-header {
    margin-bottom: 24px;
}

.account-header h1 {
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 4px;
}

.subtitle {
    color: #54595D;
    font-size: 14px;
}

.account-section {
    background: #FFFFFF;
    border: 1px solid #E0E0E0;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 24px;
}

.section-title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 16px;
}

.subsection-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 12px;
    margin-top: 16px;
    color: #54595D;
}

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

.stat-card {
    background: #F8F9FA;
    padding: 16px;
    border-radius: 4px;
    text-align: center;
}

.stat-label {
    display: block;
    font-size: 12px;
    color: #54595D;
    margin-bottom: 8px;
}

.stat-value {
    display: block;
    font-size: 20px;
    font-weight: 600;
}

.stat-hint {
    display: block;
    font-size: 11px;
    color: #888;
    margin-top: 6px;
    font-style: italic;
}

.info-notice {
    display: flex;
    align-items: center;
    gap: 10px;
    background: #fff8e1;
    border: 1px solid #ffe082;
    border-radius: 6px;
    padding: 12px 16px;
    margin-top: 16px;
}

.notice-icon {
    font-size: 18px;
    flex-shrink: 0;
}

.notice-text {
    font-size: 13px;
    color: #5d4037;
}

.table {
    width: 100%;
    border-collapse: collapse;
}

.table thead {
    background: #F8F9FA;
}

.table th {
    padding: 12px;
    text-align: left;
    font-weight: 600;
    font-size: 12px;
    border-bottom: 1px solid #E0E0E0;
}

.table td {
    padding: 12px;
    font-size: 14px;
    border-bottom: 1px solid #E0E0E0;
}

.positive { color: var(--color-rise); }
.negative { color: var(--color-fall); }

.portfolio-list {
    display: grid;
    gap: 12px;
}

.portfolio-card {
    border: 1px solid #E0E0E0;
    border-radius: 4px;
    padding: 16px;
    transition: all 0.2s;
}

.portfolio-card.active {
    border-color: #36C;
    background: #F8F9FA;
}

.portfolio-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.portfolio-header h3 {
    font-size: 16px;
    font-weight: 600;
    margin: 0;
}

.badge {
    padding: 2px 8px;
    border-radius: 2px;
    font-size: 12px;
    font-weight: 500;
}

.badge-success { background: #D5FBDD; color: #14866D; }
.badge-secondary { background: #E0E0E0; color: #54595D; }

.portfolio-stats {
    display: flex;
    gap: 16px;
    font-size: 14px;
    color: #54595D;
}

.action-buttons {
    display: flex;
    gap: 12px;
}

.btn {
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 14px;
    text-decoration: none;
    display: inline-block;
}

.btn-primary {
    background: #36C;
    color: white;
    border: none;
}

.btn-secondary {
    background: #F8F9FA;
    color: #202122;
    border: 1px solid #E0E0E0;
}

.btn-sm {
    padding: 4px 8px;
    font-size: 12px;
}

.empty-state {
    text-align: center;
    padding: 40px;
    color: #54595D;
}

.empty-state a {
    color: #36C;
    text-decoration: none;
}

.empty-state a:hover {
    text-decoration: underline;
}

/* 波动率分析样式 */
.volatility-overview {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 20px;
}

.volatility-stat {
    background: #F8F9FA;
    padding: 16px;
    border-radius: 4px;
    text-align: center;
}

.volatility-label {
    display: block;
    font-size: 12px;
    color: #54595D;
    margin-bottom: 8px;
}

.volatility-value {
    display: block;
    font-size: 18px;
    font-weight: 600;
    color: #202122;
}

.volatility-value.volatility-target {
    color: #36C;
}

.volatility-chart-container {
    position: relative;
    height: 300px;
    margin: 20px 0;
}

.volatility-alert {
    padding: 12px 16px;
    border-radius: 4px;
    margin-top: 16px;
    font-size: 14px;
}

.volatility-alert.warning {
    background: #fef3c7;
    color: #92400e;
    border-left: 4px solid #f59e0b;
}

.volatility-alert.danger {
    background: #fee7e7;
    color: #991b1b;
    border-left: 4px solid #ef4444;
}

.volatility-alert.success {
    background: #dcfce7;
    color: #166534;
    border-left: 4px solid #22c55e;
}

/* 模拟仓概览样式（新增） */
.stat-card-real {
    background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
    border: 1px solid #81c784;
}

.stat-card-simulated {
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
    border: 1px solid #64b5f6;
}

.stat-card-empty {
    background: #f5f5f5;
    border: 1px solid #e0e0e0;
}

.stat-value-link {
    display: block;
    font-size: 18px;
    font-weight: 600;
    color: #36C;
    text-decoration: none;
    margin-bottom: 4px;
}

.stat-value-link:hover {
    text-decoration: underline;
}

.stat-value-empty {
    display: block;
    font-size: 16px;
    font-weight: 500;
    color: #999;
    margin-bottom: 4px;
}

.stat-sub {
    display: block;
    font-size: 12px;
    color: #666;
    margin-top: 4px;
}

.mt-3 {
    margin-top: 12px;
}

.mt-2 {
    margin-top: 8px;
}

/* 创建按钮样式 */
.btn-create-real {
    display: inline-block;
    padding: 6px 12px;
    background: linear-gradient(135deg, #4caf50 0%, #66bb6a 100%);
    color: white;
    text-decoration: none;
    border-radius: 4px;
    font-size: 13px;
    font-weight: 500;
    transition: all 0.2s;
    border: none;
}

.btn-create-real:hover {
    background: linear-gradient(135deg, #43a047 0%, #5cb860 100%);
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.btn-create-simulated {
    display: inline-block;
    padding: 6px 12px;
    background: linear-gradient(135deg, #2196f3 0%, #42a5f5 100%);
    color: white;
    text-decoration: none;
    border-radius: 4px;
    font-size: 13px;
    font-weight: 500;
    transition: all 0.2s;
    border: none;
}

.btn-create-simulated:hover {
    background: linear-gradient(135deg, #1e88e5 0%, #3d9bfd 100%);
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(33, 150, 243, 0.3);
}
</style>

<script>
async function loadVolatilityData() {
    try {
                const response = await fetch('{% url "api_account:volatility" %}');
        const result = await response.json();

        if (!result.success) {
            console.error('获取波动率数据失败:', result.error);
            return;
        }

        const data = result.data;

        // 更新当前波动率显示
        document.getElementById('vol30d').textContent = (data.current.volatility_30d * 100).toFixed(2) + '%';
        document.getElementById('vol60d').textContent = (data.current.volatility_60d * 100).toFixed(2) + '%';
        document.getElementById('vol90d').textContent = (data.current.volatility_90d * 100).toFixed(2) + '%';
        document.getElementById('volTarget').textContent = (data.current.target * 100).toFixed(2) + '%';

        // 显示调整建议
        const alertBox = document.getElementById('volatilityAlert');
        if (data.adjustment && data.adjustment.should_reduce) {
            alertBox.textContent = '⚠️ ' + data.adjustment.reduction_reason;
            alertBox.className = 'volatility-alert warning';
            alertBox.style.display = 'block';
        } else {
            alertBox.style.display = 'none';
        }

        // 渲染图表
        renderVolatilityChart(data.history, data.current.target);

    } catch (error) {
        console.error('加载波动率数据失败:', error);
    }
}

function renderVolatilityChart(history, targetVolatility) {
    const ctx = document.getElementById('volatilityChart');
    if (!ctx) return;

    // 准备数据
    const labels = history.map(h => h.date).filter(d => d !== null);
    const data30d = history.map(h => h.rolling_volatility_30d ? h.rolling_volatility_30d * 100 : null);
    const annualized = history.map(h => h.annualized_volatility ? h.annualized_volatility * 100 : null);

    // 目标线
    const targetLine = Array(labels.length).fill(targetVolatility * 100);
    const targetUpper = Array(labels.length).fill(targetVolatility * 100 * 1.2);
    const targetLower = Array(labels.length).fill(targetVolatility * 100 * 0.8);

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: '年化波动率',
                    data: annualized,
                    borderColor: '#36C',
                    backgroundColor: 'rgba(51, 102, 204, 0.1)',
                    fill: true,
                    tension: 0.3,
                    pointRadius: 2,
                },
                {
                    label: '30天滚动波动率',
                    data: data30d,
                    borderColor: '#22c55e',
                    backgroundColor: 'transparent',
                    borderDash: [5, 5],
                    tension: 0.3,
                    pointRadius: 0,
                },
                {
                    label: '目标波动率',
                    data: targetLine,
                    borderColor: '#f59e0b',
                    backgroundColor: 'transparent',
                    borderDash: [10, 5],
                    pointRadius: 0,
                },
                {
                    label: '目标上限 (+20%)',
                    data: targetUpper,
                    borderColor: 'transparent',
                    backgroundColor: 'rgba(239, 68, 68, 0.05)',
                    fill: '+1',
                    pointRadius: 0,
                },
                {
                    label: '目标下限 (-20%)',
                    data: targetLower,
                    borderColor: 'transparent',
                    backgroundColor: 'rgba(239, 68, 68, 0.05)',
                    fill: false,
                    pointRadius: 0,
                },
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false,
            },
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        boxWidth: 12,
                        padding: 15,
                        font: { size: 11 }
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return context.dataset.label + ': ' + context.parsed.y.toFixed(2) + '%';
                        }
                    }
                }
            },
            scales: {
                x: {
                    display: true,
                    title: {
                        display: true,
                        text: '日期',
                        font: { size: 11 }
                    },
                    ticks: {
                        font: { size: 10 },
                        maxTicksLimit: 10
                    }
                },
                y: {
                    display: true,
                    title: {
                        display: true,
                        text: '波动率 (%)',
                        font: { size: 11 }
                    },
                    ticks: {
                        font: { size: 10 },
                        callback: function(value) {
                            return value.toFixed(1) + '%';
                        }
                    }
                }
            }
        }
    });
}

// 页面加载时获取数据
document.addEventListener('DOMContentLoaded', function() {
    loadVolatilityData();
});
</script>

<!-- Floating Widget Config -->
<script>
    // Load floating widget config from JSON file
    fetch('{% static "widgets/configs/account_widget.json" %}')
        .then(response => response.json())
        .then(config => {
            window.floatingWidgetConfig = config;
            // Trigger initialization manually since DOM is already loaded
            if (window.initFloatingWidget) {
                window.initFloatingWidget(config);
            }
        })
        .catch(err => console.error('Failed to load widget config:', err));
</script>

{% endblock %}
