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

{% block title %}账户设置 - AgomTradePro{% endblock %}

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

{% block content %}
<div class="settings-container">
    <div class="settings-header">
        <h1>账户设置</h1>
        <p class="subtitle">管理您的账户偏好和资金流水</p>
        <div class="settings-entry-banner">
            <div>
                <strong>设置中心是统一入口</strong>
                <div class="settings-entry-text">当前页面负责编辑账户资料、交易费率和 Token；如果你要把参数复制给 Codex 或其他 Agent，请去 MCP 接入说明页。</div>
            </div>
            <div style="display:flex; gap:8px; flex-wrap:wrap;">
                <a href="{% url 'account:mcp_guide' %}" class="btn btn-primary">MCP 接入说明</a>
                <a href="{% url 'settings-center' %}" class="btn btn-secondary">返回设置中心</a>
            </div>
        </div>
    </div>

    <!-- 资金流水 -->
    <section class="settings-section">
        <h2 class="section-title">资金流水</h2>

        <div class="capital-summary">
            <div class="summary-item">
                <span class="summary-label">累计入金</span>
                <span class="summary-value summary-deposit">¥{{ total_deposit|floatformat:2|default:"0.00" }}</span>
            </div>
            <div class="summary-item">
                <span class="summary-label">累计出金</span>
                <span class="summary-value summary-withdraw">¥{{ total_withdraw|floatformat:2|default:"0.00" }}</span>
            </div>
            <div class="summary-item">
                <span class="summary-label">净投入</span>
                <span class="summary-value summary-net">¥{{ net_capital|floatformat:2|default:"0.00" }}</span>
            </div>
        </div>

        <div class="flow-actions">
            <button type="button" class="btn btn-primary" onclick="showFlowModal('deposit')">
                + 入金
            </button>
            <button type="button" class="btn btn-secondary" onclick="showFlowModal('withdraw')">
                - 出金
            </button>
        </div>

        <!-- 流水记录 -->
        {% if capital_flows %}
        <div class="flow-list">
            <table class="table">
                <thead>
                    <tr>
                        <th>日期</th>
                        <th>类型</th>
                        <th>金额</th>
                        <th>备注</th>
                    </tr>
                </thead>
                <tbody>
                    {% for flow in capital_flows %}
                    <tr>
                        <td>{{ flow.flow_date|date:"Y-m-d" }}</td>
                        <td>
                            <span class="tag-{% if flow.flow_type == 'deposit' %}deposit{% else %}withdraw{% endif %}">
                                {{ flow.get_flow_type_display }}
                            </span>
                        </td>
                        <td class="{% if flow.flow_type == 'deposit' %}positive{% else %}negative{% endif %}">
                            ¥{{ flow.amount|floatformat:2 }}
                        </td>
                        <td>{{ flow.notes|default:"-" }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <p class="empty-state">暂无资金流水，点击上方按钮添加入金记录</p>
        {% endif %}
    </section>

    <!-- 交易费率配置 -->
    {% if portfolio %}
    <section class="settings-section">
        <h2 class="section-title">交易费率配置</h2>
        <p class="subtitle" style="margin-bottom: 16px;">配置您的券商佣金等交易成本，用于收益计算和模拟交易</p>

        <form method="post">
            {% csrf_token %}
            <input type="hidden" name="save_trading_cost" value="1">

            <div class="fee-grid">
                <div class="form-group">
                    <label for="commission_rate">佣金率</label>
                    <div class="input-with-unit">
                        <input type="number" id="commission_rate" name="commission_rate"
                               class="form-control"
                               step="0.00001" min="0" max="0.01"
                               value="{{ trading_cost_config.commission_rate|default:'0.00025' }}"
                               placeholder="0.00025">
                        <span class="unit-label" id="commission_wan"></span>
                    </div>
                    <small class="form-hint">如万2.5填 0.00025，万1填 0.0001</small>
                </div>

                <div class="form-group">
                    <label for="min_commission">最低佣金（元）</label>
                    <input type="number" id="min_commission" name="min_commission"
                           class="form-control"
                           step="0.01" min="0"
                           value="{{ trading_cost_config.min_commission|default:'5.0' }}"
                           placeholder="5.0">
                    <small class="form-hint">单笔佣金不足此金额按此收取</small>
                </div>

                <div class="form-group">
                    <label for="stamp_duty_rate">印花税率</label>
                    <div class="input-with-unit">
                        <input type="number" id="stamp_duty_rate" name="stamp_duty_rate"
                               class="form-control"
                               step="0.0001" min="0" max="0.01"
                               value="{{ trading_cost_config.stamp_duty_rate|default:'0.001' }}"
                               placeholder="0.001">
                        <span class="unit-label" id="stamp_qian"></span>
                    </div>
                    <small class="form-hint">卖出时收取，A股当前为千1（0.001）</small>
                </div>

                <div class="form-group">
                    <label for="transfer_fee_rate">过户费率</label>
                    <div class="input-with-unit">
                        <input type="number" id="transfer_fee_rate" name="transfer_fee_rate"
                               class="form-control"
                               step="0.00001" min="0" max="0.001"
                               value="{{ trading_cost_config.transfer_fee_rate|default:'0.00002' }}"
                               placeholder="0.00002">
                        <span class="unit-label" id="transfer_wan"></span>
                    </div>
                    <small class="form-hint">沪市股票双向收取，默认万0.2</small>
                </div>
            </div>

            <!-- 费用预览 -->
            <div class="fee-preview" id="feePreview">
                <h4>费用预估（以10万元为例）</h4>
                <div class="fee-preview-grid">
                    <div class="preview-item">
                        <span class="preview-label">买入费用</span>
                        <span class="preview-value" id="previewBuy">-</span>
                    </div>
                    <div class="preview-item">
                        <span class="preview-label">卖出费用</span>
                        <span class="preview-value" id="previewSell">-</span>
                    </div>
                    <div class="preview-item">
                        <span class="preview-label">一买一卖总费用</span>
                        <span class="preview-value preview-total" id="previewTotal">-</span>
                    </div>
                    <div class="preview-item">
                        <span class="preview-label">费用占比</span>
                        <span class="preview-value" id="previewRatio">-</span>
                    </div>
                </div>
            </div>

            <div class="form-actions" style="margin-top: 16px;">
                <button type="submit" class="btn btn-primary">保存费率</button>
            </div>
        </form>
    </section>
    {% endif %}

    <!-- 基本信息 -->
    <form method="post" class="settings-form">
        {% csrf_token %}

        <section class="settings-section">
            <h2 class="section-title">基本信息</h2>
            <div class="form-group">
                <label for="display_name">显示名称</label>
                <input type="text" id="display_name" name="display_name"
                       value="{{ profile.display_name|default:user.username }}"
                       class="form-control" required>
                <small class="form-hint">在系统中显示的名称</small>
            </div>
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" name="username"
                       value="{{ user.username }}"
                       class="form-control" readonly disabled>
                <small class="form-hint">用户名不可修改</small>
            </div>
            <div class="form-group">
                <label for="email">邮箱</label>
                <input type="email" id="email" name="email"
                       value="{{ user.email|default:"" }}"
                       class="form-control">
            </div>
        </section>

        <!-- 投资偏好 -->
        <section class="settings-section">
            <h2 class="section-title">投资偏好</h2>
            <div class="form-group">
                <label for="risk_tolerance">风险偏好</label>
                <select id="risk_tolerance" name="risk_tolerance" class="form-control" required>
                    <option value="conservative" {% if profile.risk_tolerance == 'conservative' %}selected{% endif %}>
                        保守型 - 追求稳健收益，可接受较低波动
                    </option>
                    <option value="moderate" {% if profile.risk_tolerance == 'moderate' %}selected{% endif %}>
                        稳健型 - 平衡风险与收益
                    </option>
                    <option value="aggressive" {% if profile.risk_tolerance == 'aggressive' %}selected{% endif %}>
                        激进型 - 追求高收益，可接受高波动
                    </option>
                </select>
            </div>
        </section>

        <!-- 安全设置 -->
        <section class="settings-section">
            <h2 class="section-title">安全设置</h2>
            <div class="form-group">
                <label for="new_password">新密码</label>
                <input type="password" id="new_password" name="new_password"
                       class="form-control" minlength="8">
                <small class="form-hint">留空则不修改密码。密码至少8位</small>
            </div>
            <div class="form-group">
                <label for="password_confirm">确认新密码</label>
                <input type="password" id="password_confirm" name="password_confirm"
                       class="form-control" minlength="8">
            </div>
        </section>

        <!-- 提交按钮 -->
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">保存设置</button>
            <a href="/account/profile/" class="btn btn-secondary">取消</a>
        </div>
    </form>

    <section class="settings-section">
        <h2 class="section-title">MCP/SDK Token</h2>
        <p class="subtitle">
            当前 MCP/SDK 权限: <strong>{% if profile.mcp_enabled %}已开启{% else %}已关闭{% endif %}</strong>
            {% if not system_settings.allow_token_plaintext_view %}，系统已关闭 Token 明文查看{% endif %}
        </p>
        <p class="subtitle" style="margin-bottom: 16px;">
            需要给 Codex、Claude Code 或其他 Agent 复制完整配置时，使用
            <a href="{% url 'account:mcp_guide' %}">MCP 接入说明</a>
            页面更方便。
        </p>

        {% if new_token_payload %}
            <div class="token-banner">
                <div><strong>新 Token</strong> - {{ new_token_payload.token_name }} - {{ new_token_payload.access_level_label }}</div>
                <div class="token-banner-row">
                    <code id="selfNewTokenValue">{{ new_token_payload.token }}</code>
                    <button type="button" class="btn btn-secondary" onclick="copySelfToken()">复制</button>
                </div>
            </div>
        {% endif %}

        {% if profile.mcp_enabled %}
            <form method="post" action="{% url 'account:create_self_token' %}" class="token-create-form">
                {% csrf_token %}
                <input type="hidden" name="next" value="{% url 'account:settings' %}">
                <input type="text" name="token_name" class="form-control" placeholder="例如: my-local-sdk" maxlength="100">
                <select name="access_level" class="form-control" style="max-width: 180px;">
                    {% for value, label in token_access_level_choices %}
                        <option value="{{ value }}" {% if value == default_token_access_level %}selected{% endif %}>{{ label }}</option>
                    {% endfor %}
                </select>
                <button type="submit" class="btn btn-primary">新建 Token</button>
            </form>
            <span class="form-hint">推荐默认使用只读 Token；需要写接口时再单独创建读写 Token。</span>
        {% endif %}

        {% if access_tokens %}
            <div class="flow-list">
                <table class="table">
                    <thead>
                        <tr>
                            <th>名称</th>
                            <th>级别</th>
                            <th>预览</th>
                            <th>创建时间</th>
                            <th>最后使用</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for token in access_tokens %}
                        <tr>
                            <td>{{ token.name }}</td>
                            <td>{{ token.get_access_level_display }}</td>
                            <td><code>{{ token.preview }}</code></td>
                            <td>{{ token.created_at|date:"Y-m-d H:i" }}</td>
                            <td>{% if token.last_used_at %}{{ token.last_used_at|date:"Y-m-d H:i" }}{% else %}-{% endif %}</td>
                            <td>
                                <form method="post" action="{% url 'account:revoke_self_token' token.id %}">
                                    {% csrf_token %}
                                    <input type="hidden" name="next" value="{% url 'account:settings' %}">
                                    <button type="submit" class="btn btn-secondary" onclick="return confirm('确定撤销 Token {{ token.name }} 吗？')">撤销</button>
                                </form>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        {% else %}
            <p class="empty-state">暂无可用 Token</p>
        {% endif %}
    </section>
