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

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

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

{% block content %}
<div class="account-container">
    <div class="account-header">
        <div class="header-title-row">
            <div>
                <h1>我的账户</h1>
                <p class="subtitle">统一管理您的投资账户，账户类型仅作为属性区分</p>
            </div>
            <div class="header-actions">
                <button onclick="showCreateModal()" class="btn btn-primary">+ 创建新账户</button>
            </div>
        </div>
    </div>

    <!-- 总资产统计 -->
    {% if accounts %}
    <section class="account-section">
        <h2 class="section-title">总资产统计</h2>
        <div class="total-assets">
            <div class="total-assets-value">¥{{ total_assets|floatformat:2 }}</div>
            <div class="total-assets-label">总资产</div>
        </div>
    </section>
    {% endif %}

    <!-- 账户列表 -->
    <section class="account-section">
        <div class="section-header-row">
            <h2 class="section-title">我的账户</h2>
            {% if accounts %}
            <div class="account-bulk-actions">
                <label class="bulk-select-all">
                    <input type="checkbox" id="selectAllAccounts" onchange="toggleSelectAllAccounts(this.checked)">
                    <span>全选</span>
                </label>
                <span class="bulk-selected-count" id="selectedAccountCount">已选择 0 个</span>
                <button type="button" class="btn btn-secondary" id="clearSelectionBtn" onclick="clearAccountSelection()" disabled>
                    清空选择
                </button>
                <button type="button" class="btn btn-danger" id="bulkDeleteBtn" onclick="deleteSelectedAccounts()" disabled>
                    批量删除
                </button>
            </div>
            {% endif %}
        </div>
        {% if accounts %}
        <div class="accounts-grid">
            {% for account in accounts %}
            <div class="account-card {% if account.account_type == 'real' %}account-real{% else %}account-simulated{% endif %}" data-account-id="{{ account.id }}">
                <div class="account-card-header">
                    <div class="account-card-heading">
                        <label class="account-select-checkbox" title="选择账户">
                            <input
                                type="checkbox"
                                class="account-select-input"
                                value="{{ account.id }}"
                                data-account-name="{{ account.account_name }}"
                                onchange="updateAccountSelectionState()"
                            >
                            <span></span>
                        </label>
                        <h3>{{ account.account_name }}</h3>
                    </div>
                    <span class="badge {% if account.account_type == 'real' %}badge-real{% else %}badge-simulated{% endif %}">
                        {% if account.account_type == 'real' %}实仓{% else %}模拟仓{% endif %}
                    </span>
                </div>
                <div class="account-card-body">
                    <div class="account-metric">
                        <span class="metric-label">总资产</span>
                        <span class="metric-value">¥{{ account.total_value|floatformat:2 }}</span>
                    </div>
                    <div class="account-metric">
                        <span class="metric-label">初始资金</span>
                        <span class="metric-value-sub">¥{{ account.initial_capital|floatformat:2 }}</span>
                    </div>
                    <div class="account-metric">
                        <span class="metric-label">当前现金</span>
                        <span class="metric-value-sub">¥{{ account.current_cash|floatformat:2 }}</span>
                    </div>
                    <div class="account-metric {% if account.total_return >= 0 %}positive{% else %}negative{% endif %}">
                        <span class="metric-label">收益率</span>
                        <span class="metric-value-return">
                            {% if account.total_return is None %}-{% else %}{{ account.total_return|floatformat:2 }}%{% endif %}
                        </span>
                    </div>
                    <div class="account-metric">
                        <span class="metric-label">状态</span>
                        <span class="metric-value-status {% if account.is_active %}status-active{% else %}status-inactive{% endif %}">
                            {% if account.is_active %}活跃{% else %}已停用{% endif %}
                        </span>
                    </div>
                    <!-- 策略信息 -->
                    <div class="account-metric">
                        <span class="metric-label">绑定策略</span>
                        <div class="metric-strategy">
                            {% if account.active_strategy %}
                                <span class="strategy-badge strategy-{{ account.active_strategy.strategy_type }}">
                                    {% if account.active_strategy.strategy_type == 'rule_based' %}规则驱动
                                    {% elif account.active_strategy.strategy_type == 'script_based' %}脚本驱动
                                    {% elif account.active_strategy.strategy_type == 'hybrid' %}混合模式
                                    {% elif account.active_strategy.strategy_type == 'ai_driven' %}AI驱动{% endif %}
                                </span>
                                <span class="strategy-name">{{ account.active_strategy.name }}</span>
                                <span class="strategy-status {% if account.active_strategy.is_active %}status-active{% else %}status-inactive{% endif %}">
                                    {% if account.active_strategy.is_active %}激活中{% else %}已停用{% endif %}
                                </span>
                            {% else %}
                                <span class="no-strategy">未绑定</span>
                            {% endif %}
                        </div>
                    </div>
                </div>
                <div class="account-card-footer">
                    <a href="{% url 'simulated_trading:my-account-detail' account.id %}" class="btn btn-primary">
                        查看详情
                    </a>
                    <a href="{% url 'share:manage' %}?account_id={{ account.id }}" class="btn btn-secondary">
                        分享链接
                    </a>
                    <a href="{% url 'simulated_trading:my-positions' account.id %}" class="btn btn-secondary">
                        持仓
                    </a>
                    <a href="{% url 'simulated_trading:my-trades' account.id %}" class="btn btn-secondary">
                        交易记录
                    </a>
                    {% if account.manual_trade_portfolio_id %}
                    <a href="{% url 'audit:manual_trades' %}?portfolio_id={{ account.manual_trade_portfolio_id }}" class="btn btn-secondary">
                        导入流水
                    </a>
                    {% endif %}
                    <button
                        type="button"
                        class="btn btn-danger btn-delete-account"
                        onclick="deleteAccount({{ account.id }}, '{{ account.account_name|escapejs }}')"
                    >
                        删除账户
                    </button>
                    {% if account.active_strategy %}
                        <button class="btn btn-danger" onclick="unbindStrategy({{ account.id }})">
                            解绑策略
                        </button>
                    {% else %}
                        <button class="btn btn-strategy" onclick="showBindStrategyModal({{ account.id }}, '{{ account.account_name }}')">
                            绑定策略
                        </button>
                    {% endif %}
                </div>
            </div>
            {% endfor %}
        </div>
        {% else %}
        <div class="empty-state">
            <div class="empty-icon">📭</div>
            <p>您还没有创建任何账户</p>
            <p class="empty-hint">点击右上角“创建新账户”按钮开始</p>
        </div>
        {% endif %}
    </section>

    <!-- 快捷操作 -->
    <section class="account-section">
        <h2 class="section-title">快捷操作</h2>
        <div class="action-buttons">
            <a href="{% url 'account:profile' %}" class="btn btn-secondary">账户设置</a>
            <a href="{% url 'dashboard:index' %}" class="btn btn-secondary">返回仪表盘</a>
        </div>
    </section>
