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

{% block title %}决策配额配置 - AgomTradePro{% endblock %}

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

{% block content %}
{% csrf_token %}
<div class="config-container">
    <!-- 头部 -->
    <div class="config-header">
        <div>
            <h1>决策配额配置</h1>
            <p class="config-subtitle">配置和管理决策频率约束参数</p>
        </div>
        <a href="{% url 'decision_rhythm:quota' %}" class="btn-secondary">
            <i class="bi bi-arrow-left"></i> 返回配额概览
        </a>
    </div>

    <!-- 账户选择器 -->
    <div class="account-selector-bar">
        <div class="account-selector-label">
            <i class="bi bi-wallet2"></i> 选择账户
        </div>
        <select id="accountSelector" class="account-selector" onchange="onAccountChange()">
            {% for acc in accounts %}
            <option value="{{ acc.id }}" {% if current_account_id == acc.id|stringformat:"s" %}selected{% endif %}>
                {{ acc.account_name }}（{% if acc.account_type == "real" %}实仓{% else %}模拟仓{% endif %}）
            </option>
            {% empty %}
            <option value="default">默认账户</option>
            {% endfor %}
        </select>
        <span class="account-selector-hint">不同账户可独立配置配额限制</span>
    </div>

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

    <!-- 配额卡片 -->
    <div class="quota-grid">
        {% for period_value, period_label in period_choices %}
        <div class="quota-card" id="quota-{{ period_value }}">
            <div class="quota-card-header">
                <span class="quota-period">{{ period_label }}</span>
                <span class="quota-badge {{ period_value }}">{{ period_value }}</span>
            </div>

            {% with current_quota=None %}
            {% for q in quotas %}
            {% if q.period == period_value %}

            <!-- 配额统计 -->
            <div class="quota-stats">
                <div class="quota-stat">
                    <div class="quota-stat-value" id="used-{{ period_value }}">{{ q.used_decisions }}</div>
                    <div class="quota-stat-label">已使用决策</div>
                </div>
                <div class="quota-stat">
                    <div class="quota-stat-value" id="total-{{ period_value }}">{{ q.max_decisions }}</div>
                    <div class="quota-stat-label">最大决策数</div>
                </div>
                <div class="quota-stat">
                    <div class="quota-stat-value" id="executed-{{ period_value }}">{{ q.used_executions }}</div>
                    <div class="quota-stat-label">已执行</div>
                </div>
                <div class="quota-stat">
                    <div class="quota-stat-value" id="max-exec-{{ period_value }}">{{ q.max_execution_count }}</div>
                    <div class="quota-stat-label">最大执行数</div>
                </div>
            </div>

            <!-- 使用率进度条 -->
            {% widthratio q.used_decisions q.max_decisions 100 as usage_pct %}
            <div class="progress-bar">
                <div class="progress-fill {% if usage_pct < 50 %}low{% elif usage_pct < 80 %}medium{% else %}high{% endif %}" style="width: {{ usage_pct }}%;"></div>
            </div>
            <div class="progress-label">使用率: {{ usage_pct }}%</div>

            <!-- 配置表单 -->
            <div class="config-form">
                <div class="form-row-config">
                    <div class="form-field">
                        <label class="form-label">最大决策数</label>
                        <input type="number" class="form-input" id="max-decisions-{{ period_value }}"
                            value="{{ q.max_decisions }}" min="1" max="100">
                    </div>
                    <div class="form-field">
                        <label class="form-label">最大执行数</label>
                        <input type="number" class="form-input" id="max-executions-{{ period_value }}"
                            value="{{ q.max_execution_count }}" min="1" max="50">
                    </div>
                    <button class="btn-update" onclick="updateQuota('{{ period_value }}')">
                        <i class="bi bi-check"></i> 更新
                    </button>
                </div>
                <div class="form-actions">
                    <button class="btn-reset" onclick="resetQuota('{{ period_value }}')">
                        <i class="bi bi-arrow-clockwise"></i> 重置计数
                    </button>
                </div>
            </div>

            {% endif %}
            {% endfor %}
            {% endwith %}

            <!-- 无配额数据时显示默认表单 -->
            {% with has_quota=False %}
            {% for q in quotas %}{% if q.period == period_value %}{% with has_quota=True %}{% endwith %}{% endif %}{% endfor %}
            {% if not has_quota %}
            <div class="quota-stats">
                <div class="quota-stat">
                    <div class="quota-stat-value" id="used-{{ period_value }}">0</div>
                    <div class="quota-stat-label">已使用决策</div>
                </div>
                <div class="quota-stat">
                    <div class="quota-stat-value" id="total-{{ period_value }}">10</div>
                    <div class="quota-stat-label">最大决策数</div>
                </div>
                <div class="quota-stat">
                    <div class="quota-stat-value" id="executed-{{ period_value }}">0</div>
                    <div class="quota-stat-label">已执行</div>
                </div>
                <div class="quota-stat">
                    <div class="quota-stat-value" id="max-exec-{{ period_value }}">5</div>
                    <div class="quota-stat-label">最大执行数</div>
                </div>
            </div>

            <div class="config-form">
                <div class="form-row-config">
                    <div class="form-field">
                        <label class="form-label">最大决策数</label>
                        <input type="number" class="form-input" id="max-decisions-{{ period_value }}"
                            value="10" min="1" max="100">
                    </div>
                    <div class="form-field">
                        <label class="form-label">最大执行数</label>
                        <input type="number" class="form-input" id="max-executions-{{ period_value }}"
                            value="5" min="1" max="50">
                    </div>
                    <button class="btn-update" onclick="updateQuota('{{ period_value }}')">
                        <i class="bi bi-check"></i> 更新
                    </button>
                </div>
                <div class="form-actions">
                    <button class="btn-reset" onclick="resetQuota('{{ period_value }}')">
                        <i class="bi bi-arrow-clockwise"></i> 重置计数
                    </button>
                </div>
            </div>
            {% endif %}
            {% endwith %}

        </div>
        {% endfor %}
    </div>

    <!-- 使用趋势图表 -->
    <div class="history-section">
        <div class="trend-header">
            <h3>
                <i class="bi bi-graph-up"></i> 配额使用趋势
            </h3>
            <div class="trend-buttons">
                <button class="btn-trend active" id="btn-7d" onclick="loadTrendData('7')">近7天</button>
                <button class="btn-trend" id="btn-30d" onclick="loadTrendData('30')">近30天</button>
            </div>
        </div>

        <!-- 趋势图表容器 -->
        <div id="trendChartContainer">
            <div class="trend-charts-row">
                <div class="trend-chart-wrapper">
                    <h4>每日决策使用量</h4>
                    <div id="dailyDecisionsChart" class="trend-chart"></div>
                </div>
            </div>
            <div class="trend-charts-row">
                <div class="trend-chart-wrapper">
                    <h4>每日执行使用量</h4>
                    <div id="dailyExecutionsChart" class="trend-chart"></div>
                </div>
            </div>
        </div>

        <!-- 统计摘要 -->
        <div class="trend-summary">
            <div class="trend-summary-grid">
                <div class="trend-summary-item">
                    <div class="trend-summary-value" style="color: var(--color-primary);" id="avgDailyDecisions">-</div>
                    <div class="trend-summary-label">平均每日决策</div>
                </div>
                <div class="trend-summary-item">
                    <div class="trend-summary-value" style="color: var(--color-success);" id="maxDailyDecisions">-</div>
                    <div class="trend-summary-label">峰值决策数</div>
                </div>
                <div class="trend-summary-item">
                    <div class="trend-summary-value" style="color: var(--color-warning);" id="avgDailyExecutions">-</div>
                    <div class="trend-summary-label">平均每日执行</div>
                </div>
                <div class="trend-summary-item">
                    <div class="trend-summary-value" style="color: var(--color-error);" id="overLimitDays">-</div>
                    <div class="trend-summary-label">超限天数</div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 获取当前选中的账户 ID