</div>

<!-- 入金/出金弹窗 -->
<div id="flowModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">入金</h3>
            <button type="button" class="modal-close" onclick="closeFlowModal()">&times;</button>
        </div>
        <form id="flowForm" method="post" action="{% url 'account:capital_flow' %}">
            {% csrf_token %}
            <input type="hidden" id="flowType" name="flow_type" value="">
            <div class="modal-body">
                <div class="form-group">
                    <label for="flowAmount">金额</label>
                    <input type="number" id="flowAmount" name="amount"
                           class="form-control" step="0.01" min="0.01" required
                           placeholder="请输入金额">
                </div>
                <div class="form-group">
                    <label for="flowDate">日期</label>
                    <input type="date" id="flowDate" name="flow_date"
                           class="form-control" required
                           value="{% now 'Y-m-d' %}">
                </div>
                <div class="form-group">
                    <label for="flowNotes">备注</label>
                    <textarea id="flowNotes" name="notes" class="form-control"
                              rows="2" placeholder="选填"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeFlowModal()">取消</button>
                <button type="submit" class="btn btn-primary">确认</button>
            </div>
        </form>
    </div>
</div>

<style>
.settings-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 24px;
}

.settings-header {
    margin-bottom: 24px;
}

.settings-entry-banner {
    margin-top: 16px;
    padding: 14px 16px;
    border-radius: 10px;
    background: linear-gradient(135deg, rgba(37,99,235,0.08), rgba(15,23,42,0.03));
    border: 1px solid rgba(37,99,235,0.14);
    display: flex;
    justify-content: space-between;
    gap: 16px;
    align-items: center;
    flex-wrap: wrap;
}

