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

{% block title %}配置版本对比 - Beta Gate{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'css/beta-gate.css' %}">
{% endblock %}

{% block content %}

<div class="version-compare-container">
    <!-- 头部 -->
    <div class="version-header">
        <div>
            <h1>配置版本对比</h1>
            <p style="color: #64748b; margin-top: 4px;">查看和对比 Beta Gate 配置历史版本</p>
        </div>
        <div style="display: flex; gap: 10px;">
            <a href="{% url 'beta_gate:config_new' %}" class="btn-compare" style="text-decoration: none;">
                <i class="bi bi-plus-lg"></i> 新建配置
            </a>
            <a href="{% url 'beta_gate:config' %}" class="btn-compare" style="text-decoration: none;">
                <i class="bi bi-arrow-left"></i> 返回配置
            </a>
        </div>
    </div>

    {% if error %}
    <div class="alert alert-danger">
        <i class="bi bi-exclamation-triangle"></i> {{ error }}
    </div>
    {% endif %}

    <!-- 版本列表 -->
    <div class="version-list">
        <div style="padding: 16px 20px; border-bottom: 1px solid #e2e8f0; font-weight: 600; font-size: 14px; color: #334155;">
            <i class="bi bi-clock-history"></i> 配置历史版本 ({{ versions|length }} 个)
        </div>
        {% if versions %}
        <table class="version-table">
            <thead>
                <tr>
                    <th>版本 ID</th>
                    <th>风险画像</th>
                    <th>版本号</th>
                    <th>状态</th>
                    <th>生效日期</th>
                    <th>过期日期</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for version in versions %}
                <tr>
                    <td><span class="version-id">{{ version.config_id }}</span></td>
                    <td><span class="risk-badge {{ version.risk_profile }}">{{ version.get_risk_profile_display }}</span></td>
                    <td>v{{ version.version }}</td>
                    <td>
                        {% if version.is_active %}
                            {% if version.is_expired %}
                                <span class="status-badge expired">已过期</span>
                            {% else %}
                                <span class="status-badge active">激活</span>
                            {% endif %}
                        {% else %}
                            <span class="status-badge inactive">未激活</span>
                        {% endif %}
                    </td>
                    <td>{{ version.effective_date|date:"Y-m-d" }}</td>
                    <td>{{ version.expires_at|date:"Y-m-d"|default:"永不过期" }}</td>
                    <td>{{ version.created_at|date:"Y-m-d H:i" }}</td>
                    <td>
                        <button class="btn-compare" style="padding: 6px 12px; font-size: 12px; margin: 0;" onclick="selectForCompare('{{ version.config_id }}')">
                            选择对比
                        </button>
                        <a class="btn-compare" style="padding: 6px 12px; font-size: 12px; margin-left: 8px; text-decoration: none;" href="{% url 'beta_gate:config_edit' version.config_id %}">
                            编辑
                        </a>
                        {% if not version.is_active %}
                        <form method="post" action="{% url 'beta_gate:config_activate' version.config_id %}" style="display: inline;">
                            {% csrf_token %}
                            <button type="submit" class="btn-rollback" style="padding: 6px 12px; font-size: 12px; margin-left: 8px;">
                                激活
                            </button>
                        </form>
                        {% endif %}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
        {% else %}
        <div class="empty-state">
            <div class="empty-state-icon">📋</div>
            <div>暂无历史版本</div>
        </div>
        {% endif %}
    </div>

    <!-- 对比选择器 -->
    <div class="version-selector">
        <div class="selector-group">
            <label><i class="bi bi-arrow-counterclockwise"></i> 基准版本 (旧)</label>
            <select id="versionA">
                <option value="">-- 选择基准版本 --</option>
                {% for version in versions %}
                <option value="{{ version.config_id }}" {% if forloop.first %}selected{% endif %}>
                    v{{ version.version }} - {{ version.get_risk_profile_display }} ({{ version.created_at|date:"Y-m-d" }})
                </option>
                {% endfor %}
            </select>
        </div>
        <div class="selector-group">
            <label><i class="bi bi-arrow-clockwise"></i> 对比版本 (新)</label>
            <select id="versionB">
                <option value="">-- 选择对比版本 --</option>
                {% for version in versions %}
                <option value="{{ version.config_id }}" {% if forloop.last %}selected{% endif %}>
                    v{{ version.version }} - {{ version.get_risk_profile_display }} ({{ version.created_at|date:"Y-m-d" }})
                </option>
                {% endfor %}
            </select>
        </div>
    </div>
    <div style="text-align: center;">
        <button class="btn-compare" onclick="compareVersions()">
            <i class="bi bi-arrows-collapse"></i> 开始对比
        </button>
    </div>

    <!-- 对比结果 -->
    <div id="compareResult" class="compare-result">
        <div style="margin-top: 32px;">
            <h3 style="font-size: 18px; margin-bottom: 16px;">
                <i class="bi bi-files"></i> 对比结果
            </h3>
        </div>

        <div class="compare-grid">
            <!-- 版本 A -->
            <div class="compare-panel">
                <div class="compare-panel-header">
                    <span class="compare-panel-title">基准版本 (旧)</span>
                    <span class="compare-panel-version" id="panelVersionA">--</span>
                </div>
                <div id="panelContentA">
                    <div style="color: #94a3b8; text-align: center; padding: 20px;">请选择版本</div>
                </div>
            </div>

            <!-- 版本 B -->
            <div class="compare-panel">
                <div class="compare-panel-header">
                    <span class="compare-panel-title">对比版本 (新)</span>
                    <span class="compare-panel-version" id="panelVersionB">--</span>
                </div>
                <div id="panelContentB">
                    <div style="color: #94a3b8; text-align: center; padding: 20px;">请选择版本</div>
                </div>
            </div>
        </div>

        <!-- 差异摘要 -->
        <div id="diffSummary" class="compare-panel" style="margin-bottom: 24px;">
            <h4 style="font-size: 14px; font-weight: 600; margin: 0 0 16px 0;">
                <i class="bi bi-exclamation-circle"></i> 差异摘要
            </h4>
            <div id="diffSummaryContent">
                <div style="color: #94a3b8;">暂无差异</div>
            </div>
        </div>
    </div>