function getAccountId() {
    const selector = document.getElementById('accountSelector');
    return selector ? selector.value : 'default';
}

// 账户切换 — 刷新页面以加载该账户的配额数据
function onAccountChange() {
    const accountId = getAccountId();
    const url = new URL(window.location.href);
    url.searchParams.set('account_id', accountId);
    window.location.href = url.toString();
}

// 获取 CSRF token
function getCsrfToken() {
    const cookie = document.cookie.split(';').find(c => c.trim().startsWith('csrftoken='));
    return cookie ? cookie.split('=')[1] : '';
}

async function updateQuota(period) {
    const maxDecisions = parseInt(document.getElementById(`max-decisions-${period}`).value);
    const maxExecutions = parseInt(document.getElementById(`max-executions-${period}`).value);

    if (isNaN(maxDecisions) || isNaN(maxExecutions) || maxDecisions < 1 || maxExecutions < 1) {
        showToast('请输入有效的数值（最小为1）', 'warning');
        return;
    }

    try {
        const res = await fetch("{% url 'decision_rhythm:api_update_quota' %}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken(),
            },
            body: JSON.stringify({
                account_id: getAccountId(),
                period: period,
                max_decisions: maxDecisions,
                max_executions: maxExecutions,
            })
        });

        if (!res.ok) {
            showToast('请求失败: ' + res.status, 'error');
            return;
        }

        const data = await res.json();

        if (data.success) {
            showToast(`${period} 配额已更新`, 'success');
            document.getElementById(`total-${period}`).textContent = data.max_decisions;
            document.getElementById(`max-exec-${period}`).textContent = data.max_executions;
        } else {
            showToast(data.error || '更新失败', 'error');
        }
    } catch (e) {
        showToast('网络错误: ' + e.message, 'error');
    }
}

