{% load static %}

<!-- 主流程面板 -->
<section class="main-workflow-panel">
    <div class="section-header">
        <div>
            <h2 class="section-title">🚀 决策 Workflow</h2>
<p class="section-subtitle">环境评估 → 方向选择 → 板块偏好 → 推优筛选 → 交易计划 → 审批执行</p>
        </div>
        <div class="header-actions">
            <button class="btn-precheck" onclick="refreshWorkflowCandidates()">
                🔄 刷新候选
            </button>
            <a href="{% url 'decision-workspace' %}" class="btn-submit-decision" style="text-decoration: none;">
                进入新 Workflow
            </a>
        </div>
    </div>

    <!-- 步骤导航 -->
    <div class="workflow-steps">
        <div class="workflow-step {% if current_regime and policy_level %}completed{% else %}active{% endif %}">
            <div class="step-number">1</div>
            <div class="step-label">环境评估</div>
        </div>
        <div class="workflow-step {% if action_weights %}completed{% elif current_regime and policy_level %}active{% endif %}">
            <div class="step-number">2</div>
            <div class="step-label">方向选择</div>
        </div>
        <div class="workflow-step {% if action_sectors %}completed{% elif action_weights %}active{% endif %}">
            <div class="step-number">3</div>
            <div class="step-label">板块偏好</div>
        </div>
        <div class="workflow-step {% if alpha_actionable_count > 0 %}active{% endif %}">
            <div class="step-number">4</div>
            <div class="step-label">推优筛选</div>
        </div>
        <div class="workflow-step {% if pending_count > 0 %}active{% endif %}">
            <div class="step-number">5</div>
            <div class="step-label">交易计划</div>
        </div>
        <div class="workflow-step">
            <div class="step-number">6</div>
            <div class="step-label">审批执行</div>
        </div>
    </div>

    {% if alpha_decision_chain_overview %}
    <div class="workflow-chain-summary">
        <div class="workflow-chain-summary-header">
            <h3 class="subsection-title">Alpha 决策链收束</h3>
            <span class="workflow-chain-summary-text">
                Top 10 → 可行动 → 待执行，页面按同一条链路展示
            </span>
        </div>
        <div class="workflow-chain-track">
            <div class="workflow-chain-node">
                <span class="workflow-chain-node-value">{{ alpha_decision_chain_overview.top_ranked_count|default:0 }}</span>
                <span class="workflow-chain-node-label">Top 10 排名</span>
            </div>
            <div class="workflow-chain-arrow">→</div>
            <div class="workflow-chain-node workflow-chain-node-actionable">
                <span class="workflow-chain-node-value">{{ alpha_decision_chain_overview.top10_actionable_count|default:0 }}</span>
                <span class="workflow-chain-node-label">Top10 中可行动</span>
            </div>
            <div class="workflow-chain-arrow">→</div>
            <div class="workflow-chain-node workflow-chain-node-pending">
                <span class="workflow-chain-node-value">{{ alpha_decision_chain_overview.top10_pending_count|default:0 }}</span>
                <span class="workflow-chain-node-label">Top10 中待执行</span>
            </div>
            <div class="workflow-chain-arrow">·</div>
            <div class="workflow-chain-node workflow-chain-node-muted">
                <span class="workflow-chain-node-value">{{ alpha_decision_chain_overview.top10_rank_only_count|default:0 }}</span>
                <span class="workflow-chain-node-label">仍仅在 Top10</span>
            </div>
        </div>
        {% if alpha_decision_chain_overview.actionable_outside_top10_count or alpha_decision_chain_overview.pending_outside_top10_count %}
        <div class="workflow-chain-summary-foot">
            <span>链外可行动 {{ alpha_decision_chain_overview.actionable_outside_top10_count|default:0 }}</span>
            <span>链外待执行 {{ alpha_decision_chain_overview.pending_outside_top10_count|default:0 }}</span>
        </div>
        {% endif %}
    </div>
    {% endif %}

    {% with exit_watchlist=alpha_exit_entry_watchlist|default:alpha_exit_watchlist exit_watch_summary=alpha_exit_entry_watch_summary|default:alpha_exit_watch_summary %}
    {% if exit_watchlist %}
    <div class="candidate-actions-section alpha-recommendations-section workflow-exit-entry-section" style="margin-top: 12px;">
        <div class="workflow-exit-entry-header">
            <div class="workflow-exit-entry-title-group">
                <h3 class="subsection-title">退出待办</h3>
                <p class="workflow-exit-entry-subtitle">
                    先在右侧核对退出契约与调仓计划，再决定是否进入工作台继续执行。
                </p>
            </div>
            <span class="workflow-exit-entry-count">{{ exit_watchlist|length }} 条待处理</span>
        </div>
        {% if exit_watch_summary.total %}
        <div class="workflow-exit-summary">
            <span class="workflow-exit-pill workflow-exit-pill-urgent">立即处理 {{ exit_watch_summary.urgent_count|default:0 }}</span>
            <span class="workflow-exit-pill workflow-exit-pill-sell">SELL {{ exit_watch_summary.sell_count|default:0 }}</span>
            <span class="workflow-exit-pill workflow-exit-pill-reduce">REDUCE {{ exit_watch_summary.reduce_count|default:0 }}</span>
            <span class="workflow-exit-pill">HOLD {{ exit_watch_summary.hold_count|default:0 }}</span>
        </div>
        {% endif %}
        {% if alpha_exit_entry_hidden_count %}
        <p class="workflow-exit-entry-note">
            已自动收起 {{ alpha_exit_entry_hidden_count }} 条已采纳 / 已忽略项，避免首页重复提醒；仍可在右侧详情面板继续核对。
        </p>
        {% endif %}
        <div class="workflow-exit-entry-list">
        {% for item in exit_watchlist|slice:":3" %}
        <div class="workflow-exit-entry">
            <div class="workflow-exit-entry-main">
                <div class="candidate-main-info">
                    <span class="candidate-asset-code">{{ item.asset_code }}</span>
                    {% if item.asset_name %}
                    <span class="candidate-asset-name">{{ item.asset_name }}</span>
                    {% endif %}
                    <span class="candidate-direction-badge {% if item.exit_action == 'SELL' %}short{% else %}long{% endif %}">
                        {{ item.exit_action_label }}
                    </span>
                </div>
                <div class="candidate-meta">
                    <span>账户: {{ item.account_name }}</span>
                    <span>退出来源: {{ item.exit_source }}</span>
                    <span>决策侧: {{ item.decision_side_label }}</span>
                </div>
                <div class="candidate-chain-meta">
                    <span class="candidate-chain-badge candidate-chain-badge-pending">{{ item.priority_label }}</span>
                    {% if item.stop_loss_price %}
                        <span class="candidate-chain-badge candidate-chain-badge-score">止损 {{ item.stop_loss_price }}</span>
                    {% endif %}
                    <span class="candidate-chain-badge candidate-chain-badge-origin">{{ item.contract_status_label }}</span>
                </div>
                <div class="workflow-exit-entry-reason">
                    {{ item.exit_reason_text|default:"当前未触发退出动作。" }}
                </div>
            </div>
            <div class="workflow-exit-entry-actions">
                <a class="btn-precheck workflow-exit-detail-btn"
                   href="{{ item.dashboard_detail_url }}"
                   data-dashboard-exit-detail-link="true"
                   data-exit-asset-code="{{ item.asset_code }}"
                   {% if item.account_id %}data-exit-account-id="{{ item.account_id }}"{% endif %}
                   style="text-decoration:none;">
                    查看右侧详情
                </a>
                <span class="workflow-exit-inline-cue">不会离开当前页</span>
                <a class="btn-submit-decision workflow-exit-primary-btn"
                   href="{{ item.decision_workspace_url|default:'/decision/workspace/' }}"
                   style="text-decoration:none;">
                    进入决策工作台
                </a>
            </div>
        </div>
        {% endfor %}
        </div>
    </div>
    {% endif %}
    {% endwith %}

    <!-- Alpha 推荐资产列表 -->
    <div class="candidate-actions-section alpha-recommendations-section" style="margin-top: 12px;">
        <div style="display:flex; justify-content:space-between; align-items:flex-start; gap:12px; flex-wrap:wrap;">
            <div>
                <h3 class="subsection-title">Alpha 推荐资产 (展示 {{ alpha_stock_scores|slice:":5"|length }} / 共 {{ alpha_stock_scores|length|default:0 }})</h3>
                <p class="candidate-meta" style="margin: 6px 0 0 0;">
                    这里只展示已通过账户 scope、数据新鲜度和风控 readiness 的资产；研究排名请进入完整排名页核对。
                </p>
            </div>
            <a class="btn-precheck"
               href="{% url 'dashboard:alpha_ranking' %}?alpha_scope={{ selected_alpha_scope|default:'portfolio' }}{% if selected_portfolio_id and selected_alpha_scope != 'general' %}&portfolio_id={{ selected_portfolio_id }}{% endif %}{% if selected_alpha_pool_mode and selected_alpha_scope != 'general' %}&pool_mode={{ selected_alpha_pool_mode|urlencode }}{% endif %}&top_n=200"
               style="text-decoration:none;">
                📋 查看完整排名
            </a>
        </div>
        {% if alpha_stock_scores %}
            {% for stock in alpha_stock_scores|slice:":5" %}
            <div class="candidate-action-row" data-stock-code="{{ stock.code }}">
                <div class="candidate-info-cell">
                    <div class="candidate-main-info">
                        <a class="candidate-asset-code"
                           href="{% url 'equity:detail' stock.code %}"
                           style="text-decoration:none;">
                            {{ stock.code }}
                        </a>
                        {% if stock.name %}
                        <a class="candidate-asset-name"
                           href="{% url 'equity:detail' stock.code %}"
                           style="text-decoration:none;">
                            {{ stock.name }}
                        </a>
                        {% endif %}
                        <span class="candidate-direction-badge long">
                            排名 #{% if stock.rank %}{{ stock.rank }}{% else %}{{ forloop.counter }}{% endif %}
                        </span>
                    </div>
                    <div class="candidate-meta">
                        {% if stock.alpha_score != None %}
                        <span>Alpha: {{ stock.alpha_score|floatformat:3 }}</span>
                        {% elif stock.score != None %}
                        <span>Alpha: {{ stock.score|floatformat:3 }}</span>
                        {% endif %}
                        {% if stock.confidence != None %}
                        <span>置信度: {{ stock.confidence|floatformat:2 }}</span>
                        {% endif %}
                        {% if stock.source %}
                        <span>来源: {{ stock.source }}</span>
                        {% endif %}
                        {% if stock.asof_date %}
                        <span>日期: {{ stock.asof_date }}</span>
                        {% endif %}
                    </div>
                    <div class="candidate-chain-meta">
                        <span class="candidate-chain-badge candidate-chain-badge-stage">{{ stock.stage_label|default:"Alpha 推荐排名" }}</span>
                        {% if stock.buy_reason_summary %}
                        <span class="candidate-chain-badge candidate-chain-badge-origin">{{ stock.buy_reason_summary }}</span>
                        {% endif %}
                        {% if stock.invalidation_summary %}
                        <span class="candidate-chain-badge candidate-chain-badge-score">证伪: {{ stock.invalidation_summary }}</span>
                        {% endif %}
                    </div>
                </div>
                <a class="btn-precheck"
                   href="{{ stock.decision_workspace_url }}"
                   style="text-decoration:none;">
                    🔍 在 Workflow 中查看
                </a>
                <a class="btn-submit-decision"
                   href="{{ stock.decision_workspace_primary_url }}"
                   style="text-decoration:none;">
                    📝 进入 Step 4
                </a>
            </div>
            {% endfor %}
        {% else %}
            <div class="empty-state" style="padding: 16px;">
                <div class="empty-icon">📊</div>
                <p>暂无可信 Alpha 推荐资产</p>
                <p class="empty-hint">
                    {% if alpha_stock_scores_meta.blocked_reason %}
                        {{ alpha_stock_scores_meta.blocked_reason }}
                    {% elif alpha_stock_scores_meta.no_recommendation_reason %}
                        {{ alpha_stock_scores_meta.no_recommendation_reason }}
                    {% else %}
                        当前没有通过 readiness 的账户推荐；系统不会用市场 broad pool、硬编码股票池、静态名单或默认 ETF 冒充推荐。
                    {% endif %}
                </p>
                {% if alpha_stock_scores_meta.uses_cached_data and alpha_stock_scores_meta.effective_asof_date %}
                <p class="empty-hint">
                    当前只拿到截至 {{ alpha_stock_scores_meta.effective_asof_date }} 的历史结果，首页不会把这类缓存结果当成可执行推荐展示。
                </p>
                {% endif %}
                <div style="display:flex; align-items:center; justify-content:center; gap:10px; flex-wrap:wrap;">
                    <button type="button" class="btn-precheck" onclick="triggerAlphaRealtimeRefresh(10, this)">
                        ⚡ 立即推理刷新
                    </button>
                    <span id="alphaRefreshStatus" class="alpha-refresh-status"></span>
                </div>
            </div>
        {% endif %}
    </div>

    <!-- 可操作候选列表 -->
    {% if actionable_candidates %}
    <div class="candidate-actions-section">
        <h3 class="subsection-title">可行动候选 (展示 {{ actionable_candidates|length }} / 共 {{ alpha_actionable_count|default:0 }})</h3>
        {% if valuation_repair_config_summary %}
        <div class="repair-config-inline-summary">
            <span class="repair-config-title">估值修复参数</span>
            <span>v{{ valuation_repair_config_summary.version }}</span>
            <span>目标 {{ valuation_repair_config_summary.target_percentile|floatformat:2 }}</span>
            <span>低估 {{ valuation_repair_config_summary.undervalued_threshold|floatformat:2 }}</span>
            <span>接近目标 {{ valuation_repair_config_summary.near_target_threshold|floatformat:2 }}</span>
            <span>高估 {{ valuation_repair_config_summary.overvalued_threshold|floatformat:2 }}</span>
        </div>
        {% endif %}

        {% for candidate in actionable_candidates %}
        <div class="candidate-action-row" data-candidate-id="{{ candidate.candidate_id }}">
            <!-- 候选信息 -->
            <div class="candidate-info-cell">
                <div class="candidate-main-info">
                    <span class="candidate-asset-code">{{ candidate.asset_code }}</span>
                    {% if candidate.asset_name %}
                    <span class="candidate-asset-name">{{ candidate.asset_name }}</span>
                    {% endif %}
                    <span class="candidate-direction-badge {{ candidate.direction|lower }}">
                        {% if candidate.direction == 'LONG' %}做多{% elif candidate.direction == 'SHORT' %}做空{% else %}中性{% endif %}
                    </span>
                </div>
                <div class="candidate-meta">
                    <span class="candidate-confidence">置信度: {{ candidate.confidence|floatformat:2 }}</span>
                    <span class="candidate-asset-class">{{ candidate.asset_class }}</span>
                </div>
                <div class="candidate-chain-meta">
                    <span class="candidate-chain-badge candidate-chain-badge-stage">{{ candidate.chain_stage_label|default:"可行动候选" }}</span>
                    <span class="candidate-chain-badge candidate-chain-badge-origin">{{ candidate.origin_stage_label|default:"当前不在 Top 10" }}</span>
                    {% if candidate.current_top_score != None %}
                    <span class="candidate-chain-badge candidate-chain-badge-score">Alpha {{ candidate.current_top_score|floatformat:3 }}</span>
                    {% endif %}
                </div>
                {% if candidate.valuation_repair %}
                <div class="candidate-valuation-repair">
                    <div class="repair-badges">
                        <span class="repair-phase-badge phase-{{ candidate.valuation_repair.phase }}">
                            修复: {{ candidate.valuation_repair.phase }}
                        </span>
                        {% if candidate.valuation_repair.signal %}
                        <span class="repair-signal-badge signal-{{ candidate.valuation_repair.signal }}">
                            {{ candidate.valuation_repair.signal }}
                        </span>
                        {% endif %}
                    </div>
                    <div class="repair-metrics">
                        <span>
                            综合分位:
                            {% if candidate.valuation_repair.composite_percentile is not None %}
                            {{ candidate.valuation_repair.composite_percentile|floatformat:2 }}
                            {% else %}
                            -
                            {% endif %}
                        </span>
                        <span>
                            修复进度:
                            {% if candidate.valuation_repair.repair_progress is not None %}
                            {{ candidate.valuation_repair.repair_progress|floatformat:2 }}
                            {% else %}
                            -
                            {% endif %}
                        </span>
                        <span>
                            ETA:
                            {% if candidate.valuation_repair.estimated_days_to_target %}
                            {{ candidate.valuation_repair.estimated_days_to_target }}d
                            {% else %}
                            -
                            {% endif %}
                        </span>
                    </div>
                </div>
                {% else %}
                <div class="candidate-valuation-repair candidate-valuation-repair-empty">
                    <span class="repair-empty-text">未命中估值修复快照</span>
                </div>
                {% endif %}
            </div>

            <a class="btn-precheck"
               href="{{ candidate.decision_workspace_url }}"
               style="text-decoration:none;">
                🔍 在 Workflow 中查看
            </a>

            <a class="btn-submit-decision"
               href="{{ candidate.decision_workspace_primary_url }}"
               style="text-decoration:none;">
                📝 进入 Step 4
            </a>
        </div>
        {% endfor %}
    </div>
    {% else %}
    <div class="empty-state">
        <div class="empty-icon">⏳</div>
        <p>暂无通过触发器和风控约束的可行动候选</p>
        <a href="{% url 'alpha_trigger:create' %}" class="btn btn-primary">创建触发器</a>
    </div>
    {% endif %}

    <!-- 待执行队列 -->
    <div class="candidate-actions-section" style="margin-top: 12px;">
        <h3 class="subsection-title">待执行队列 ({{ pending_count|default:0 }})</h3>
        {% if pending_requests %}
            {% for req in pending_requests|slice:":5" %}
            <div class="candidate-action-row">
                <div class="candidate-info-cell">
                    <div class="candidate-main-info">
                        <span class="candidate-asset-code">{{ req.asset_code }}</span>
                        {% if req.asset_name %}
                        <span class="candidate-asset-name">{{ req.asset_name }}</span>
                        {% endif %}
                        <span class="candidate-direction-badge {% if req.direction == 'BUY' %}long{% else %}short{% endif %}">
                            {{ req.direction }}
                        </span>
                    </div>
                    <div class="candidate-meta">
                        <span>请求ID: {{ req.request_id|truncatechars:16 }}</span>
                        <span>状态: {{ req.execution_status }}</span>
                    </div>
                    <div class="candidate-chain-meta">
                        <span class="candidate-chain-badge candidate-chain-badge-pending">{{ req.chain_stage_label|default:"待执行队列" }}</span>
                        <span class="candidate-chain-badge candidate-chain-badge-origin">{{ req.origin_stage_label|default:"当前不在 Top 10" }}</span>
                        {% if req.current_top_score != None %}
                        <span class="candidate-chain-badge candidate-chain-badge-score">Alpha {{ req.current_top_score|floatformat:3 }}</span>
                        {% endif %}
                    </div>
                </div>
                <a class="btn-submit-decision" href="{{ req.decision_workspace_primary_url }}" style="text-decoration:none;">
                    去 Step 5
                </a>
            </div>
            {% endfor %}
        {% else %}
            <div class="empty-state" style="padding: 16px;">
                <p>当前无待执行请求</p>
            </div>
        {% endif %}
    </div>
</section>

<style>
.workflow-exit-summary {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    margin-bottom: 12px;
}

.workflow-exit-pill {
    display: inline-flex;
    align-items: center;
    padding: 4px 10px;
    border-radius: 999px;
    background: #ecf1f8;
    color: #425164;
    font-size: 12px;
    font-weight: 700;
}

.workflow-exit-pill-urgent {
    background: #ffe7e7;
    color: #a33434;
}

.workflow-exit-pill-sell {
    background: #ffecec;
    color: #b42318;
}

.workflow-exit-pill-reduce {
    background: #fff0d9;
    color: #9a6220;
}
</style>