.settings-entry-text {
    margin-top: 4px;
    color: #54595D;
    font-size: 13px;
    line-height: 1.6;
}

.settings-header h1 {
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 4px;
}

.subtitle {
    color: #54595D;
    font-size: 14px;
}

.settings-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;
}

/* 资金流水 */
.capital-summary {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 16px;
}

.summary-item {
    background: #F8F9FA;
    padding: 16px;
    border-radius: 4px;
    text-align: center;
}

.summary-label {
    display: block;
    font-size: 12px;
    color: #54595D;
    margin-bottom: 8px;
}

.summary-value {
    display: block;
    font-size: 20px;
    font-weight: 600;
}

.summary-deposit { color: var(--color-capital-inflow); }
.summary-withdraw { color: var(--color-capital-outflow); }
.summary-net { color: #202122; }

.flow-actions {
    display: flex;
    gap: 12px;
    margin-bottom: 20px;
}

.flow-list {
    margin-top: 16px;
}

.token-banner {
    margin: 12px 0 16px;
    padding: 12px;
    border: 1px solid #FFECB5;
    background: #FFF3CD;
    border-radius: 4px;
}

.token-banner-row {
    margin-top: 8px;
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    align-items: center;
}

.token-create-form {
    display: flex;
    gap: 12px;
    margin: 16px 0;
}

.tag-deposit {
    padding: 2px 8px;
    border-radius: 2px;
    background: var(--color-rise-soft);
    color: var(--color-rise-strong);
    font-size: 12px;
}

.tag-withdraw {
    padding: 2px 8px;
    border-radius: 2px;
    background: var(--color-fall-soft);
    color: var(--color-fall-strong);
    font-size: 12px;
}

/* 表单 */
.form-group {
    margin-bottom: 16px;
}

.form-group label {
    display: block;
    font-weight: 500;
    margin-bottom: 4px;
    font-size: 14px;
}

.form-control {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #E0E0E0;
    border-radius: 4px;
    font-size: 14px;
}

.form-control:read-only,
.form-control:disabled {
    background: #F8F9FA;
    color: #54595D;
}

.form-hint {
    display: block;
    font-size: 12px;
    color: #54595D;
    margin-top: 4px;
}

.form-actions {
    display: flex;
    gap: 12px;
}

.btn {
    padding: 10px 20px;
    border-radius: 4px;
    font-size: 14px;
    text-decoration: none;
    display: inline-block;
    cursor: pointer;
    border: none;
}

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

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

/* 表格 */
.table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 12px;
}

