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

{% block rotation_content %}
<div class="rotation-header">
    <h1>账户轮动配置</h1>
    <div class="header-meta">
        <span class="meta-item">📅 {{ current_date|date:"Y-m-d" }}</span>
        <a href="{% url 'rotation:configs' %}" class="btn-secondary-sm">查看全局模板</a>
    </div>
</div>

<p class="page-desc">为每个投资组合账户独立配置风险偏好和各宏观象限的资产权重，配置互相独立，互不影响。</p>

{% if not user_accounts %}
<div class="empty-state">
    <div class="empty-icon">📂</div>
    <p>暂无投资组合账户</p>
    <a href="/simulated-trading/" class="btn-primary">前往创建账户</a>
</div>
{% else %}
<div class="accounts-grid">
    {% for account in user_accounts %}
    <article class="account-card">
        <div class="account-card-header">
            <div>
                <div class="account-name">{{ account.account_name }}</div>
                <div class="account-meta">{{ account.get_account_type_display }} · 总资产 ¥{{ account.total_value|floatformat:0 }} · 现金 ¥{{ account.current_cash|floatformat:0 }}</div>
            </div>
            <div class="badges">
                {% if account.rotation_config %}
                <span class="status-pill {% if account.rotation_config.is_enabled %}enabled{% else %}disabled{% endif %}">
                    {% if account.rotation_config.is_enabled %}轮动已启用{% else %}轮动未启用{% endif %}
                </span>
                <span class="risk-pill risk-{{ account.rotation_config.risk_tolerance }}">
                    {{ account.rotation_config.get_risk_tolerance_display }}
                </span>
                {% else %}
                <span class="status-pill unconfigured">未配置</span>
                {% endif %}
            </div>
        </div>

        {% if account.rotation_config and account.rotation_config.regime_allocations %}
        <div class="regime-summary">
            {% for regime, allocs in account.rotation_config.regime_allocations.items %}
            <span class="regime-chip">{{ regime }} · {{ allocs|length }} 资产</span>
            {% endfor %}
        </div>
        {% endif %}

        <div class="account-card-footer">
            <button
                type="button"
                class="btn-primary-sm js-open-config"
                onclick="handleOpenConfigFromDataset(this)"
                data-account-id="{{ account.id }}"
                data-account-name="{{ account.account_name|escape }}"
                data-risk-tolerance="{% if account.rotation_config %}{{ account.rotation_config.risk_tolerance }}{% else %}moderate{% endif %}"
                data-is-enabled="{% if account.rotation_config and account.rotation_config.is_enabled %}true{% else %}false{% endif %}"
                data-config-id="{% if account.rotation_config %}{{ account.rotation_config.id }}{% endif %}"
            >
                {% if account.rotation_config %}编辑配置{% else %}+ 配置轮动{% endif %}
            </button>
        </div>
    </article>
    {% endfor %}
</div>
{% endif %}