async function resetQuota(period) {
    if (!confirm(`确认重置 ${period} 配额的使用计数?`)) return;

    try {
        const res = await fetch("{% url 'decision_rhythm:reset-quota' %}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken(),
            },
            body: JSON.stringify({
                account_id: getAccountId(),
                period: period,
            })
        });

        if (!res.ok) {
            showToast('请求失败: ' + res.status, 'error');
            return;
        }

        const data = await res.json();

        if (data.success) {
            showToast(`${period} 配额已重置`, 'success');
            document.getElementById(`used-${period}`).textContent = '0';
            document.getElementById(`executed-${period}`).textContent = '0';
            const progressBar = document.querySelector(`#quota-${period} .progress-fill`);
            if (progressBar) {
                progressBar.style.width = '0%';
                progressBar.className = 'progress-fill low';
            }
        } else {
            showToast(data.error || '重置失败', 'error');
        }
    } catch (e) {
        showToast('网络错误: ' + e.message, 'error');
    }
}

// 趋势图表
let trendDataDays = 7;

document.addEventListener('DOMContentLoaded', function() {
    loadTrendData('7');
});

async function loadTrendData(days) {
    trendDataDays = parseInt(days);

    document.querySelectorAll('.btn-trend').forEach(b => b.classList.remove('active'));
    document.getElementById(`btn-${days}d`).classList.add('active');

    document.getElementById('dailyDecisionsChart').innerHTML = '<div class="trend-chart-loading">加载中...</div>';
    document.getElementById('dailyExecutionsChart').innerHTML = '<div class="trend-chart-loading">加载中...</div>';

    try {
        const accountId = getAccountId();
        const res = await fetch(`{% url 'decision_rhythm:api_trend_data' %}?days=${days}&account_id=${accountId}`);

        if (!res.ok) {
            showError('请求失败: ' + res.status);
            return;
        }

        const data = await res.json();

        if (data.success) {
            renderTrendCharts(data.data);
            updateStatistics(data.data);
        } else {
            showError('加载失败: ' + (data.error || '未知错误'));
        }
    } catch (e) {
        showError('网络错误: ' + e.message);
    }
}

function renderTrendCharts(data) {
    renderBarChart('dailyDecisionsChart', data.daily_decisions || [], 'decisions');
    renderBarChart('dailyExecutionsChart', data.daily_executions || [], 'executions');
}

function renderBarChart(containerId, chartData, type) {
    const container = document.getElementById(containerId);

    if (!chartData || chartData.length === 0) {
        container.innerHTML = '<div class="trend-chart-empty">暂无数据</div>';
        return;
    }

    const maxValue = Math.max(...chartData.map(d => d.value), 1);
    const quotaLimit = chartData[0]?.max_quota || maxValue * 1.2;

    let html = '<div class="bar-chart">';
    chartData.forEach(item => {
        const heightPercent = Math.min((item.value / quotaLimit) * 100, 100);
        const statusClass = item.value >= quotaLimit ? 'over' : (item.value >= quotaLimit * 0.8 ? 'warning' : 'normal');

        html += `
            <div class="bar">
                <div class="bar-tooltip">
                    ${item.date}<br>
                    <strong>${item.value} / ${quotaLimit}</strong>
                </div>
                <div class="bar-value">${item.value}</div>
                <div class="bar-fill ${statusClass}" style="height: ${heightPercent}%;"></div>
                <div class="bar-label">${formatDateLabel(item.date)}</div>
            </div>
        `;
    });
    html += '</div>';

    container.innerHTML = html;
}

function updateStatistics(data) {
    const decisions = data.daily_decisions || [];
    const executions = data.daily_executions || [];
    const dailyLimit = decisions[0]?.max_quota || 10;

    if (decisions.length === 0) {
        document.getElementById('avgDailyDecisions').textContent = '-';
        document.getElementById('maxDailyDecisions').textContent = '-';
        document.getElementById('avgDailyExecutions').textContent = '-';
        document.getElementById('overLimitDays').textContent = '-';
        return;
    }

    const avgDecisions = (decisions.reduce((sum, d) => sum + d.value, 0) / decisions.length).toFixed(1);
    document.getElementById('avgDailyDecisions').textContent = avgDecisions;

    const maxDecisions = Math.max(...decisions.map(d => d.value));
    document.getElementById('maxDailyDecisions').textContent = maxDecisions;

    const avgExecutions = executions.length > 0
        ? (executions.reduce((sum, d) => sum + d.value, 0) / executions.length).toFixed(1)
        : 0;
    document.getElementById('avgDailyExecutions').textContent = avgExecutions;

    const overLimitDays = decisions.filter(d => d.value >= dailyLimit).length;
    document.getElementById('overLimitDays').textContent = overLimitDays;
}

function formatDateLabel(dateStr) {
    const date = new Date(dateStr);
    return `${date.getMonth() + 1}/${date.getDate()}`;
}

function showError(message) {
    document.getElementById('dailyDecisionsChart').innerHTML = `<div class="trend-chart-empty">${message}</div>`;
    document.getElementById('dailyExecutionsChart').innerHTML = `<div class="trend-chart-empty">${message}</div>`;
}

function showToast(message, type = 'info') {
    const colors = {
        success: 'var(--color-success, #10b981)',
        error: 'var(--color-error, #ef4444)',
        warning: 'var(--color-warning, #f59e0b)',
        info: 'var(--color-primary, #3b82f6)'
    };

    const toast = document.createElement('div');
    toast.className = 'toast-notification';
    toast.style.background = colors[type];
    toast.textContent = message;

    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}
</script>
{% endblock %}