.table thead {
    background: #F8F9FA;
}

.table th {
    padding: 10px;
    text-align: left;
    font-weight: 600;
    font-size: 12px;
    border-bottom: 1px solid #E0E0E0;
}

.table td {
    padding: 10px;
    font-size: 13px;
    border-bottom: 1px solid #E0E0E0;
}

.positive { color: var(--color-rise); }
.negative { color: var(--color-fall); }

/* 弹窗 */
#flowModal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

#flowModal .modal-content {
    background: #FFFFFF;
    border-radius: 8px;
    width: 400px;
    max-width: 90%;
}

#flowModal .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #E0E0E0;
}

#flowModal .modal-header h3 {
    font-size: 16px;
    font-weight: 600;
    margin: 0;
}

#flowModal .modal-close {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    padding: 0;
    width: 24px;
    height: 24px;
}

#flowModal .modal-body {
    padding: 16px;
}

#flowModal .modal-footer {
    display: flex;
    gap: 12px;
    padding: 16px;
    border-top: 1px solid #E0E0E0;
    justify-content: flex-end;
}

.empty-state {
    text-align: center;
    padding: 24px;
    color: #54595D;
    font-size: 13px;
}

/* 费率配置 */
.fee-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
}

.input-with-unit {
    display: flex;
    align-items: center;
    gap: 8px;
}