<div id="accountConfigModal" class="modal" hidden>
    <div class="modal-content modal-lg">
        <div class="modal-header">
            <h3 id="modalAccountTitle">账户轮动配置</h3>
            <button type="button" class="modal-close" id="closeConfigModal" aria-label="关闭">&times;</button>
        </div>

        <div class="modal-tabs">
            <button type="button" class="tab-btn active" data-tab-target="tab-basic">基本信息</button>
            <button type="button" class="tab-btn" data-tab-target="tab-quadrant">象限配置</button>
            <button type="button" class="tab-btn" data-tab-target="tab-preview">配置预览</button>
        </div>

        <form id="accountConfigForm">
            <input type="hidden" id="formAccountId" name="account_id">
            <input type="hidden" id="formConfigId" name="config_id">

            <section id="tab-basic" class="tab-panel active">
                <div class="form-group">
                    <label for="displayAccountName">账户名称</label>
                    <input type="text" id="displayAccountName" class="form-input" readonly>
                </div>

                <div class="form-group">
                    <label for="riskTolerance">风险偏好</label>
                    <select id="riskTolerance" name="risk_tolerance" class="form-select">
                        {% for value, label in risk_tolerance_choices %}
                        <option value="{{ value }}">{{ label }}</option>
                        {% endfor %}
                    </select>
                </div>

                <label class="toggle-row" for="isEnabled">
                    <span>启用轮动自动调仓</span>
                    <input type="checkbox" id="isEnabled" name="is_enabled">
                </label>
                <p class="form-hint">启用后，自动交易将在 Regime 切换时按照下方象限配置调仓。</p>

                <div class="form-group">
                    <label>快速应用预设模板</label>
                    <div class="template-buttons">
                        <button type="button" class="btn-template" data-template-key="conservative">保守型</button>
                        <button type="button" class="btn-template" data-template-key="moderate">稳健型</button>
                        <button type="button" class="btn-template" data-template-key="aggressive">激进型</button>
                    </div>
                    <p class="form-hint">模板数据从数据库读取，应用后可在「象限配置」中微调。</p>
                </div>
            </section>

            <section id="tab-quadrant" class="tab-panel" hidden>
                <link rel="stylesheet" href="{% static 'rotation/css/quadrant_editor.css' %}">
                <input type="hidden" id="regimeAllocationsJson" name="regime_allocations" value="">
                <div id="quadrantEditorContainer"></div>
            </section>

            <section id="tab-preview" class="tab-panel" hidden>
                <p class="form-hint">当前配置的 JSON 格式（保存前预览）：</p>
                <pre id="configPreview" class="json-preview"></pre>
            </section>

            <div class="modal-footer">
                <button type="button" class="btn-secondary" id="cancelConfigModal">取消</button>
                <button type="button" class="btn-primary" id="saveConfigBtn">保存配置</button>
            </div>
        </form>
    </div>
</div>

<script>
const modalEl = document.getElementById('accountConfigModal');
const formAccountIdEl = document.getElementById('formAccountId');
const formConfigIdEl = document.getElementById('formConfigId');
const displayAccountNameEl = document.getElementById('displayAccountName');
const riskToleranceEl = document.getElementById('riskTolerance');
const isEnabledEl = document.getElementById('isEnabled');
const modalTitleEl = document.getElementById('modalAccountTitle');
const previewEl = document.getElementById('configPreview');

async function waitForEditor(timeout = 5000) {
    const start = Date.now();
    while (!window.quadrantEditor) {
        if (Date.now() - start > timeout) {
            throw new Error('象限编辑器初始化超时');
        }
        await new Promise(resolve => setTimeout(resolve, 100));
    }
    if (typeof window.quadrantEditor.ready === 'function') {
        await Promise.race([
            window.quadrantEditor.ready(),
            new Promise((_, reject) => setTimeout(() => reject(new Error('象限编辑器初始化超时')), timeout)),
        ]);
    }
}

function switchAccountConfigTab(tabId) {
    document.querySelectorAll('.tab-btn').forEach(button => {
        button.classList.toggle('active', button.dataset.tabTarget === tabId);
    });
    document.querySelectorAll('.tab-panel').forEach(panel => {
        const active = panel.id === tabId;
        panel.hidden = !active;
        panel.classList.toggle('active', active);
    });
    if (tabId === 'tab-preview') {
        updatePreview();
    }
}

function updatePreview() {
    const allocations = window.quadrantEditor ? window.quadrantEditor.getData() : {};
    previewEl.textContent = JSON.stringify({
        risk_tolerance: riskToleranceEl.value,
        is_enabled: isEnabledEl.checked,
        regime_allocations: allocations,
    }, null, 2);
}

function openAccountConfigModal() {
    modalEl.hidden = false;
    modalEl.style.display = 'flex';
}

function closeAccountConfigModal() {
    modalEl.hidden = true;
    modalEl.style.display = 'none';
}

