#!/usr/bin/env python3
"""B4: 月报台账看板 HTML 汇总 (2026-06-08)"""
import json, csv
from pathlib import Path
from datetime import date

DATA_DATE = '2026-06-08'
BASE = Path('/mnt/y/Openclaw_Hub/03.资源/实施项目 wiki/dashboard/data') / DATA_DATE / 'cleaned'
TODAY = date.today().strftime('%Y-%m-%d')

# Load all validation reports
reports = {}
for name in ['validation_report', 'tracking_validation', 'revenue_validation']:
    p = BASE / f'{name}.json'
    if p.exists():
        with open(p, encoding='utf-8') as f:
            reports[name] = json.load(f)

# Load project summaries
methods_ps = []
with open(BASE / 'project_summary.csv', encoding='utf-8-sig') as f:
    methods_ps = list(csv.DictReader(f))

tracking_ps = []
with open(BASE / 'tracking_project_summary.csv', encoding='utf-8-sig') as f:
    tracking_ps = list(csv.DictReader(f))

revenue_ps = []
with open(BASE / 'revenue_active.csv', encoding='utf-8-sig') as f:
    revenue_ps = list(csv.DictReader(f))

# Build HTML
m = reports.get('validation_report', {}).get('summary', {})
t = reports.get('tracking_validation', {})
r = reports.get('revenue_validation', {})

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>中东区域公司 技术部月报台账看板 | {DATA_DATE}</title>
<style>
* {{ margin:0; padding:0; box-sizing:border-box; }}
body {{ font-family: 'Microsoft YaHei', 'PingFang SC', sans-serif; background:#0f172a; color:#e2e8f0; padding:20px; }}
.header {{ text-align:center; padding:30px 0; border-bottom:2px solid #1e3a5f; margin-bottom:30px; }}
.header h1 {{ color:#c8962e; font-size:28px; }}
.header p {{ color:#64748b; margin-top:8px; }}
.grid {{ display:grid; grid-template-columns:repeat(3,1fr); gap:20px; margin-bottom:30px; }}
.card {{ background:#1e293b; border-radius:12px; padding:20px; border:1px solid #334155; }}
.card h2 {{ color:#c8962e; font-size:16px; margin-bottom:15px; padding-bottom:10px; border-bottom:1px solid #334155; }}
.metric {{ display:flex; justify-content:space-between; padding:8px 0; border-bottom:1px solid #1e293b; }}
.metric .label {{ color:#94a3b8; }}
.metric .value {{ font-weight:bold; font-size:18px; }}
.value.good {{ color:#22c55e; }}
.value.warn {{ color:#f59e0b; }}
.value.bad {{ color:#ef4444; }}

.table-wrap {{ background:#1e293b; border-radius:12px; padding:20px; margin-bottom:20px; border:1px solid #334155; }}
.table-wrap h2 {{ color:#c8962e; font-size:18px; margin-bottom:15px; }}
table {{ width:100%; border-collapse:collapse; font-size:13px; }}
th {{ background:#0f172a; color:#c8962e; padding:10px 8px; text-align:left; position:sticky; top:0; }}
td {{ padding:8px; border-bottom:1px solid #1e293b; }}
tr:hover {{ background:#1e3a5f; }}
.bar {{ display:inline-block; height:8px; border-radius:4px; background:#22c55e; }}
.bar-bg {{ background:#334155; border-radius:4px; width:100%; height:8px; display:inline-block; }}
.red {{ color:#ef4444; }}
.orange {{ color:#f59e0b; }}
.green {{ color:#22c55e; }}
.num {{ text-align:right; font-variant-numeric:tabular-nums; }}
.footer {{ text-align:center; color:#475569; padding:20px; font-size:12px; }}
</style>
</head>
<body>

<div class="header">
<h1>🏗️ 中东区域公司 · 技术部月报台账看板</h1>
<p>数据日期：{DATA_DATE} | 生成时间：{TODAY} | 数据来源：OA项管平台</p>
</div>

<!-- KPI Cards -->
<div class="grid">
<div class="card">
<h2>📋 危大方案编审进度</h2>
<div class="metric"><span class="label">有效方案总数</span><span class="value">{m.get('有效方案','N/A')}</span></div>
<div class="metric"><span class="label">超一定规模</span><span class="value">{m.get('超规','N/A')}</span></div>
<div class="metric"><span class="label">已审批</span><span class="value good">{m.get('已审批','N/A')}</span></div>
<div class="metric"><span class="label">审批率</span><span class="value {'good' if '49' in str(m.get('审批率','')) or '50' in str(m.get('审批率','')) else 'warn'}">{m.get('审批率','N/A')}</span></div>
<div class="metric"><span class="label">预警信号</span><span class="value {'warn' if m.get('预警',0)>0 else 'good'}">{m.get('预警',0)}</span></div>
<div class="metric"><span class="label">覆盖项目</span><span class="value">{m.get('项目','N/A')}</span></div>
</div>

<div class="card">
<h2>🔄 项目启动动态跟踪</h2>
<div class="metric"><span class="label">跟踪项目数</span><span class="value">{t.get('me_projects','N/A')}</span></div>
<div class="metric"><span class="label">总任务数</span><span class="value">{t.get('total_tasks','N/A')}</span></div>
<div class="metric"><span class="label">已完成</span><span class="value good">{t.get('completed','N/A')}</span></div>
<div class="metric"><span class="label">逾期</span><span class="value {'bad' if t.get('overdue',0)>500 else 'warn'}">{t.get('overdue','N/A')}</span></div>
<div class="metric"><span class="label">完成率</span><span class="value">{int(t.get('completed',0))/int(t.get('total_tasks',1))*100:.0f}%</span></div>
</div>

<div class="card">
<h2>💰 营业额与产值</h2>
<div class="metric"><span class="label">活跃在建项目</span><span class="value">{r.get('active','N/A')}</span></div>
<div class="metric"><span class="label">签约合同额</span><span class="value">${r.get('contract',0)/10000:,.0f}万</span></div>
<div class="metric"><span class="label">本年营业收入</span><span class="value good">${r.get('annual',0)/10000:,.0f}万</span></div>
<div class="metric"><span class="label">本月营业收入</span><span class="value">${r.get('monthly',0)/10000:,.0f}万</span></div>
<div class="metric"><span class="label">累计营业收入</span><span class="value">${r.get('cumulative',0)/10000:,.0f}万</span></div>
</div>
</div>

<!-- 危大方案 Top 15 -->
<div class="table-wrap">
<h2>📋 危大方案编审 — 项目排行 Top 15</h2>
<table>
<tr><th>项目名称</th><th class="num">方案总数</th><th class="num">已审批</th><th class="num">超规</th><th class="num">预警</th><th class="num">审批率</th><th>国别</th></tr>
'''
for row in methods_ps[:15]:
    name = row.get('项目名称','')[:55]
    total = row.get('方案总数','0')
    approved = row.get('已审批','0')
    oversize = row.get('超规','0')
    red_w = int(row.get('红色预警','0'))
    orange_w = int(row.get('橙色预警','0'))
    warn_str = ''
    if red_w > 0: warn_str += f'<span class="red">🔴{red_w}</span> '
    if orange_w > 0: warn_str += f'<span class="orange">🟠{orange_w}</span>'
    if not warn_str: warn_str = '-'
    rate = row.get('审批率','0%')
    country = row.get('国别','')
    html += f'<tr><td>{name}</td><td class="num">{total}</td><td class="num">{approved}</td><td class="num">{oversize}</td><td class="num">{warn_str}</td><td class="num">{rate}</td><td>{country}</td></tr>\n'

html += '''</table></div>

<!-- 项目启动跟踪 逾期Top 15 -->
<div class="table-wrap">
<h2>🔄 项目启动跟踪 — 逾期项目 Top 15</h2>
<table>
<tr><th>项目名称</th><th class="num">总任务</th><th class="num">已完成</th><th class="num">逾期</th><th class="num">完成率</th><th>进度</th></tr>
'''
for row in tracking_ps[:15]:
    name = row.get('项目名称','')[:55]
    total = int(row.get('总任务数','0'))
    done = int(row.get('已完成','0'))
    overdue = int(row.get('逾期','0'))
    rate = row.get('完成率','0%')
    pct = int(done/total*100) if total > 0 else 0
    bar_color = '#ef4444' if pct < 30 else '#f59e0b' if pct < 60 else '#22c55e'
    html += f'<tr><td>{name}</td><td class="num">{total}</td><td class="num">{done}</td><td class="num"><span class="red">{overdue}</span></td><td class="num">{rate}</td><td><span class="bar-bg"><span class="bar" style="width:{pct}%;background:{bar_color}"></span></span></td></tr>\n'

html += '''</table></div>

<!-- 营收 Top 15 -->
<div class="table-wrap">
<h2>💰 活跃在建项目营收 Top 15</h2>
<table>
<tr><th>项目名称</th><th class="num">合同额($万)</th><th class="num">本年营收($万)</th><th class="num">本月营收($万)</th><th class="num">累计营收($万)</th><th>国别</th></tr>
'''
for row in revenue_ps[:15]:
    name = row.get('项目名称','')[:55]
    contract = float(row.get('合同额','0') or 0)
    annual = float(row.get('本年营收','0') or 0)
    monthly = float(row.get('本月营收','0') or 0)
    cumulative = float(row.get('累计营收','0') or 0)
    country = row.get('国别','')
    html += f'<tr><td>{name}</td><td class="num">{contract:,.0f}</td><td class="num">{annual:,.0f}</td><td class="num">{monthly:,.0f}</td><td class="num">{cumulative:,.0f}</td><td>{country}</td></tr>\n'

html += f'''</table></div>

<div class="footer">
<p>中国港湾中东区域公司 技术部 | 数据来源：OA项管平台 | 自动生成于 {TODAY}</p>
<p>原始数据路径：Y:\\Openclaw_Hub\\03.资源\\实施项目 wiki\\raw\\月报数据\\{DATA_DATE}\\</p>
</div>

</body></html>'''

OUT = BASE / 'dashboard.html'
with open(OUT, 'w', encoding='utf-8') as f:
    f.write(html)

print(f'✅ Dashboard HTML: {OUT}')
print(f'   Size: {len(html):,} bytes')