.input-with-unit .form-control {
    flex: 1;
}

.unit-label {
    font-size: 13px;
    color: #54595D;
    white-space: nowrap;
    min-width: 50px;
}

.fee-preview {
    margin-top: 20px;
    padding: 16px;
    background: #F8F9FA;
    border-radius: 4px;
    border: 1px solid #E0E0E0;
}

.fee-preview h4 {
    font-size: 14px;
    font-weight: 600;
    margin-bottom: 12px;
}

.fee-preview-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
}

.preview-item {
    text-align: center;
}

.preview-label {
    display: block;
    font-size: 12px;
    color: #54595D;
    margin-bottom: 4px;
}

.preview-value {
    display: block;
    font-size: 16px;
    font-weight: 600;
}

.preview-total {
    color: #D33;
}

@media (max-width: 600px) {
    .fee-grid {
        grid-template-columns: 1fr;
    }
    .fee-preview-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}
</style>

<script>
function showFlowModal(type) {
    document.getElementById('flowType').value = type;
    document.getElementById('modalTitle').textContent = type === 'deposit' ? '入金' : '出金';
    document.getElementById('flowModal').style.display = 'flex';
    document.getElementById('flowAmount').focus();
}

function closeFlowModal() {
    document.getElementById('flowModal').style.display = 'none';
    document.getElementById('flowForm').reset();
}

function copySelfToken() {
    const el = document.getElementById('selfNewTokenValue');
    if (!el) return;
    navigator.clipboard.writeText(el.textContent || '').then(() => {
        if (window.showToast) {
            window.showToast('Token 已复制到剪贴板', 'success');
        }
    });
}

// 点击弹窗外部关闭
document.getElementById('flowModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeFlowModal();
    }
});

// 费率实时预览
function updateFeePreview() {
    var commRate = parseFloat(document.getElementById('commission_rate').value) || 0;
    var minComm = parseFloat(document.getElementById('min_commission').value) || 0;
    var stampRate = parseFloat(document.getElementById('stamp_duty_rate').value) || 0;
    var transferRate = parseFloat(document.getElementById('transfer_fee_rate').value) || 0;
    var amount = 100000;

    // 更新单位标签
    document.getElementById('commission_wan').textContent = '(万' + (commRate * 10000).toFixed(1) + ')';
    document.getElementById('stamp_qian').textContent = '(千' + (stampRate * 1000).toFixed(1) + ')';
    document.getElementById('transfer_wan').textContent = '(万' + (transferRate * 10000).toFixed(2) + ')';

    // 买入: 佣金 + 过户费(沪市)
    var buyComm = Math.max(amount * commRate, minComm);
    var buyCost = buyComm;

    // 卖出: 佣金 + 印花税 + 过户费(沪市)
    var sellComm = Math.max(amount * commRate, minComm);
    var sellStamp = amount * stampRate;
    var sellCost = sellComm + sellStamp;

    var totalCost = buyCost + sellCost;
    var ratio = (totalCost / amount * 100).toFixed(3);

    document.getElementById('previewBuy').textContent = '\u00a5' + buyCost.toFixed(2);
    document.getElementById('previewSell').textContent = '\u00a5' + sellCost.toFixed(2);
    document.getElementById('previewTotal').textContent = '\u00a5' + totalCost.toFixed(2);
    document.getElementById('previewRatio').textContent = ratio + '%';
}

// 监听费率输入变化
['commission_rate', 'min_commission', 'stamp_duty_rate', 'transfer_fee_rate'].forEach(function(id) {
    var el = document.getElementById(id);
    if (el) {
        el.addEventListener('input', updateFeePreview);
    }
});

// 初始化预览
if (document.getElementById('commission_rate')) {
    updateFeePreview();
}

document.querySelector('.settings-form').addEventListener('submit', function(e) {
    const newPass = document.getElementById('new_password').value;
    const confirmPass = document.getElementById('password_confirm').value;

    if (newPass && newPass !== confirmPass) {
        e.preventDefault();
        alert('两次输入的密码不一致');
        return false;
    }

    if (newPass && newPass.length < 8) {
        e.preventDefault();
        alert('密码至少需要8位');
        return false;
    }
});
</script>
{% endblock %}