async function loadConfig(configId) {
    if (!configId) {
        window.quadrantEditor.loadFromJson('{}');
        updatePreview();
        return;
    }
    const response = await fetch(`/api/rotation/account-configs/${configId}/`, {
        headers: { 'X-CSRFToken': window.csrfToken }
    });
    if (!response.ok) {
        throw new Error(`加载配置失败: ${response.status}`);
    }
    const data = await response.json();
    window.quadrantEditor.loadFromJson(JSON.stringify(data.regime_allocations || {}));
    updatePreview();
}

async function handleOpenConfig(button) {
    formAccountIdEl.value = button.dataset.accountId || '';
    formConfigIdEl.value = button.dataset.configId || '';
    displayAccountNameEl.value = button.dataset.accountName || '';
    riskToleranceEl.value = button.dataset.riskTolerance || 'moderate';
    isEnabledEl.checked = button.dataset.isEnabled === 'true';
    modalTitleEl.textContent = `${button.dataset.accountName || '账户'} - 轮动配置`;
    switchAccountConfigTab('tab-basic');
    openAccountConfigModal();
    await waitForEditor();
    await loadConfig(button.dataset.configId || '');
}

function handleOpenConfigFromDataset(button) {
    handleOpenConfig(button).catch(error => {
        console.error(error);
        showToast(`加载失败: ${error.message}`, 'error');
    });
}

async function saveConfig() {
    const payload = {
        account: parseInt(formAccountIdEl.value, 10),
        risk_tolerance: riskToleranceEl.value,
        is_enabled: isEnabledEl.checked,
        regime_allocations: window.quadrantEditor ? window.quadrantEditor.getData() : {},
    };

    const configId = formConfigIdEl.value;
    const response = await fetch(
        configId ? `/api/rotation/account-configs/${configId}/` : '/api/rotation/account-configs/',
        {
            method: configId ? 'PUT' : 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': window.csrfToken,
            },
            body: JSON.stringify(payload),
        }
    );

    if (!response.ok) {
        const errorPayload = await response.json();
        const message = errorPayload.regime_allocations || errorPayload.detail || JSON.stringify(errorPayload);
        throw new Error(message);
    }

    showToast(configId ? '配置已更新' : '配置已创建', 'success');
    closeAccountConfigModal();
    window.location.reload();
}

document.querySelectorAll('.tab-btn').forEach(button => {
    button.addEventListener('click', () => switchAccountConfigTab(button.dataset.tabTarget));
});

document.querySelectorAll('.btn-template').forEach(button => {
    button.addEventListener('click', async () => {
        try {
            await waitForEditor();
            window.quadrantEditor.applyTemplate(button.dataset.templateKey);
            riskToleranceEl.value = button.dataset.templateKey;
            updatePreview();
        } catch (error) {
            console.error(error);
            showToast(`模板加载失败: ${error.message}`, 'error');
        }
    });
});

document.getElementById('closeConfigModal').addEventListener('click', closeAccountConfigModal);
document.getElementById('cancelConfigModal').addEventListener('click', closeAccountConfigModal);
document.getElementById('saveConfigBtn').addEventListener('click', () => {
    saveConfig().catch(error => {
        console.error(error);
        showToast(`保存失败: ${error.message}`, 'error');
    });
});

riskToleranceEl.addEventListener('change', updatePreview);
isEnabledEl.addEventListener('change', updatePreview);

window.addEventListener('click', event => {
    if (event.target === modalEl) {
        closeAccountConfigModal();
    }
});
</script>

<script src="{% static 'rotation/js/quadrant_editor.js' %}"></script>
<script>
(function () {
    const editor = new RotationQuadrantEditor('quadrantEditorContainer', 'regimeAllocationsJson');
    window.quadrantEditor = editor;
    editor.init();
})();
</script>