</div>

<script>
let compareData = null;

// 选择版本快速对比
function selectForCompare(configId) {
    const currentA = document.getElementById('versionA').value;
    const currentB = document.getElementById('versionB').value;

    if (!currentA) {
        document.getElementById('versionA').value = configId;
    } else if (!currentB) {
        document.getElementById('versionB').value = configId;
    } else {
        // 两个都已选择，替换 B
        document.getElementById('versionB').value = configId;
    }
}

// 执行对比
async function compareVersions() {
    const versionA = document.getElementById('versionA').value;
    const versionB = document.getElementById('versionB').value;

    if (!versionA || !versionB) {
        showToast('请选择两个版本进行对比', 'warning');
        return;
    }

    if (versionA === versionB) {
        showToast('请选择不同的版本进行对比', 'warning');
        return;
    }

    try {
        showToast('正在对比版本...', 'info');

        const res = await fetch(`{% url 'beta_gate:api_version_compare' %}?version1=${encodeURIComponent(versionA)}&version2=${encodeURIComponent(versionB)}`);
        const data = await res.json();

        if (data.success) {
            compareData = data;
            renderCompareResult(data);
            document.getElementById('compareResult').classList.add('show');
            showToast('对比完成', 'success');
        } else {
            showToast('对比失败: ' + (data.error || '未知错误'), 'error');
        }
    } catch (e) {
        showToast('网络错误: ' + e.message, 'error');
    }
}

// 渲染对比结果
function renderCompareResult(data) {
    // 更新版本信息
    document.getElementById('panelVersionA').textContent = `v${data.config1.version} - ${data.config1.risk_profile}`;
    document.getElementById('panelVersionB').textContent = `v${data.config2.version} - ${data.config2.risk_profile}`;

    // 渲染面板内容
    renderConfigPanel('panelContentA', data.config1, data.differences);
    renderConfigPanel('panelContentB', data.config2, data.differences, true);

    // 渲染差异摘要
    renderDiffSummary(data.differences);
}

// 渲染配置面板
function renderConfigPanel(containerId, config, differences, highlightNew = false) {
    const container = document.getElementById(containerId);
    const changedFields = differences.map(d => d.field);

    let html = '';

    // 基本信息
    html += '<div class="config-section">';
    html += '<h4>基本信息</h4>';
    html += renderConfigItem('配置 ID', config.config_id, changedFields, 'config_id', highlightNew);
    html += renderConfigItem('风险画像', config.risk_profile, changedFields, 'risk_profile', highlightNew);
    html += renderConfigItem('版本号', config.version, changedFields, 'version', highlightNew);
    html += renderConfigItem('是否激活', config.is_active ? '是' : '否', changedFields, 'is_active', highlightNew);
    html += renderConfigItem('生效日期', config.effective_date, changedFields, 'effective_date', highlightNew);
    html += renderConfigItem('过期日期', config.expires_at || '永不过期', changedFields, 'expires_at', highlightNew);
    html += '</div>';

    // Regime 约束
    html += '<div class="config-section">';
    html += '<h4>Regime 约束</h4>';
    if (config.regime_constraints) {
        Object.entries(config.regime_constraints).forEach(([key, value]) => {
            html += renderConfigItem(
                formatConfigKey(key),
                formatConfigValue(value),
                changedFields,
                `regime_constraints.${key}`,
                highlightNew
            );
        });
    } else {
        html += '<div style="color: #94a3b8; font-size: 13px;">无配置</div>';
    }
    html += '</div>';

    // Policy 约束
    html += '<div class="config-section">';
    html += '<h4>Policy 约束</h4>';
    if (config.policy_constraints) {
        Object.entries(config.policy_constraints).forEach(([key, value]) => {
            html += renderConfigItem(
                formatConfigKey(key),
                formatConfigValue(value),
                changedFields,
                `policy_constraints.${key}`,
                highlightNew
            );
        });
    } else {
        html += '<div style="color: #94a3b8; font-size: 13px;">无配置</div>';
    }
    html += '</div>';

    // 组合约束
    html += '<div class="config-section">';
    html += '<h4>组合约束</h4>';
    if (config.portfolio_constraints) {
        Object.entries(config.portfolio_constraints).forEach(([key, value]) => {
            html += renderConfigItem(
                formatConfigKey(key),
                formatConfigValue(value),
                changedFields,
                `portfolio_constraints.${key}`,
                highlightNew
            );
        });
    } else {
        html += '<div style="color: #94a3b8; font-size: 13px;">无配置</div>';
    }
    html += '</div>';

    container.innerHTML = html;
}

