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

{% block title %}Regime 判定 - AgomTradePro{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'css/regime.css' %}">
<link rel="stylesheet" href="{% static 'css/teaching.css' %}">
{% if regime_result %}
<style>
    :root {
        {% if regime_result.quadrant == 'Recovery' %}
        --color-primary: #10B981; /* Green */
        --color-primary-light: #D1FAE5;
        {% elif regime_result.quadrant == 'Overheat' %}
        --color-primary: #EF4444; /* Red */
        --color-primary-light: #FEE2E2;
        {% elif regime_result.quadrant == 'Stagflation' %}
        --color-primary: #F59E0B; /* Orange */
        --color-primary-light: #FEF3C7;
        {% elif regime_result.quadrant == 'Deflation' %}
        --color-primary: #3B82F6; /* Blue */
        --color-primary-light: #DBEAFE;
        {% endif %}
    }
</style>
{% endif %}
{% endblock %}

{% block content %}
<div class="page-header">
    <div class="header-content">
        <div>
            <h1>Regime 判定</h1>
        </div>
        <div class="data-source-selector">
            <label for="dateSelect">分析时点:</label>
            <input type="date" id="dateSelect" data-datepicker value="{{ as_of_date|date:'Y-m-d' }}"
                   hx-get="{% url 'regime:dashboard' %}" hx-trigger="change" hx-include="#dateSelect,#sourceSelect"
                   hx-push-url="true" hx-indicator="#syncProgress">
            <label for="sourceSelect">数据源:</label>
            <select id="sourceSelect"
                    hx-get="{% url 'regime:dashboard' %}" hx-trigger="change" hx-include="#dateSelect,#sourceSelect"
                    hx-push-url="true" hx-indicator="#syncProgress">
                {% if available_sources %}
                    {% for source in available_sources %}
                    <option value="{{ source.source_type }}" {% if current_source == source.source_type %}selected{% endif %}>
                        {{ source.name }}
                    </option>
                    {% endfor %}
                {% else %}
                    <option value="akshare">AkShare (默认)</option>
                {% endif %}
            </select>
            <span class="source-badge source-{{ current_source }}">{{ current_source }}</span>
            <button id="syncBtn" class="sync-btn" onclick="syncData()" title="同步宏观数据">
                <span class="sync-icon">⟳</span> <span id="syncBtnText">同步数据</span>
            </button>
            <button id="clearCacheBtn" class="sync-btn" onclick="clearRegimeCache()" title="清除缓存并刷新">
                <span>🔄</span> <span>强制刷新</span>
            </button>
            <div id="syncProgress" class="sync-progress" style="display: none;">
                <div class="progress-bar">
                    <div id="progressFill" class="progress-fill"></div>
                </div>
                <div id="progressText" class="progress-text">正在同步...</div>
            </div>
                <a href="{% url 'data_center:dc-providers-page' %}" class="config-link" title="配置数据源">
                <span>⚙️</span>
            </a>
            <button class="teaching-toggle-btn" onclick="openTeachingModal()" title="学习Regime判定系统">
                <span class="btn-icon">📚</span>
                <span class="btn-text">学习Regime判定</span>
            </button>
            <a href="#navigatorHistorySection" class="config-link" title="查看历史叠加时序图">
                <span>🕰️</span>
            </a>
        </div>
    </div>
</div>

<script>
// CSRF Token 辅助函数
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// 设置全局 CSRF token
window.csrfToken = getCookie('csrftoken');