</div>

<!-- 创建账户弹窗 -->
<div id="createModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2>创建新账户</h2>
            <span class="close" onclick="closeCreateModal()">&times;</span>
        </div>
        <form method="post" action="{% url 'simulated_trading:my-accounts' %}">
            {% csrf_token %}
            <div class="form-group">
                <label for="account_name">账户名称</label>
                <input type="text" id="account_name" name="account_name" placeholder="例如：我的主账户" required maxlength="100">
            </div>
            <div class="form-group">
                <label for="account_type">账户类型</label>
                <select id="account_type" name="account_type" required>
                    <option value="real">真实账户</option>
                    <option value="simulated">模拟账户</option>
                </select>
            </div>
            <div class="form-group">
                <label for="initial_capital">初始资金（元）</label>
                <input type="number" id="initial_capital" name="initial_capital" value="100000" min="1000" step="0.01" required>
            </div>
            <div class="form-quick-options">
                <button type="button" class="quick-option-btn" onclick="setCapital(50000)">5万</button>
                <button type="button" class="quick-option-btn" onclick="setCapital(100000)">10万</button>
                <button type="button" class="quick-option-btn" onclick="setCapital(500000)">50万</button>
                <button type="button" class="quick-option-btn" onclick="setCapital(1000000)">100万</button>
            </div>
            <div class="modal-footer">
                <button type="button" onclick="closeCreateModal()" class="btn btn-secondary">取消</button>
                <button type="submit" class="btn btn-primary">创建账户</button>
            </div>
        </form>
    </div>
