#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
流程规划可视化HTML生成器 v2.0
架构大图：L1全景图 → 点击下钻L2 → 点击下钻L3，侧边抽屉交互
"""

import json
import os
from datetime import datetime
from typing import Dict, List
from process_planning import generate_process_planning


def generate_html_report(data: Dict, output_path: str) -> str:
    """生成完整的流程规划HTML报告"""

    company = data["company_info"]
    arch = data["architecture"]
    matrix = data["capability_matrix"]
    roadmap = data["roadmap"]

    # 序列化架构数据，供JS使用
    arch_json = json.dumps(arch['L1_processes'], ensure_ascii=False)
    matrix_json = json.dumps(matrix, ensure_ascii=False)

    # 统计
    high_priority = sum(1 for m in matrix if m['priority'] == '高')

    # 热力图表格行
    heatmap_rows = ""
    for item in matrix:
        imp_cls = "hm-high" if item['importance'] == '高' else "hm-mid" if item['importance'] == '中' else "hm-low"
        mat_cls = "hm-high" if item['maturity'] == '高' else "hm-mid" if item['maturity'] == '中' else "hm-low"
        pri_cls = "hm-high" if item['priority'] == '高' else "hm-mid" if item['priority'] == '中' else "hm-low"
        cat = item['category']
        badge = "badge-o" if '运营' in cat else "badge-e" if '使能' in cat else "badge-s"
        cat_short = cat.split('(')[1].replace(')', '')
        gap_str = ('+' if item['gap'] > 0 else '') + str(item['gap'])
        gap_cls = "text-red" if item['gap'] > 0 else "text-green"
        row_cls = "row-high" if item['priority'] == '高' else "row-mid" if item['priority'] == '中' else "row-low"
        heatmap_rows += f'''<tr class="{row_cls}">
<td><p class="fw6">{item['L1_name']}</p><p class="mono">{item['L1_code']}</p></td>
<td><span class="badge {badge}">{cat_short}</span></td>
<td class="tc"><span class="pill {imp_cls}">{item['importance']}</span></td>
<td class="tc"><span class="pill {mat_cls}">{item['maturity']}</span></td>
<td class="tc"><span class="fw7 {gap_cls}">{gap_str}</span></td>
<td class="tc"><span class="pill {pri_cls}">{item['priority']}</span></td>
<td class="tc muted">{item['L2_count']} / {item['L3_count']}</td>
</tr>'''

    # 路线图内容
    roadmap_html = ""
    phase_meta = {
        'phase1': ('1', '第一阶段（0-6个月）', '高优先级流程，立即启动', '#3b6fd4'),
        'phase2': ('2', '第二阶段（6-12个月）', '中优先级流程，系统建设', '#e07b2a'),
        'phase3': ('3', '第三阶段（12-18个月）', '基础能力建设，持续完善', '#2ea06d'),
    }
    for key, (num, title, focus, color) in phase_meta.items():
        items = roadmap.get(key, {}).get('items', [])
        cards = ""
        for it in items:
            cat = it['category']
            b = "badge-o" if '运营' in cat else "badge-e" if '使能' in cat else "badge-s"
            cs = cat.split('(')[1].replace(')', '')
            cards += f'''<div class="rm-card">
<div class="rm-card-top"><span class="badge {b}">{cs}</span><span class="muted fs11">差距 +{it['gap']}</span></div>
<p class="fw6 mt4">{it['L1_name']}</p>
<p class="muted fs11 mt2">{it['L2_count']}个L2 · {it['L3_count']}个L3</p>
</div>'''
        roadmap_html += f'''<div class="rm-phase">
<div class="rm-phase-head" style="border-left:4px solid {color}">
  <div class="rm-num" style="background:{color}">{num}</div>
  <div><p class="fw7">{title}</p><p class="muted fs12">{focus} · {len(items)}项</p></div>
</div>
<div class="rm-cards">{cards}</div>
</div>'''

    now_str = datetime.now().strftime("%Y-%m-%d %H:%M")

    html = f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{company['name']} · 流程架构规划</title>
<style>
/* ===== Reset & Base ===== */
*,*::before,*::after{{box-sizing:border-box;margin:0;padding:0}}
body{{font-family:'PingFang SC','Microsoft YaHei',system-ui,sans-serif;background:#f0f4f8;color:#1e293b;min-height:100vh}}
a{{text-decoration:none}}
/* ===== Layout ===== */
.header{{background:linear-gradient(135deg,#1e3a5f 0%,#2558a8 60%,#3d7ab5 100%);color:#fff;padding:28px 40px}}
.header-inner{{max-width:1200px;margin:0 auto;display:flex;justify-content:space-between;align-items:flex-start}}
.header h1{{font-size:26px;font-weight:700;margin:6px 0 4px}}
.header .sub{{font-size:13px;opacity:.75}}
.header-meta{{text-align:right;font-size:12px;opacity:.7;line-height:1.8}}
.nav{{background:#fff;border-bottom:1px solid #e2e8f0;position:sticky;top:0;z-index:100}}
.nav-inner{{max-width:1200px;margin:0 auto;display:flex;gap:0}}
.nav-btn{{padding:14px 20px;font-size:14px;background:none;border:none;border-bottom:3px solid transparent;cursor:pointer;color:#64748b;transition:.2s;white-space:nowrap}}
.nav-btn.active{{border-bottom-color:#2558a8;color:#2558a8;font-weight:600}}
.nav-btn:hover:not(.active){{color:#334155}}
.main{{max-width:1200px;margin:0 auto;padding:28px 40px}}
.section{{display:none}}.section.active{{display:block}}
/* ===== Cards ===== */
.card{{background:#fff;border-radius:12px;box-shadow:0 1px 4px rgba(0,0,0,.08);padding:24px;margin-bottom:20px}}
.card-title{{font-size:17px;font-weight:700;color:#1e293b;margin-bottom:4px}}
.card-sub{{font-size:13px;color:#64748b;margin-bottom:20px}}
/* ===== Stat Row ===== */
.stat-row{{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:20px}}
.stat-box{{background:#fff;border-radius:12px;padding:20px;text-align:center;box-shadow:0 1px 4px rgba(0,0,0,.08)}}
.stat-num{{font-size:36px;font-weight:700}}
.stat-label{{font-size:13px;color:#64748b;margin-top:4px}}
/* ===== Badges & Pills ===== */
.badge{{padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600;color:#fff}}
.badge-o{{background:linear-gradient(135deg,#3b6fd4,#2558a8)}}.badge-e{{background:linear-gradient(135deg,#e07b2a,#c55e10)}}.badge-s{{background:linear-gradient(135deg,#2ea06d,#1d7a52)}}
.pill{{padding:3px 10px;border-radius:20px;font-size:11px;font-weight:700;color:#fff}}
.hm-high{{background:#e05252}}.hm-mid{{background:#e09b2a}}.hm-low{{background:#2ea06d}}
/* ===== Heatmap Table ===== */
.hm-table{{width:100%;border-collapse:collapse}}
.hm-table th{{background:#f8fafc;padding:10px 14px;text-align:left;font-size:12px;font-weight:600;color:#475569;border-bottom:2px solid #e2e8f0}}
.hm-table td{{padding:10px 14px;border-bottom:1px solid #f1f5f9;font-size:13px;vertical-align:middle}}
.hm-table tr:hover td{{background:#fafbff}}
.row-high{{border-left:3px solid #e05252}}.row-mid{{border-left:3px solid #e09b2a}}.row-low{{border-left:3px solid #2ea06d}}
.tc{{text-align:center}}.fw6{{font-weight:600}}.fw7{{font-weight:700}}.mono{{font-size:11px;color:#94a3b8;margin-top:2px}}
.muted{{color:#94a3b8}}.text-red{{color:#e05252}}.text-green{{color:#2ea06d}}.fs11{{font-size:11px}}.fs12{{font-size:12px}}.mt2{{margin-top:2px}}.mt4{{margin-top:4px}}
/* ===== Roadmap ===== */
.rm-phase{{background:#fff;border-radius:12px;padding:20px;margin-bottom:16px;box-shadow:0 1px 4px rgba(0,0,0,.08)}}
.rm-phase-head{{display:flex;align-items:center;gap:14px;margin-bottom:16px;padding-left:12px}}
.rm-num{{width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700;font-size:15px;flex-shrink:0}}
.rm-cards{{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px}}
.rm-card{{border:1px solid #e2e8f0;border-radius:8px;padding:14px;transition:.2s}}.rm-card:hover{{box-shadow:0 2px 8px rgba(0,0,0,.1)}}
.rm-card-top{{display:flex;justify-content:space-between;align-items:center}}

/* ===== 架构大图 ===== */
.bigmap-wrap{{background:#eef2f7;border-radius:14px;padding:28px}}
/* 全景图：L1色块 */
.l1-section{{margin-bottom:28px}}
.l1-section-label{{font-size:11px;font-weight:700;letter-spacing:1px;color:#94a3b8;margin-bottom:10px;padding-left:4px;text-transform:uppercase}}
.l1-grid{{display:flex;flex-wrap:wrap;gap:10px}}
.l1-block{{
  min-width:160px;flex:1;min-height:88px;
  border-radius:10px;padding:16px 18px;color:#fff;cursor:pointer;
  display:flex;flex-direction:column;justify-content:center;
  transition:all .25s ease;box-shadow:0 2px 8px rgba(0,0,0,.14);
  position:relative;
}}
.l1-block:hover{{transform:translateY(-4px);box-shadow:0 8px 24px rgba(0,0,0,.18)}}
.l1-block:active{{transform:translateY(-1px)}}
.l1-block .bn{{font-size:15px;font-weight:700;line-height:1.3}}
.l1-block .bc{{font-size:11px;opacity:.7;margin-top:4px}}
.l1-block .arrow{{position:absolute;right:14px;top:50%;transform:translateY(-50%);font-size:18px;opacity:.6}}
.l1-block.col-o{{background:linear-gradient(135deg,#3b6fd4,#2558a8)}}
.l1-block.col-e{{background:linear-gradient(135deg,#e07b2a,#c55e10)}}
.l1-block.col-s{{background:linear-gradient(135deg,#2ea06d,#1d7a52)}}

/* ===== 抽屉 ===== */
.drawer-mask{{display:none;position:fixed;inset:0;background:rgba(0,0,0,.35);z-index:200;backdrop-filter:blur(2px)}}
.drawer-mask.open{{display:block}}
.drawer{{position:fixed;right:-700px;top:0;bottom:0;width:700px;background:#fff;z-index:201;
  box-shadow:-8px 0 40px rgba(0,0,0,.18);transition:right .35s cubic-bezier(.4,0,.2,1);
  display:flex;flex-direction:column;overflow:hidden}}
.drawer.open{{right:0}}
.drawer-header{{padding:20px 24px;border-bottom:1px solid #e2e8f0;display:flex;align-items:center;gap:12px;flex-shrink:0}}
.drawer-header .dh-badge{{padding:4px 10px;border-radius:6px;color:#fff;font-size:12px;font-weight:600}}
.drawer-header .dh-title{{font-size:18px;font-weight:700;flex:1}}
.drawer-header .dh-close{{width:32px;height:32px;border-radius:8px;background:#f1f5f9;border:none;cursor:pointer;font-size:18px;display:flex;align-items:center;justify-content:center;color:#64748b;transition:.2s}}
.drawer-header .dh-close:hover{{background:#e2e8f0}}
.drawer-body{{flex:1;overflow-y:auto;padding:20px 24px}}
/* 面包屑 */
.breadcrumb{{display:flex;align-items:center;gap:8px;margin-bottom:16px;font-size:13px;color:#64748b}}
.breadcrumb .bc-item{{cursor:pointer;color:#2558a8}}.breadcrumb .bc-item:hover{{text-decoration:underline}}
.breadcrumb .sep{{color:#cbd5e1}}
/* L2 块 */
.l2-grid{{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin-bottom:8px}}
.l2-block{{
  border-radius:8px;padding:14px 16px;color:#fff;cursor:pointer;
  min-height:72px;display:flex;flex-direction:column;justify-content:center;
  transition:all .2s;box-shadow:0 1px 6px rgba(0,0,0,.12);
}}
.l2-block:hover{{transform:translateY(-3px);box-shadow:0 6px 18px rgba(0,0,0,.18)}}
.l2-block .bn{{font-size:13px;font-weight:600;line-height:1.3}}
.l2-block .bc{{font-size:10px;opacity:.7;margin-top:3px}}
/* L3 块 */
.l3-section-title{{font-size:13px;font-weight:600;color:#475569;margin:16px 0 8px;padding-bottom:4px;border-bottom:1px solid #e2e8f0}}
.l3-grid{{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:16px}}
.l3-block{{
  border-radius:6px;padding:7px 12px;color:#fff;
  font-size:12px;font-weight:500;
  box-shadow:0 1px 4px rgba(0,0,0,.1);
  transition:all .15s;
}}
.l3-block:hover{{transform:translateY(-2px);box-shadow:0 3px 10px rgba(0,0,0,.15)}}
/* 颜色类 */
.col-o{{background:linear-gradient(135deg,#3b6fd4,#2558a8)}}
.col-e{{background:linear-gradient(135deg,#e07b2a,#c55e10)}}
.col-s{{background:linear-gradient(135deg,#2ea06d,#1d7a52)}}
.col-o-l2{{background:linear-gradient(135deg,#4f82e0,#3b6fd4)}}
.col-e-l2{{background:linear-gradient(135deg,#f0913e,#e07b2a)}}
.col-s-l2{{background:linear-gradient(135deg,#3db880,#2ea06d)}}
.col-o-l3{{background:linear-gradient(135deg,#6799ea,#4f82e0)}}
.col-e-l3{{background:linear-gradient(135deg,#f5a55c,#f0913e)}}
.col-s-l3{{background:linear-gradient(135deg,#55c995,#3db880)}}
/* 图例 */
.legend{{display:flex;gap:20px;justify-content:center;margin-top:20px;flex-wrap:wrap}}
.legend-item{{display:flex;align-items:center;gap:6px;font-size:12px;color:#64748b}}
.legend-dot{{width:14px;height:14px;border-radius:3px}}
/* info card */
.info-card{{background:#fff;border-radius:12px;padding:20px 24px;margin-bottom:20px;box-shadow:0 1px 4px rgba(0,0,0,.08)}}
.info-row{{display:grid;grid-template-columns:1fr 1fr;gap:16px}}
.info-label{{font-size:12px;color:#94a3b8;margin-bottom:3px}}
.info-val{{font-size:14px;font-weight:500;color:#1e293b}}
.pain-tags{{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}}
.pain-tag{{padding:3px 10px;background:#fef2f2;color:#dc2626;border-radius:20px;font-size:12px}}
/* methodology */
.method-grid{{display:grid;grid-template-columns:1fr 1fr;gap:16px}}
.method-card{{border-left:4px solid #2558a8;padding:14px 16px;background:#f8faff;border-radius:0 8px 8px 0}}
.method-card.orange{{border-left-color:#e07b2a;background:#fff8f3}}
.method-card h4{{font-size:14px;font-weight:700;margin-bottom:8px}}
.method-card li{{font-size:13px;color:#475569;margin-bottom:4px;list-style:none;padding-left:14px;position:relative}}
.method-card li::before{{content:'·';position:absolute;left:4px;color:#94a3b8}}
footer{{background:#1e293b;color:#94a3b8;text-align:center;padding:20px;font-size:12px;margin-top:40px}}
/* Scrollbar */
.drawer-body::-webkit-scrollbar{{width:4px}}.drawer-body::-webkit-scrollbar-thumb{{background:#cbd5e1;border-radius:2px}}
</style>
</head>
<body>

<!-- 头部 -->
<header class="header">
  <div class="header-inner">
    <div>
      <p class="sub">流程架构规划方案</p>
      <h1>{company['name']}</h1>
      <p class="sub" style="margin-top:4px">基于华为OES方法论 · APQC框架</p>
    </div>
    <div class="header-meta">
      <p>规划日期：{company['planning_date']}</p>
      <p>行业：{company['industry']}</p>
      <p>规模：{company['scale']}</p>
    </div>
  </div>
</header>

<!-- 导航 -->
<nav class="nav">
  <div class="nav-inner">
    <button class="nav-btn active" onclick="showTab('overview',this)">总览</button>
    <button class="nav-btn" onclick="showTab('bigmap',this)">流程架构大图</button>
    <button class="nav-btn" onclick="showTab('heatmap',this)">能力热力图</button>
    <button class="nav-btn" onclick="showTab('architecture',this)">流程清单</button>
    <button class="nav-btn" onclick="showTab('roadmap',this)">建设路线图</button>
  </div>
</nav>

<main class="main">

  <!-- ===== 总览 ===== -->
  <div id="sec-overview" class="section active">
    <div class="stat-row">
      <div class="stat-box"><div class="stat-num" style="color:#2558a8">{arch['L1_count']}</div><div class="stat-label">L1 一级流程</div></div>
      <div class="stat-box"><div class="stat-num" style="color:#e07b2a">{arch['total_L2']}</div><div class="stat-label">L2 流程组</div></div>
      <div class="stat-box"><div class="stat-num" style="color:#2ea06d">{arch['total_L3']}</div><div class="stat-label">L3 具体流程</div></div>
      <div class="stat-box"><div class="stat-num" style="color:#7c3aed">{high_priority}</div><div class="stat-label">高优先级建设</div></div>
    </div>
    <div class="info-card">
      <p style="font-size:16px;font-weight:700;margin-bottom:14px">企业战略信息</p>
      <div class="info-row">
        <div><div class="info-label">企业愿景</div><div class="info-val">{company['vision']}</div></div>
        <div><div class="info-label">战略目标</div><div class="info-val">{company['strategy']}</div></div>
      </div>
      {'<div class="pain-tags" style="margin-top:14px">' + ''.join(f'<span class="pain-tag">{p}</span>' for p in company.get('pain_points', [])) + '</div>' if company.get('pain_points') else ''}
    </div>
    <div class="card">
      <p class="card-title">方法论框架</p>
      <p class="card-sub">融合华为OES分类法与APQC PCF国际标准</p>
      <div class="method-grid">
        <div class="method-card">
          <h4>华为 OES 分类法</h4>
          <ul>
            <li><span style="color:#3b6fd4;font-weight:600">运营类(O)</span>：直接为客户创造价值的端到端流程</li>
            <li><span style="color:#e07b2a;font-weight:600">使能类(E)</span>：响应运营需求，支撑价值实现</li>
            <li><span style="color:#2ea06d;font-weight:600">支撑类(S)</span>：提供基础公共服务</li>
          </ul>
        </div>
        <div class="method-card orange">
          <h4>APQC PCF 参考</h4>
          <ul>
            <li>国际通用的流程分类标准（12个L1领域）</li>
            <li>支持跨行业对标与基准比较</li>
            <li>L1→L2→L3→L4→L5 五层分级模型</li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <!-- ===== 流程架构大图 ===== -->
  <div id="sec-bigmap" class="section">
    <div class="card">
      <p class="card-title">流程架构全景图</p>
      <p class="card-sub">点击任意 L1 色块 → 查看该领域 L2 流程组 &nbsp;|&nbsp; 再点击 L2 → 查看 L3 具体流程</p>
      <div class="bigmap-wrap" id="bigmapContainer"></div>
      <div class="legend">
        <div class="legend-item"><div class="legend-dot" style="background:#3b6fd4"></div>运营类(O) · 直接创造价值</div>
        <div class="legend-item"><div class="legend-dot" style="background:#e07b2a"></div>使能类(E) · 支撑运营实现</div>
        <div class="legend-item"><div class="legend-dot" style="background:#2ea06d"></div>支撑类(S) · 基础公共服务</div>
      </div>
    </div>
  </div>

  <!-- ===== 能力热力图 ===== -->
  <div id="sec-heatmap" class="section">
    <div class="card">
      <p class="card-title">流程能力评估矩阵</p>
      <p class="card-sub">基于战略重要性与当前成熟度的差距分析，识别建设优先级</p>
      <div style="overflow-x:auto">
        <table class="hm-table">
          <thead><tr>
            <th>L1流程</th><th>分类</th><th class="tc">战略重要性</th>
            <th class="tc">当前成熟度</th><th class="tc">差距</th>
            <th class="tc">建设优先级</th><th class="tc">L2/L3</th>
          </tr></thead>
          <tbody>{heatmap_rows}</tbody>
        </table>
      </div>
    </div>
    <div class="card" style="padding:16px 20px">
      <p style="font-size:13px;font-weight:600;color:#475569;margin-bottom:10px">图例</p>
      <div style="display:flex;flex-wrap:wrap;gap:16px;font-size:12px;color:#64748b">
        <span><span class="pill hm-high" style="margin-right:4px">高</span>高重要性/成熟度/优先级</span>
        <span><span class="pill hm-mid" style="margin-right:4px">中</span>中等水平</span>
        <span><span class="pill hm-low" style="margin-right:4px">低</span>低优先级</span>
        <span style="padding-left:8px;border-left:2px solid #e2e8f0"><span style="display:inline-block;width:12px;height:12px;background:#fef2f2;border-left:3px solid #e05252;margin-right:4px"></span>高优先行</span>
      </div>
    </div>
  </div>

  <!-- ===== 流程清单 ===== -->
  <div id="sec-architecture" class="section">
    <div id="archListContainer"></div>
  </div>

  <!-- ===== 建设路线图 ===== -->
  <div id="sec-roadmap" class="section">
    {roadmap_html}
  </div>

</main>

<!-- 抽屉遮罩 -->
<div class="drawer-mask" id="drawerMask" onclick="closeDrawer()"></div>

<!-- 抽屉主体 -->
<div class="drawer" id="drawer">
  <div class="drawer-header">
    <div class="dh-badge" id="drawerBadge"></div>
    <div class="dh-title" id="drawerTitle"></div>
    <button class="dh-close" onclick="closeDrawer()">✕</button>
  </div>
  <div class="drawer-body">
    <div class="breadcrumb" id="drawerBreadcrumb"></div>
    <div id="drawerContent"></div>
  </div>
</div>

<footer>
  流程架构规划方案 · 华为OES方法论 + APQC框架 &nbsp;|&nbsp; 生成时间：{now_str}
</footer>

<script>
// =========== 数据 ===========
const L1_DATA = {arch_json};

// 颜色工具
function getCatColor(category, level) {{
  if (category.includes('运营')) {{
    return level === 1 ? 'col-o' : level === 2 ? 'col-o-l2' : 'col-o-l3';
  }} else if (category.includes('使能')) {{
    return level === 1 ? 'col-e' : level === 2 ? 'col-e-l2' : 'col-e-l3';
  }} else {{
    return level === 1 ? 'col-s' : level === 2 ? 'col-s-l2' : 'col-s-l3';
  }}
}}
function getBadgeClass(category) {{
  return category.includes('运营') ? 'badge-o' : category.includes('使能') ? 'badge-e' : 'badge-s';
}}
function getCatLabel(category) {{
  const m = category.match(/\\(([^)]+)\\)/);
  return m ? m[1] : '';
}}

// =========== 标签切换 ===========
function showTab(name, btn) {{
  document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
  document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
  document.getElementById('sec-' + name).classList.add('active');
  if (btn) btn.classList.add('active');
  if (name === 'bigmap') renderBigMap();
  if (name === 'architecture') renderArchList();
}}

// =========== 架构大图 ===========
let bigMapRendered = false;
function renderBigMap() {{
  if (bigMapRendered) return;
  bigMapRendered = true;
  const container = document.getElementById('bigmapContainer');

  // 按OES分类分组
  const groups = {{'运营类(Operating)': [], '使能类(Enabling)': [], '支撑类(Supporting)': []}};
  L1_DATA.forEach(l1 => groups[l1.category] && groups[l1.category].push(l1));

  const groupMeta = {{
    '运营类(Operating)': {{ label: 'O · 运营类', desc: '直接为客户创造价值' }},
    '使能类(Enabling)':  {{ label: 'E · 使能类', desc: '响应运营，支撑价值实现' }},
    '支撑类(Supporting)':{{ label: 'S · 支撑类', desc: '提供基础公共服务' }},
  }};

  let html = '';
  Object.keys(groups).forEach(cat => {{
    const list = groups[cat];
    if (!list.length) return;
    const meta = groupMeta[cat];
    const colCls = getCatColor(cat, 1);
    html += `<div class="l1-section">
      <div class="l1-section-label">${{meta.label}} &nbsp;—&nbsp; ${{meta.desc}}</div>
      <div class="l1-grid">`;
    list.forEach(l1 => {{
      html += '<div class="l1-block ' + colCls + '" data-code="' + l1.code + '" onclick="handleL1Click(this)">' +
        '<div class="bn">' + l1.name + '</div>' +
        '<div class="bc">' + l1.code + ' · ' + l1.L2_count + '个L2</div>' +
        '<span class="arrow">›</span>' +
        '</div>';
    }});
    html += `</div></div>`;
  }});

  container.innerHTML = html;
}}

// =========== 抽屉操作 ===========
function openDrawer(title, badgeClass, content, breadcrumbHtml) {{
  document.getElementById('drawerTitle').textContent = title;
  const badge = document.getElementById('drawerBadge');
  badge.className = 'dh-badge ' + badgeClass;
  badge.textContent = getCatLabelByBadge(badgeClass);
  document.getElementById('drawerContent').innerHTML = content;
  document.getElementById('drawerBreadcrumb').innerHTML = breadcrumbHtml || '';
  document.getElementById('drawerMask').classList.add('open');
  document.getElementById('drawer').classList.add('open');
}}
function closeDrawer() {{
  document.getElementById('drawerMask').classList.remove('open');
  document.getElementById('drawer').classList.remove('open');
}}
function getCatLabelByBadge(cls) {{
  if (cls.includes('badge-o')) return 'O · 运营类';
  if (cls.includes('badge-e')) return 'E · 使能类';
  return 'S · 支撑类';
}}

// 全局点击处理，用data属性传参，彻底避免引号嵌套
function handleL1Click(el) {{
  openL1Drawer(el.dataset.code);
}}
function handleBackL1(el) {{
  openL1Drawer(el.dataset.backL1);
}}

// 打开L1抽屉（显示该L1下所有L2）
function openL1Drawer(l1Code) {{
  const l1 = L1_DATA.find(l => l.code === l1Code);
  if (!l1) return;
  const colL2 = getCatColor(l1.category, 2);
  const badgeCls = getBadgeClass(l1.category);

  let html = '<p style="font-size:13px;color:#64748b;margin-bottom:16px">共 ' + l1.L2_count + ' 个流程组，点击任意 L2 块查看 L3 具体流程</p><div class="l2-grid">';

  l1.L2_processes.forEach(l2 => {{
    html += '<div class="l2-block ' + colL2 + '" onclick="openL2Drawer(this)" data-l1="' + l1Code + '" data-l2="' + l2.code + '">' +
      '<div class="bn">' + l2.name + '</div>' +
      '<div class="bc">' + l2.code + ' · ' + l2.L3_count + '个L3 ›</div>' +
      '</div>';
  }});
  html += '</div>';

  const bc = '<span class="bc-item" onclick="closeDrawer()">全景图</span>' +
    ' <span class="sep">›</span> ' +
    '<span style="color:#1e293b;font-weight:600">' + l1.name + '</span>';

  openDrawer(l1.name, badgeCls, html, bc);
}}

// 打开L2抽屉（显示该L2下所有L3）
function openL2Drawer(el) {{
  const l1Code = el.dataset.l1;
  const l2Code = el.dataset.l2;
  const l1 = L1_DATA.find(l => l.code === l1Code);
  if (!l1) return;
  const l2 = l1.L2_processes.find(l => l.code === l2Code);
  if (!l2) return;
  const colL3 = getCatColor(l1.category, 3);
  const badgeCls = getBadgeClass(l1.category);

  let html = '<p style="font-size:13px;color:#64748b;margin-bottom:16px">共 ' + l2.L3_count + ' 个 L3 流程</p><div class="l3-grid">';

  l2.L3_processes.forEach(name => {{
    html += '<div class="l3-block ' + colL3 + '">' + name + '</div>';
  }});
  html += '</div>';

  const bc = '<span class="bc-item" onclick="closeDrawer()">全景图</span>' +
    ' <span class="sep">›</span> ' +
    '<span class="bc-item" data-back-l1="' + l1Code + '" onclick="handleBackL1(this)">' + l1.name + '</span>' +
    ' <span class="sep">›</span> ' +
    '<span style="color:#1e293b;font-weight:600">' + l2.name + '</span>';

  openDrawer(l2.name, badgeCls, html, bc);
}}

// =========== 流程清单 ===========
let archListRendered = false;
function renderArchList() {{
  if (archListRendered) return;
  archListRendered = true;
  const container = document.getElementById('archListContainer');
  let html = '';
  L1_DATA.forEach(l1 => {{
    const badgeCls = getBadgeClass(l1.category);
    const catLabel = getCatLabel(l1.category);
    html += `<div class="card" style="margin-bottom:16px">
      <div style="display:flex;align-items:center;gap:10px;margin-bottom:12px">
        <span class="badge ${{badgeCls}}">${{catLabel}}</span>
        <span style="font-size:16px;font-weight:700">${{l1.name}}</span>
        <span style="font-size:12px;color:#94a3b8">${{l1.code}} · ${{l1.L2_count}}个流程组</span>
      </div>
      <p style="font-size:13px;color:#64748b;margin-bottom:14px">${{l1.description}}</p>`;

    l1.L2_processes.forEach(l2 => {{
      html += `<div style="background:#f8fafc;border-radius:8px;padding:12px 14px;margin-bottom:10px;border-left:3px solid #e2e8f0">
        <div style="display:flex;justify-content:space-between;margin-bottom:8px">
          <span style="font-size:13px;font-weight:600">${{l2.name}} <span style="color:#94a3b8;font-weight:400">${{l2.code}}</span></span>
          <span style="font-size:11px;color:#94a3b8">${{l2.L3_count}}个L3</span>
        </div>
        <div style="display:flex;flex-wrap:wrap;gap:6px">`;
      l2.L3_processes.forEach(name => {{
        html += `<span style="padding:3px 8px;background:#fff;border:1px solid #e2e8f0;border-radius:4px;font-size:12px;color:#475569">${{name}}</span>`;
      }});
      html += `</div></div>`;
    }});
    html += `</div>`;
  }});
  container.innerHTML = html;
}}

// ESC关闭抽屉
document.addEventListener('keydown', e => {{ if (e.key === 'Escape') closeDrawer(); }});
</script>
</body>
</html>'''

    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(html)
    return output_path


def main():
    result = generate_process_planning(
        company_name="示例制造科技有限公司",
        industry="制造业",
        vision="成为行业领先的智能制造企业",
        strategy="未来3年实现数字化转型，提升运营效率30%，构建端到端流程体系",
        scale="中型",
        pain_points=["流程割裂", "信息孤岛", "响应速度慢", "跨部门协同难"]
    )
    output_dir = os.path.join(os.path.dirname(__file__), "output")
    os.makedirs(output_dir, exist_ok=True)
    html_path = os.path.join(output_dir, "process_planning_report.html")
    generate_html_report(result, html_path)
    print(f"✅ 流程规划报告已生成：{html_path}")
    return html_path


if __name__ == "__main__":
    main()