// Toast 消息提示
function showToast(message, type = 'info') {
    // 移除旧的 toast
    const existingToast = document.querySelector('.toast-message');
    if (existingToast) {
        existingToast.remove();
    }

    // 创建新的 toast
    const toast = document.createElement('div');
    toast.className = `toast-message toast-${type}`;
    toast.textContent = message;
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 20px;
        background: ${type === 'success' ? 'var(--color-success)' : type === 'error' ? 'var(--color-error)' : 'var(--color-primary)'};
        color: white;
        border-radius: var(--radius-md);
        box-shadow: var(--shadow-lg);
        z-index: 10000;
    `;
    document.body.appendChild(toast);

    // 3秒后自动消失
    setTimeout(() => {
        toast.remove();
    }, 3000);
}

async function syncData() {
    const syncBtn = document.getElementById('syncBtn');
    const progress = document.getElementById('syncProgress');
    const progressFill = document.getElementById('progressFill');
    const progressText = document.getElementById('progressText');
    const providerId = Number('{{ current_source_provider_id|default:"0" }}');

    syncBtn.disabled = true;
    progress.style.display = 'block';
    progressFill.style.width = '0%';
    progressText.textContent = '正在同步数据...';

    try {
        if (!providerId) {
            throw new Error('当前数据源未配置可用的 Data Center provider');
        }

        const today = document.getElementById('dateSelect').value || '{{ as_of_date|date:"Y-m-d" }}';
        const indicators = ['CN_PMI', 'CN_CPI_NATIONAL_YOY'];
        let successCount = 0;

        for (const indicatorCode of indicators) {
            const response = await fetch('{% url "api_data_center:dc-sync-macro" %}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': window.csrfToken
                },
                body: JSON.stringify({
                    provider_id: providerId,
                    indicator_code: indicatorCode,
                    start: today,
                    end: today
                })
            });
            const data = await response.json();
            if (!response.ok || data.status === 'error' || data.error_message) {
                throw new Error(data.detail || data.error_message || `同步 ${indicatorCode} 失败`);
            }
            successCount += 1;
            progressFill.style.width = `${Math.round((successCount / indicators.length) * 100)}%`;
            progressText.textContent = `已同步 ${successCount}/${indicators.length} 个指标...`;
        }

        progressFill.style.width = '100%';
        progressText.textContent = '同步完成！';
        showToast('数据同步成功', 'success');

        setTimeout(() => {
            location.reload();
        }, 1000);
    } catch (error) {
        progressText.textContent = '同步失败: ' + error.message;
        showToast('数据同步失败', 'error');
        syncBtn.disabled = false;
    }
}

async function clearRegimeCache() {
    try {
        const response = await fetch('/regime/clear-cache/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': window.csrfToken
            }
        });

        if (response.redirected) {
            window.location.href = response.url;
        } else {
            showToast('缓存已清除', 'success');
            setTimeout(() => location.reload(), 500);
        }
    } catch (error) {
        showToast('清除缓存失败', 'error');
    }
}
</script>

<!-- Regime 判定结果 -->
{% if error %}
<div class="alert alert-error">
    <i class="bi bi-exclamation-triangle"></i> {{ error }}
</div>
{% endif %}

{% if regime_result %}
<div class="card" style="margin-bottom: 20px;">
    <div class="card-body" style="display: flex; gap: 24px; flex-wrap: wrap; align-items: center;">
        <div><strong>当前象限：</strong>{{ regime_result.quadrant }}</div>
        <div><strong>判定置信度：</strong>{{ regime_result.confidence|default:0|floatformat:2 }}</div>
    </div>
</div>

<div class="regime-cards">
    <!-- Recovery 复苏 -->
    <div class="regime-card recovery {% if regime_result.quadrant == 'Recovery' %}active{% endif %}">
        <div class="regime-card-icon">🌱</div>
        <div class="regime-card-title">Recovery 复苏</div>
        <div class="regime-card-score">{{ regime_result.distribution.Recovery|default:0|floatformat:2 }}</div>
        <div class="regime-card-description">
            增长上行，通胀下行<br>
            PMI > 50，CPI 同比下降
        </div>
    </div>

    <!-- Overheat 过热 -->
    <div class="regime-card overheat {% if regime_result.quadrant == 'Overheat' %}active{% endif %}">
        <div class="regime-card-icon">🔥</div>
        <div class="regime-card-title">Overheat 过热</div>
        <div class="regime-card-score">{{ regime_result.distribution.Overheat|default:0|floatformat:2 }}</div>
        <div class="regime-card-description">
            增长上行，通胀上行<br>
            PMI > 50，CPI 同比上升
        </div>
    </div>

    <!-- Deflation 通缩 -->
    <div class="regime-card deflation {% if regime_result.quadrant == 'Deflation' %}active{% endif %}">
        <div class="regime-card-icon">❄️</div>
        <div class="regime-card-title">Deflation 通缩</div>
        <div class="regime-card-score">{{ regime_result.distribution.Deflation|default:0|floatformat:2 }}</div>
        <div class="regime-card-description">
            增长下行，通胀下行<br>
            PMI < 50，CPI 同比下降
        </div>
    </div>

    <!-- Stagflation 滞胀 -->
    <div class="regime-card stagflation {% if regime_result.quadrant == 'Stagflation' %}active{% endif %}">
        <div class="regime-card-icon">⚠️</div>
        <div class="regime-card-title">Stagflation 滞胀</div>
        <div class="regime-card-score">{{ regime_result.distribution.Stagflation|default:0|floatformat:2 }}</div>
        <div class="regime-card-description">
            增长下行，通胀上行<br>
            PMI < 50，CPI 同比上升
        </div>
    </div>
</div>

<!-- 指标图表 -->
<div class="charts-container">
    <div class="chart-card">
        <div class="chart-card-title">增长指标 (PMI)</div>
        <div id="growthChart" class="chart-canvas"></div>
    </div>
    <div class="chart-card">
        <div class="chart-card-title">通胀指标 (CPI 同比)</div>
        <div id="inflationChart" class="chart-canvas"></div>
    </div>
</div>

<div id="navigatorHistorySection" class="card" style="margin-bottom: 20px;">
    <div class="card-header" style="display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap;">
        <div>
            <h3 class="card-header-title">历史 Regime + Pulse 叠加时序图</h3>
            <p style="margin: 6px 0 0; color: var(--text-secondary);">上方为 Regime 象限带，中间为 Pulse 脉搏，下方为行动建议资产权重。</p>
        </div>
        <div style="display: flex; gap: 8px; align-items: center;">
            <label for="historyMonthsSelect">时间范围</label>
            <select id="historyMonthsSelect">
                <option value="3">近 3 个月</option>
                <option value="6">近 6 个月</option>
                <option value="12" selected>近 12 个月</option>
                <option value="24">近 24 个月</option>
            </select>
        </div>
    </div>
    <div class="card-body">
        <div id="navigatorHistoryChart" class="chart-canvas" style="height: 560px;"></div>
        <div id="navigatorHistoryEmpty" class="empty-state" style="display: none;">
            <div class="empty-icon">🕰️</div>
            <p>当前时间范围内暂无可用的 Regime / Pulse / Action 历史数据</p>
        </div>
    </div>
</div>

<!-- 判定详情 -->
<div class="card">
    <div class="card-header">
        <h3 class="card-header-title">判定详情</h3>
    </div>
    <div class="card-body">
        <table class="table">
            <tr>
                <th>指标</th>
                <th>当前值</th>
                <th>阈值</th>
                <th>趋势</th>
            </tr>
            <tr>
                <td>当前主导象限</td>
                <td>{{ regime_result.quadrant }}</td>
                <td>-</td>
                <td><span class="badge badge-neutral">{{ regime_result.confidence|default:0|floatformat:2 }}</span></td>
            </tr>
            <tr>
                <td>PMI (制造业采购经理指数)</td>
                <td>{{ regime_result.pmi_value|default:"-" }}</td>
                <td>50</td>
                <td>
                    {% if regime_result.pmi_trend == 'up' %}
                        <span class="badge badge-success">↑ 上升</span>
                    {% elif regime_result.pmi_trend == 'down' %}
                        <span class="badge badge-error">↓ 下降</span>
                    {% else %}
                        <span class="badge badge-neutral">→ 持平</span>
                    {% endif %}
                </td>
            </tr>
            <tr>
                <td>CPI 同比</td>
                <td>{{ regime_result.cpi_value|default:"-" }}%</td>
                <td>前值</td>
                <td>
                    {% if regime_result.cpi_trend == 'up' %}
                        <span class="badge badge-warning">↑ 上升</span>
                    {% elif regime_result.cpi_trend == 'down' %}
                        <span class="badge badge-success">↓ 下降</span>
                    {% else %}
                        <span class="badge badge-neutral">→ 持平</span>
                    {% endif %}
                </td>
            </tr>
        </table>
    </div>
</div>

{% if raw_data %}
<div class="card">
    <div class="card-header">
        <h3 class="card-header-title">原始数据明细（最近12期）</h3>
    </div>
    <div class="card-body" style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
        <div>
            <h4 style="margin-bottom: 8px;">PMI</h4>
            <table class="table">
                <tr>
                    <th>日期</th>
                    <th>值</th>
                </tr>
                {% for item in raw_data.growth|slice:"-12:" %}
                <tr>
                    <td>{{ item.date }}</td>
                    <td>{{ item.value }}</td>
                </tr>
                {% endfor %}
            </table>
        </div>
        <div>
            <h4 style="margin-bottom: 8px;">CPI</h4>
            <table class="table">
                <tr>
                    <th>日期</th>
                    <th>值</th>
                </tr>
                {% for item in raw_data.inflation|slice:"-12:" %}
                <tr>
                    <td>{{ item.date }}</td>
                    <td>{{ item.value }}</td>
                </tr>
                {% endfor %}
            </table>
        </div>
    </div>
</div>
{% endif %}

<script src="{% static 'vendor/js/echarts.min.js' %}"></script>
<script>
// 使用 ECharts 绘制图表
if (typeof echarts !== 'undefined') {
    // 增长指标图表
    const growthChart = echarts.init(document.getElementById('growthChart'));
    growthChart.setOption({
        xAxis: {
            type: 'category',
            data: {{ regime_result.growth_dates|default:"[]"|safe }}
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            data: {{ regime_result.growth_values|default:"[]"|safe }},
            type: 'line',
            smooth: true,
            lineStyle: {
                color: '#3366CC'
            },
            areaStyle: {
                color: 'rgba(51, 102, 204, 0.1)'
            }
        }]
    });

    // 通胀指标图表
    const inflationChart = echarts.init(document.getElementById('inflationChart'));
    inflationChart.setOption({
        xAxis: {
            type: 'category',
            data: {{ regime_result.inflation_dates|default:"[]"|safe }}
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            data: {{ regime_result.inflation_values|default:"[]"|safe }},
            type: 'line',
            smooth: true,
            lineStyle: {
                color: '#DD3333'
            },
            areaStyle: {
                color: 'rgba(221, 51, 51, 0.1)'
            }
        }]
    });

    // 响应式处理
    window.addEventListener('resize', () => {
        growthChart.resize();
        inflationChart.resize();
    });
}

if (typeof echarts !== 'undefined') {
    const historyContainer = document.getElementById('navigatorHistoryChart');
    const historyEmptyState = document.getElementById('navigatorHistoryEmpty');
    const historyMonthsSelect = document.getElementById('historyMonthsSelect');
    const historyChart = echarts.init(historyContainer);
    const regimeColors = {
        Recovery: '#10B981',
        Overheat: '#EF4444',
        Stagflation: '#F59E0B',
        Deflation: '#3B82F6',
        Unknown: '#94A3B8',
    };

    function buildTimeline(historyData) {
        const dates = new Set();
        (historyData.pulse_history || []).forEach(item => dates.add(item.date));
        (historyData.action_history || []).forEach(item => dates.add(item.date));
        (historyData.regime_transitions || []).forEach(item => dates.add(item.date));
        return Array.from(dates).sort();
    }

    function buildRegimeBand(dates, transitions) {
        if (!dates.length) {
            return [];
        }

        const sortedTransitions = [...(transitions || [])].sort((a, b) => a.date.localeCompare(b.date));
        let cursor = 0;
        let currentRegime = sortedTransitions.length ? (sortedTransitions[0].to_regime || 'Unknown') : 'Unknown';

        return dates.map(currentDate => {
            while (cursor + 1 < sortedTransitions.length && sortedTransitions[cursor + 1].date <= currentDate) {
                cursor += 1;
                currentRegime = sortedTransitions[cursor].to_regime || 'Unknown';
            }
            return currentRegime;
        });
    }

    function valueByDate(items, valueKey, dates) {
        const lookup = new Map((items || []).map(item => [item.date, item[valueKey]]));
        return dates.map(itemDate => {
            const value = lookup.get(itemDate);
            return value === undefined || value === null ? null : value;
        });
    }

    function percentageByDate(items, valueKey, dates) {
        return valueByDate(items, valueKey, dates).map(value => value === null ? null : Number(value) * 100);
    }

    function renderHistoryChart(historyData) {
        const dates = buildTimeline(historyData);
        if (!dates.length) {
            historyContainer.style.display = 'none';
            historyEmptyState.style.display = 'flex';
            historyChart.clear();
            return;
        }

        historyContainer.style.display = 'block';
        historyEmptyState.style.display = 'none';

        const regimeBand = buildRegimeBand(dates, historyData.regime_transitions || []);

        historyChart.setOption({
            animation: false,
            tooltip: {
                trigger: 'axis',
            },
            legend: {
                top: 8,
                data: ['Regime', 'Pulse 综合', '增长', '通胀', '流动性', '情绪', '权益', '债券', '商品', '现金'],
            },
            grid: [
                { left: 56, right: 24, top: 56, height: 70 },
                { left: 56, right: 24, top: 170, height: 150 },
                { left: 56, right: 24, top: 370, height: 140 },
            ],
            xAxis: [
                { type: 'category', gridIndex: 0, data: dates, axisLabel: { show: false } },
                { type: 'category', gridIndex: 1, data: dates, axisLabel: { show: false } },
                { type: 'category', gridIndex: 2, data: dates, axisLabel: { rotate: 45 } },
            ],
            yAxis: [
                { type: 'value', gridIndex: 0, min: 0, max: 1, axisLabel: { show: false }, splitLine: { show: false } },
                { type: 'value', gridIndex: 1, min: -1, max: 1, name: 'Pulse', splitLine: { lineStyle: { type: 'dashed' } } },
                { type: 'value', gridIndex: 2, min: 0, max: 100, name: '权重%', splitLine: { lineStyle: { type: 'dashed' } } },
            ],
            series: [
                {
                    name: 'Regime',
                    type: 'bar',
                    xAxisIndex: 0,
                    yAxisIndex: 0,
                    data: regimeBand.map(regime => ({
                        value: 1,
                        itemStyle: { color: regimeColors[regime] || regimeColors.Unknown },
                    })),
                    barCategoryGap: '0%',
                    silent: true,
                    label: {
                        show: true,
                        position: 'inside',
                        color: '#fff',
                        fontSize: 10,
                        formatter: params => regimeBand[params.dataIndex],
                    },
                },
                {
                    name: 'Pulse 综合',
                    type: 'line',
                    smooth: true,
                    xAxisIndex: 1,
                    yAxisIndex: 1,
                    data: valueByDate(historyData.pulse_history, 'composite_score', dates),
                    lineStyle: { width: 3, color: '#111827' },
                },
                {
                    name: '增长',
                    type: 'line',
                    smooth: true,
                    xAxisIndex: 1,
                    yAxisIndex: 1,
                    data: valueByDate(historyData.pulse_history, 'growth_score', dates),
                    lineStyle: { color: '#2563EB' },
                },
                {
                    name: '通胀',
                    type: 'line',
                    smooth: true,
                    xAxisIndex: 1,
                    yAxisIndex: 1,
                    data: valueByDate(historyData.pulse_history, 'inflation_score', dates),
                    lineStyle: { color: '#DC2626' },
                },
                {
                    name: '流动性',
                    type: 'line',
                    smooth: true,
                    xAxisIndex: 1,
                    yAxisIndex: 1,
                    data: valueByDate(historyData.pulse_history, 'liquidity_score', dates),
                    lineStyle: { color: '#059669' },
                },
                {
                    name: '情绪',
                    type: 'line',
                    smooth: true,
                    xAxisIndex: 1,
                    yAxisIndex: 1,
                    data: valueByDate(historyData.pulse_history, 'sentiment_score', dates),
                    lineStyle: { color: '#7C3AED' },
                },
                {
                    name: '权益',
                    type: 'line',
                    stack: 'allocation',
                    areaStyle: {},
                    smooth: true,
                    xAxisIndex: 2,
                    yAxisIndex: 2,
                    data: percentageByDate(historyData.action_history, 'equity_weight', dates),
                    lineStyle: { color: '#2563EB' },
                },
                {
                    name: '债券',
                    type: 'line',
                    stack: 'allocation',
                    areaStyle: {},
                    smooth: true,
                    xAxisIndex: 2,
                    yAxisIndex: 2,
                    data: percentageByDate(historyData.action_history, 'bond_weight', dates),
                    lineStyle: { color: '#0F766E' },
                },
                {
                    name: '商品',
                    type: 'line',
                    stack: 'allocation',
                    areaStyle: {},
                    smooth: true,
                    xAxisIndex: 2,
                    yAxisIndex: 2,
                    data: percentageByDate(historyData.action_history, 'commodity_weight', dates),
                    lineStyle: { color: '#D97706' },
                },
                {
                    name: '现金',
                    type: 'line',
                    stack: 'allocation',
                    areaStyle: {},
                    smooth: true,
                    xAxisIndex: 2,
                    yAxisIndex: 2,
                    data: percentageByDate(historyData.action_history, 'cash_weight', dates),
                    lineStyle: { color: '#6B7280' },
                },
            ],
        });
    }

    async function loadNavigatorHistory(months) {
        try {
            const response = await fetch(`{% url "regime_api:regime-navigator-history" %}?months=${months}`);
            const payload = await response.json();
            renderHistoryChart(payload.data || {});
        } catch (error) {
            historyContainer.style.display = 'none';
            historyEmptyState.style.display = 'flex';
            historyEmptyState.querySelector('p').textContent = `历史叠加图加载失败: ${error.message}`;
        }
    }

    historyMonthsSelect.addEventListener('change', () => loadNavigatorHistory(historyMonthsSelect.value));
    loadNavigatorHistory(historyMonthsSelect.value);

    window.addEventListener('resize', () => {
        historyChart.resize();
    });
}
</script>

{% else %}
<div class="empty-state">
    <div class="empty-icon">📊</div>
    <p>暂无 Regime 判定数据，请同步宏观数据</p>
</div>
{% endif %}

<!-- Teaching Module Scripts -->
<script src="{% static 'js/teaching/teaching-modal.js' %}"></script>
<script src="{% static 'js/teaching/regime-calculator.js' %}"></script>
<script src="{% static 'js/teaching/policy-simulator.js' %}"></script>
<script src="{% static 'js/teaching/policy-simulator-enhanced.js' %}"></script>
<script src="{% static 'js/teaching/cases-library.js' %}"></script>
<script src="{% static 'js/teaching/learning-progress.js' %}"></script>
<script src="{% static 'js/teaching/interactive-charts.js' %}"></script>
<script src="{% static 'js/teaching/bilingual-support.js' %}"></script>

<!-- Teaching Modal Template -->
{% include "dashboard/teaching_modal.html" %}

{% endblock %}