</div>

<!-- 绑定策略弹窗 -->
<div id="bindStrategyModal" class="modal">
    <div class="modal-content" style="max-width: 600px;">
        <div class="modal-header">
            <h2>绑定策略</h2>
            <span class="close" onclick="closeBindStrategyModal()">&times;</span>
        </div>
        <div class="modal-body">
            <p style="margin-bottom: 16px;">选择要绑定到 <strong id="targetAccountName"></strong> 的策略：</p>

            <!-- 策略筛选 -->
            <div class="form-group">
                <input type="text" id="strategySearch" placeholder="搜索策略名称..." oninput="filterStrategies()">
            </div>

            <div class="form-group">
                <select id="strategyTypeFilter" 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>
            </div>

            <!-- 策略列表 -->
            <div id="strategyList" class="strategy-list">
                <div class="app-loading-state app-loading-state--compact"><p class="app-loading-text">正在加载策略列表...</p></div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" onclick="closeBindStrategyModal()" class="btn btn-secondary">取消</button>
            <button type="button" onclick="confirmBindStrategy()" class="btn btn-primary" id="confirmBindBtn" disabled>
                确认绑定
            </button>
        </div>
    </div>
</div>

<style>
.account-container {
    max-width: 1200px;
    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;
}

.section-header-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
    margin-bottom: 16px;
}

.section-header-row .section-title {
    margin-bottom: 0;
}

.account-bulk-actions {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

.bulk-select-all {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: #54595D;
}

.bulk-selected-count {
    font-size: 13px;
    color: #202122;
}

.accounts-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
}

.account-card {
    border: 1px solid #E0E0E0;
    border-radius: 8px;
    overflow: hidden;
    transition: box-shadow 0.2s, transform 0.2s;
}

.account-card:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
}