<style>
.page-desc { color: #6b7280; margin-bottom: 24px; }
.accounts-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 16px; }
.account-card { background: #fff; border: 1px solid #e5e7eb; border-radius: 12px; }
.account-card-header { padding: 16px; display: flex; justify-content: space-between; gap: 12px; border-bottom: 1px solid #f3f4f6; }
.account-name { font-size: 16px; font-weight: 600; color: #111827; }
.account-meta { margin-top: 6px; font-size: 12px; color: #6b7280; }
.badges { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; }
.status-pill, .risk-pill, .regime-chip { display: inline-flex; align-items: center; padding: 4px 8px; border-radius: 999px; font-size: 12px; }
.status-pill.enabled { background: #d1fae5; color: #065f46; }
.status-pill.disabled { background: #f3f4f6; color: #6b7280; }
.status-pill.unconfigured { background: #fef3c7; color: #92400e; }
.risk-conservative { background: #dbeafe; color: #1e40af; }
.risk-moderate { background: #dcfce7; color: #166534; }
.risk-aggressive { background: #fce7f3; color: #9d174d; }
.regime-summary { padding: 0 16px 16px; display: flex; flex-wrap: wrap; gap: 8px; }
.regime-chip { background: #f3f4f6; color: #374151; }
.account-card-footer { padding: 0 16px 16px; display: flex; justify-content: flex-end; }
.btn-primary, .btn-secondary, .btn-primary-sm, .btn-secondary-sm, .btn-template { border: none; border-radius: 8px; cursor: pointer; text-decoration: none; }
.btn-primary, .btn-secondary { padding: 10px 18px; }
.btn-primary-sm, .btn-secondary-sm { padding: 8px 14px; display: inline-block; }
.btn-primary, .btn-primary-sm { background: #2563eb; color: #fff; }
.btn-secondary, .btn-secondary-sm { background: #e5e7eb; color: #374151; }
.btn-template { padding: 8px 14px; background: #eff6ff; color: #1d4ed8; border: 1px solid #bfdbfe; }
#accountConfigModal { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.4); align-items: center; justify-content: center; z-index: 1000; }
#accountConfigModal .modal-content { background: #fff; border-radius: 16px; width: min(960px, 92vw); max-height: 92vh; overflow: auto; }
#accountConfigModal .modal-header, #accountConfigModal .modal-footer { padding: 20px; border-bottom: 1px solid #e5e7eb; }
#accountConfigModal .modal-footer { border-top: 1px solid #e5e7eb; border-bottom: none; display: flex; justify-content: flex-end; gap: 12px; }
#accountConfigModal .modal-close { background: none; border: none; font-size: 28px; cursor: pointer; }
.modal-tabs { display: flex; gap: 8px; padding: 0 20px; border-bottom: 1px solid #e5e7eb; }
.tab-btn { background: none; border: none; padding: 14px 8px; color: #6b7280; border-bottom: 2px solid transparent; cursor: pointer; }
.tab-btn.active { color: #2563eb; border-bottom-color: #2563eb; }
.tab-panel { padding: 20px; }
.form-group { margin-bottom: 16px; }
.form-group label { display: block; margin-bottom: 6px; font-size: 13px; color: #4b5563; }
.form-input, .form-select { width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; }
.toggle-row { display: flex; align-items: center; justify-content: space-between; font-weight: 500; color: #111827; margin-bottom: 4px; }
.form-hint { margin: 6px 0 0; color: #6b7280; font-size: 12px; }
.template-buttons { display: flex; gap: 8px; flex-wrap: wrap; }
.json-preview { background: #f8fafc; border: 1px solid #e5e7eb; border-radius: 8px; padding: 12px; font-size: 12px; white-space: pre-wrap; max-height: 360px; overflow: auto; }
@media (max-width: 640px) {
    .account-card-header { flex-direction: column; }
    .badges { align-items: flex-start; }
    #accountConfigModal .modal-content { width: 96vw; }
}
</style>
{% endblock %}