// 渲染配置项
function renderConfigItem(key, value, changedFields, fieldPath, highlightNew) {
    const isChanged = changedFields.includes(fieldPath);
    const changeClass = isChanged ? 'changed' : '';
    const valueClass = isChanged ? (highlightNew ? 'diff-added' : 'diff-changed') : '';

    return `
        <div class="config-item ${changeClass}">
            <span class="config-item-key">${key}</span>
            <span class="config-item-value ${valueClass}">${value}</span>
        </div>
    `;
}

// 渲染差异摘要
function renderDiffSummary(differences) {
    const container = document.getElementById('diffSummaryContent');

    if (differences.length === 0) {
        container.innerHTML = '<div style="color: #10b981;"><i class="bi bi-check-circle"></i> 两个版本完全相同</div>';
        return;
    }

    let html = `<div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px;">`;

    differences.forEach(diff => {
        html += `
            <div style="padding: 12px; background: #fef3c7; border-radius: 6px; border-left: 3px solid #f59e0b;">
                <div style="font-weight: 600; font-size: 13px; color: #92400e; margin-bottom: 4px;">
                    ${formatConfigKey(diff.field)}
                </div>
                <div style="font-size: 12px; color: #64748b;">
                    <span class="diff-removed">${formatConfigValue(diff.old_value)}</span>
                    <i class="bi bi-arrow-right" style="margin: 0 8px;"></i>
                    <span class="diff-added">${formatConfigValue(diff.new_value)}</span>
                </div>
            </div>
        `;
    });

    html += '</div>';
    container.innerHTML = html;
}

// 格式化配置键
function formatConfigKey(key) {
    const keyMap = {
        'config_id': '配置 ID',
        'risk_profile': '风险画像',
        'version': '版本号',
        'is_active': '是否激活',
        'effective_date': '生效日期',
        'expires_at': '过期日期',
        'regime_constraints': 'Regime 约束',
        'policy_constraints': 'Policy 约束',
        'portfolio_constraints': '组合约束',
        'allowed_regimes': '允许的 Regime',
        'min_regime_confidence': '最小 Regime 置信度',
        'allowed_policy_levels': '允许的 Policy 档位',
        'max_single_asset_weight': '单资产最大权重',
        'max_sector_weight': '单行业最大权重',
        'min_diversification_score': '最小分散化得分',
        'max_concentration_ratio': '最大集中度比率'
    };

    // 处理嵌套键
    if (key.includes('.')) {
        const parts = key.split('.');
        return formatConfigKey(parts[1] || key);
    }

    return keyMap[key] || key;
}

// 格式化配置值
function formatConfigValue(value) {
    if (value === null || value === undefined) {
        return '-';
    }
    if (typeof value === 'boolean') {
        return value ? '是' : '否';
    }
    if (Array.isArray(value)) {
        return value.join(', ');
    }
    if (typeof value === 'object') {
        return JSON.stringify(value);
    }
    return String(value);
}

// 回滚到指定版本
async function rollbackTo(configId) {
    if (!confirm(`确认要回滚到版本 ${configId}？\n\n当前激活的配置将被停用，所选版本将成为激活状态。`)) {
        return;
    }

    try {
        showToast('正在回滚配置...', 'info');

        const res = await fetch(`{% url 'beta_gate:api_rollback' 'PLACEHOLDER' %}`.replace('PLACEHOLDER', configId), {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
        });

        const data = await res.json();

        if (data.success) {
            showToast('配置已回滚', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('回滚失败: ' + (data.error || '未知错误'), 'error');
        }
    } catch (e) {
        showToast('网络错误: ' + e.message, 'error');
    }
}

// Toast 提示
function showToast(message, type = 'info') {
    // 简单的 toast 实现
    const colors = {
        success: '#10b981',
        error: '#ef4444',
        warning: '#f59e0b',
        info: '#3b82f6'
    };

    const toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 20px;
        background: ${colors[type]};
        color: white;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 9999;
        animation: slideIn 0.3s ease-out;
    `;
    toast.textContent = message;

    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// 页面加载完成后自动对比选中的版本
document.addEventListener('DOMContentLoaded', function() {
    const versionA = document.getElementById('versionA').value;
    const versionB = document.getElementById('versionB').value;

    if (versionA && versionB && versionA !== versionB) {
        compareVersions();
    }
});
</script>

<style>
@keyframes slideIn {
    from { transform: translateX(100%); opacity: 0; }
    to { transform: translateX(0); opacity: 1; }
}
</style>
{% endblock %}