.account-card.account-real {
    background: linear-gradient(135deg, #e8f5e9 0%, #f1f8f2 100%);
    border-color: #81c784;
}

.account-card.account-simulated {
    background: linear-gradient(135deg, #e3f2fd 0%, #f0f7ff 100%);
    border-color: #64b5f6;
}

.account-card-header {
    padding: 16px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.account-card-heading {
    display: flex;
    align-items: center;
    gap: 10px;
}

.account-select-checkbox {
    display: inline-flex;
    align-items: center;
    cursor: pointer;
}

.account-select-input {
    width: 16px;
    height: 16px;
    cursor: pointer;
}

.account-card-header h3 {
    font-size: 18px;
    font-weight: 600;
    margin: 0;
}

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

.badge-real {
    background: #4caf50;
    color: white;
}

.badge-simulated {
    background: #2196f3;
    color: white;
}

.account-card-body {
    padding: 16px;
}

.account-metric {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.account-metric:last-child {
    border-bottom: none;
}

.metric-label {
    font-size: 13px;
    color: #666;
}

.metric-value {
    font-size: 20px;
    font-weight: 600;
    color: #202122;
}

.metric-value-sub {
    font-size: 14px;
    font-weight: 500;
    color: #54595D;
}

.metric-value-return {
    font-size: 16px;
    font-weight: 600;
}

.metric-value-status {
    font-size: 13px;
    font-weight: 500;
}

.positive {
    color: #14866D;
}

.negative {
    color: #D33;
}

.status-active {
    color: #14866D;
}

.status-inactive {
    color: #999;
}

.account-card-footer {
    padding: 16px;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

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

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

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

.btn-primary:hover {
    background: #25a;
}

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

.btn-secondary:hover {
    background: #e8e8e8;
}

.btn-danger {
    background: #D33;
    color: white;
    border: none;
}

.btn-danger:hover {
    background: #b22;
}

.btn-delete-account {
    margin-right: auto;
}

.btn-strategy {
    background: #667eea;
    color: white;
    border: none;
}

.btn-strategy:hover {
    background: #5568d3;
}

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

.empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
}

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

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

.empty-hint {
    font-size: 13px;
    color: #888;
}

/* 总资产统计 */
.total-assets {
    text-align: center;
    padding: 24px;
    background: linear-gradient(135deg, #e8f5e9 0%, #f1f8f2 100%);
    border-radius: 8px;
    border: 1px solid #81c784;
}

.total-assets-value {
    font-size: 36px;
    font-weight: 700;
    color: #2e7d32;
    margin-bottom: 8px;
}

.total-assets-label {
    font-size: 14px;
    color: #555;
}

/* 弹窗样式 */
#createModal,
#bindStrategyModal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.5);
}

#createModal .modal-content,
#bindStrategyModal .modal-content {
    background-color: #fefefe;
    margin: 10% auto;
    padding: 0;
    border: 1px solid #888;
    width: 90%;
    max-width: 500px;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

#createModal .modal-header,
#bindStrategyModal .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid #e0e0e0;
}

#createModal .modal-header h2,
#bindStrategyModal .modal-header h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
}

#createModal .close,
#bindStrategyModal .close {
    color: #aaa;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
}

#createModal .close:hover,
#bindStrategyModal .close:hover {
    color: #000;
}

/* 表单样式 */
.form-group {
    margin-bottom: 16px;
    padding: 0 24px;
}

.form-group label {
    display: block;
    margin-bottom: 6px;
    font-size: 14px;
    font-weight: 500;
    color: #333;
}

.form-group input,
.form-group select {
    width: 100%;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
    box-sizing: border-box;
}

.form-group input:focus,
.form-group select:focus {
    outline: none;
    border-color: #36C;
    box-shadow: 0 0 0 2px rgba(51, 102, 204, 0.1);
}

.form-quick-options {
    display: flex;
    gap: 8px;
    padding: 0 24px;
    margin-bottom: 16px;
}

.quick-option-btn {
    padding: 6px 12px;
    background: #f0f0f0;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    font-size: 13px;
    transition: all 0.2s;
}

.quick-option-btn:hover {
    background: #e0e0e0;
}

#createModal .modal-footer,
#bindStrategyModal .modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 24px;
    border-top: 1px solid #e0e0e0;
}

/* 策略绑定相关样式 */
#bindStrategyModal .modal-body {
    padding: 16px 24px;
    max-height: 400px;
    overflow-y: auto;
}

.strategy-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-top: 16px;
}

.strategy-option {
    padding: 12px 16px;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s;
}

.strategy-option:hover {
    border-color: #667eea;
    background: #f8fafc;
}

.strategy-option.selected {
    border-color: #667eea;
    background: #eff6ff;
}

.strategy-option-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.strategy-option-name {
    font-size: 15px;
    font-weight: 600;
    color: #334155;
}

.strategy-option-badges {
    display: flex;
    gap: 6px;
}

.strategy-option-desc {
    font-size: 13px;
    color: #64748b;
    line-height: 1.4;
}

.metric-strategy {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.strategy-badge {
    display: inline-block;
    padding: 3px 10px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
}

.strategy-badge.strategy-rule_based {
    background: #dbeafe;
    color: #1e40af;
}

.strategy-badge.strategy-script_based {
    background: #f3e8ff;
    color: #6b21a8;
}

.strategy-badge.strategy-hybrid {
    background: #ffedd5;
    color: #9a3412;
}

.strategy-badge.strategy-ai_driven {
    background: #dcfce7;
    color: #166534;
}

.strategy-name {
    font-size: 14px;
    font-weight: 500;
    color: #334155;
}

.strategy-status {
    font-size: 12px;
}

.no-strategy {
    font-size: 13px;
    color: #94a3b8;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .account-container {
        padding: 16px;
    }

    .section-header-row {
        flex-direction: column;
        align-items: flex-start;
    }

    .accounts-grid {
        grid-template-columns: 1fr;
    }

    .account-card-footer {
        flex-direction: column;
    }

    .account-card-footer .btn {
        width: 100%;
        text-align: center;
    }
}
</style>

<script>
// 全局变量
let currentAccountId = null;
let availableStrategies = [];
let selectedStrategyId = null;

function getCsrfToken() {
    const cookie = document.cookie
        .split('; ')
        .find(row => row.startsWith('csrftoken='));
    return cookie ? decodeURIComponent(cookie.split('=')[1]) : '';
}

async function confirmAction(message, options = {}) {
    if (window.uiConfirm) {
        return window.uiConfirm(message, options);
    }
    return Promise.resolve(window.confirm(message));
}

function getSelectedAccountInputs() {
    return Array.from(document.querySelectorAll('.account-select-input:checked'));
}

function updateAccountSelectionState() {
    const selectedInputs = getSelectedAccountInputs();
    const totalInputs = document.querySelectorAll('.account-select-input').length;
    const countEl = document.getElementById('selectedAccountCount');
    const bulkDeleteBtn = document.getElementById('bulkDeleteBtn');
    const clearSelectionBtn = document.getElementById('clearSelectionBtn');
    const selectAll = document.getElementById('selectAllAccounts');

    if (countEl) {
        countEl.textContent = `已选择 ${selectedInputs.length} 个`;
    }
    if (bulkDeleteBtn) {
        bulkDeleteBtn.disabled = selectedInputs.length === 0;
    }
    if (clearSelectionBtn) {
        clearSelectionBtn.disabled = selectedInputs.length === 0;
    }
    if (selectAll) {
        selectAll.checked = totalInputs > 0 && selectedInputs.length === totalInputs;
        selectAll.indeterminate = selectedInputs.length > 0 && selectedInputs.length < totalInputs;
    }
}

function toggleSelectAllAccounts(checked) {
    document.querySelectorAll('.account-select-input').forEach(input => {
        input.checked = checked;
    });
    updateAccountSelectionState();
}

function clearAccountSelection() {
    toggleSelectAllAccounts(false);
}

async function deleteAccount(accountId, accountName) {
    const confirmed = await confirmAction(
        `确认删除账户“${accountName}”？\n\n该账户的持仓、交易记录和巡检记录会一起删除，此操作不可恢复。`,
        { title: '删除账户', icon: 'warning' }
    );
    if (!confirmed) {
        return;
    }

    try {
        const res = await fetch(`/api/simulated-trading/accounts/${accountId}/`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken(),
            },
        });
        const data = await res.json();
        if (!res.ok || !data.success) {
            throw new Error(data.error || '删除失败');
        }

        showToast(data.message || '账户已删除');
        document.querySelector(`.account-card[data-account-id="${accountId}"]`)?.remove();
        updateAccountSelectionState();
        setTimeout(() => location.reload(), 800);
    } catch (e) {
        showToast(`删除失败: ${e.message}`, 'error');
    }
}

async function deleteSelectedAccounts() {
    const selectedInputs = getSelectedAccountInputs();
    if (selectedInputs.length === 0) {
        return;
    }

    const accountIds = selectedInputs.map(input => parseInt(input.value, 10));
    const accountNames = selectedInputs.map(input => input.dataset.accountName);
    const confirmed = await confirmAction(
        `确认批量删除这 ${accountIds.length} 个账户？\n\n${accountNames.join('、')}\n\n该操作不可恢复。`,
        { title: '批量删除账户', icon: 'warning' }
    );
    if (!confirmed) {
        return;
    }

    try {
        const res = await fetch('/api/simulated-trading/accounts/batch-delete/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken(),
            },
            body: JSON.stringify({ account_ids: accountIds }),
        });
        const data = await res.json();
        if (!res.ok || !data.success) {
            throw new Error(data.error || '批量删除失败');
        }

        (data.deleted_account_ids || []).forEach(accountId => {
            document.querySelector(`.account-card[data-account-id="${accountId}"]`)?.remove();
        });

        if (Array.isArray(data.failed) && data.failed.length > 0) {
            const failedSummary = data.failed.map(item => `${item.account_id}:${item.error}`).join('；');
            showToast(`已删除 ${data.deleted_count} 个，失败 ${data.failed.length} 个: ${failedSummary}`, 'error');
        } else {
            showToast(data.message || `已删除 ${data.deleted_count} 个账户`);
        }

        updateAccountSelectionState();
        setTimeout(() => location.reload(), 900);
    } catch (e) {
        showToast(`批量删除失败: ${e.message}`, 'error');
    }
}

function showCreateModal() {
    document.getElementById('createModal').style.display = 'block';
}

function closeCreateModal() {
    document.getElementById('createModal').style.display = 'none';
}

function setCapital(amount) {
    document.getElementById('initial_capital').value = amount;
}

// 策略绑定相关函数
function showBindStrategyModal(accountId, accountName) {
    currentAccountId = accountId;
    selectedStrategyId = null;
    document.getElementById('targetAccountName').textContent = accountName;
    document.getElementById('bindStrategyModal').style.display = 'block';
    document.getElementById('confirmBindBtn').disabled = true;

    // 加载策略列表
    loadStrategies();
}

function closeBindStrategyModal() {
    document.getElementById('bindStrategyModal').style.display = 'none';
    currentAccountId = null;
    selectedStrategyId = null;
}

async function loadStrategies() {
    const strategyList = document.getElementById('strategyList');
    strategyList.innerHTML = '<div class="app-loading-state app-loading-state--compact"><p class="app-loading-text">正在加载策略列表...</p></div>';

    try {
        const res = await fetch('/api/strategy/strategies/my_strategies/');
        const data = await res.json();

        if (Array.isArray(data)) {
            availableStrategies = data;
            renderStrategies(availableStrategies);
        } else {
            strategyList.innerHTML = '<div class="app-loading-state app-loading-state--compact"><p class="app-loading-text app-loading-text--error">加载失败</p></div>';
        }
    } catch (e) {
        strategyList.innerHTML = '<div class="app-loading-state app-loading-state--compact"><p class="app-loading-text app-loading-text--error">加载失败: ' + e.message + '</p></div>';
    }
}

function renderStrategies(strategies) {
    const strategyList = document.getElementById('strategyList');

    if (strategies.length === 0) {
        strategyList.innerHTML = '<div class="app-loading-state app-loading-state--compact"><p class="app-loading-text">暂无可用策略，请先创建策略</p></div>';
        return;
    }

    strategyList.innerHTML = strategies.map(strategy => `
        <div class="strategy-option" onclick="selectStrategy(${strategy.id || strategy.strategy_id})" data-strategy-id="${strategy.id || strategy.strategy_id}">
            <div class="strategy-option-header">
                <span class="strategy-option-name">${strategy.name}</span>
                <div class="strategy-option-badges">
                    <span class="strategy-badge strategy-${strategy.strategy_type}">
                        ${getStrategyTypeName(strategy.strategy_type)}
                    </span>
                    <span class="strategy-badge ${strategy.is_active ? 'status-active' : 'status-inactive'}">
                        ${strategy.is_active ? '激活中' : '已停用'}
                    </span>
                </div>
            </div>
            <div class="strategy-option-desc">${strategy.description || '暂无描述'}</div>
        </div>
    `).join('');
}

function getStrategyTypeName(type) {
    const names = {
        'rule_based': '规则驱动',
        'script_based': '脚本驱动',
        'hybrid': '混合模式',
        'ai_driven': 'AI驱动'
    };
    return names[type] || type;
}

function selectStrategy(strategyId) {
    selectedStrategyId = strategyId;

    // 更新选中状态
    document.querySelectorAll('.strategy-option').forEach(el => {
        el.classList.remove('selected');
        if (parseInt(el.dataset.strategyId) === strategyId) {
            el.classList.add('selected');
        }
    });

    // 启用确认按钮
    document.getElementById('confirmBindBtn').disabled = false;
}

function filterStrategies() {
    const search = document.getElementById('strategySearch').value.toLowerCase();
    const typeFilter = document.getElementById('strategyTypeFilter').value;

    const filtered = availableStrategies.filter(strategy => {
        const matchSearch = !search || strategy.name.toLowerCase().includes(search);
        const matchType = !typeFilter || strategy.strategy_type === typeFilter;
        return matchSearch && matchType;
    });

    renderStrategies(filtered);
}

async function confirmBindStrategy() {
    if (!currentAccountId || !selectedStrategyId) {
        return;
    }

    try {
        const res = await fetch('/api/strategy/bind-strategy/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                portfolio_id: currentAccountId,
                strategy_id: selectedStrategyId
            })
        });

        const data = await res.json();

        if (data.success) {
            showToast('策略绑定成功');
            closeBindStrategyModal();
            setTimeout(() => location.reload(), 1500);
        } else {
            showToast('绑定失败: ' + (data.error || '未知错误'), 'error');
        }
    } catch (e) {
        showToast('绑定失败: ' + e.message, 'error');
    }
}

async function unbindStrategy(accountId) {
    if (!confirm('确认解绑此账户的策略？\n\n解绑后，该账户将不再自动执行策略。')) {
        return;
    }

    try {
        const res = await fetch('/api/strategy/unbind-strategy/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                portfolio_id: accountId
            })
        });

        const data = await res.json();

        if (data.success) {
            showToast('策略已解绑');
            setTimeout(() => location.reload(), 1500);
        } else {
            showToast('解绑失败: ' + (data.error || '未知错误'), 'error');
        }
    } catch (e) {
        showToast('解绑失败: ' + e.message, 'error');
    }
}

function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    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;
        font-size: 14px;
    `;
    toast.textContent = message;
    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);
}

// 点击弹窗外部关闭
window.onclick = function(event) {
    const createModal = document.getElementById('createModal');
    const bindModal = document.getElementById('bindStrategyModal');

    if (event.target == createModal) {
        createModal.style.display = 'none';
    }
    if (event.target == bindModal) {
        bindModal.style.display = 'none';
    }
}

// ============================================================================
// 实时价格轮询功能
// ============================================================================

// 价格轮询配置
const PRICE_POLLING_CONFIG = {
    enabled: true,           // 是否启用轮询
    interval: 30000,         // 轮询间隔（毫秒），默认30秒
    apiEndpoint: '/api/realtime/prices/',  // 价格API端点
};

// 存储轮询定时器ID
let pricePollingTimer = null;
let isPolling = false;

/**
 * 启动价格轮询
 */
function startPricePolling() {
    if (!PRICE_POLLING_CONFIG.enabled) {
        console.log('价格轮询功能已禁用');
        return;
    }

    if (isPolling) {
        console.log('价格轮询已在运行中');
        return;
    }

    console.log(`启动价格轮询，间隔: ${PRICE_POLLING_CONFIG.interval / 1000}秒`);
    isPolling = true;

    // 立即执行一次
    updatePrices();

    // 启动定时轮询
    pricePollingTimer = setInterval(updatePrices, PRICE_POLLING_CONFIG.interval);
}

/**
 * 停止价格轮询
 */
function stopPricePolling() {
    if (pricePollingTimer) {
        clearInterval(pricePollingTimer);
        pricePollingTimer = null;
        isPolling = false;
        console.log('价格轮询已停止');
    }
}

/**
 * 更新价格数据
 */
async function updatePrices() {
    try {
        // 获取所有持仓资产代码
        const assetCodes = getHeldAssetCodes();

        if (assetCodes.length === 0) {
            console.log('没有持仓资产，跳过价格更新');
            return;
        }

        // 请求价格数据
        const response = await fetch(`${PRICE_POLLING_CONFIG.apiEndpoint}?assets=${assetCodes.join(',')}`);

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();

        // 更新UI
        updateUIWithPrices(data.prices || []);

        console.log(`价格更新完成: ${data.success || 0}/${data.total || 0} 个资产`);

    } catch (error) {
        console.error('价格更新失败:', error);
    }
}

/**
 * 获取所有持仓资产代码
 */
function getHeldAssetCodes() {
    const codes = [];
    const accountCards = document.querySelectorAll('.account-card');

    accountCards.forEach(card => {
        const assetCodes = card.getAttribute('data-asset-codes');
        if (assetCodes) {
            codes.push(...assetCodes.split(','));
        }
    });

    return [...new Set(codes)];  // 去重
}

/**
 * 使用价格数据更新UI
 */
function updateUIWithPrices(prices) {
    // 创建价格映射表
    const priceMap = {};
    prices.forEach(price => {
        priceMap[price.asset_code] = price;
    });

    // 更新每个账户卡片
    const accountCards = document.querySelectorAll('.account-card');

    accountCards.forEach(card => {
        const accountId = card.getAttribute('data-account-id');
        const assetCodes = card.getAttribute('data-asset-codes');

        if (!assetCodes) return;

        const codes = assetCodes.split(',');
        let totalMarketValue = 0;

        // 更新持仓列表中的价格
        const positionItems = card.querySelectorAll('.position-item');
        positionItems.forEach(item => {
            const assetCode = item.getAttribute('data-asset-code');
            const price = priceMap[assetCode];

            if (price) {
                // 更新价格显示
                const priceEl = item.querySelector('.position-price');
                if (priceEl) {
                    const oldPrice = parseFloat(priceEl.textContent.replace('¥', ''));
                    const newPrice = price.price;

                    priceEl.textContent = `¥${newPrice.toFixed(2)}`;

                    // 高亮价格变化
                    if (newPrice > oldPrice) {
                        priceEl.style.color = '#ef4444';  // 红色表示上涨
                        setTimeout(() => priceEl.style.color = '', 2000);
                    } else if (newPrice < oldPrice) {
                        priceEl.style.color = '#10b981';  // 绿色表示下跌
                        setTimeout(() => priceEl.style.color = '', 2000);
                    }
                }

                // 更新市值
                const quantityEl = item.querySelector('.position-quantity');
                if (quantityEl) {
                    const quantity = parseFloat(quantityEl.textContent.replace(/[^0-9.-]+/g, ''));
                    totalMarketValue += newPrice * quantity;
                }
            }
        });

        // 更新账户总市值（可选，需要从后端获取完整数据）
        const totalValueEl = card.querySelector('.total-value');
        if (totalValueEl && totalMarketValue > 0) {
            // 这里可以添加动画效果
            console.log(`账户 ${accountId} 市值更新: ${totalMarketValue.toFixed(2)}`);
        }
    });
}

// 页面加载完成后启动价格轮询
document.addEventListener('DOMContentLoaded', function() {
    updateAccountSelectionState();
    // 延迟3秒后启动轮询，避免页面加载时过于频繁的请求
    setTimeout(startPricePolling, 3000);
});

// 页面卸载时停止轮询
window.addEventListener('beforeunload', function() {
    stopPricePolling();
});
</script>
{% endblock %}
