#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""科研秋季促销 · 分区域统计 HTML"""
import json
import os
import sys

sys.path.insert(0, '/Users/liuxinyuan/Desktop/Hermes输出-工作类/脚本')
import brand_kit as BK  # noqa: E402

W = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
d = json.load(open(os.path.join(W, '数据/promo_stats_2026.json'), encoding='utf-8'))
OUT = os.path.join(W, '营销活动/科研秋季促销_分区域统计_2026.html')

TIER_CLS = {'10W': 't10', '5W': 't5', '2W': 't2', '1W': 't1', '5K': 't5k', '2K': 't2k', '1K': 't1k', '未达标': 'none'}


def row(r):
    return ('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td class="n">%d</td>'
            '<td class="n">%s</td><td><span class="tier %s">%s</span></td>'
            '<td class="n">%s</td><td class="n">%s</td></tr>') % (
        r[0], r[1], r[2], r[3] or '—', r[4], '{:,.2f}'.format(r[5]), TIER_CLS.get(r[6], 'none'), r[6],
        '{:,}'.format(r[7]) if r[7] else '—', '{:,}'.format(r[8]) if r[8] else '—')


detail = ''.join(row(r) for r in d['detail'])
sales = ''.join('<tr><td>%s</td><td>%s</td><td class="n">%d</td><td class="n">%d</td><td class="n">%s</td></tr>' % (
    s[0], s[1], s[2], s[3], '{:,.2f}'.format(s[4])) for s in sorted(d['sales'], key=lambda x: (x[0], -x[4])))

GD, ZJ = d['summary'].get('广东', {}), d['summary'].get('浙江', {})


def kpi(name, s, color):
    return ('<div class="k"><div class="t">%s</div><b>%s</b><span>销售额（元）</span>'
            '<div class="sub">客户 %d ｜订单 %d ｜达档 %d<br>赠品预算 %s–%s 元</div></div>') % (
        name, '{:,.2f}'.format(s.get('amount', 0)), s.get('customers', 0), s.get('orders', 0),
        s.get('hit', 0), '{:,}'.format(s.get('gift_lo', 0)), '{:,}'.format(s.get('gift_hi', 0)))


page = """<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>科研秋季促销 · 分区域统计</title><style>
*{box-sizing:border-box}body{margin:0;background:#f4f6fa;font-family:-apple-system,"PingFang SC",sans-serif;color:#1b2430;font-size:13px;line-height:1.6}
.wrap{max-width:1240px;margin:0 auto;padding:0 16px 40px}
h1{font-size:21px;margin:14px 0 4px}.sub0{color:#5f6b7a;font-size:12.4px;margin-bottom:12px}
.kpis{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:14px}
.k{background:#fff;border:1px solid #e3e8f1;border-radius:10px;padding:12px 14px}
.k .t{font-size:12.5px;color:#5f6b7a}.k b{display:block;font-size:24px;color:#1852B6;margin:2px 0}
.k span{font-size:11.4px;color:#8a94a3}.k .sub{margin-top:5px;font-size:11.8px;color:#43505f}
.card{background:#fff;border:1px solid #e3e8f1;border-radius:10px;padding:13px 15px;margin-bottom:13px}
.card h2{font-size:14.5px;margin:0 0 9px;padding-left:9px;border-left:3px solid #1F4E79}
table{width:100%%;border-collapse:collapse;font-size:12px}
th{background:#1F4E79;color:#fff;padding:6px 7px;text-align:left;position:sticky;top:0}
td{padding:5px 7px;border-bottom:1px solid #eef1f6;vertical-align:top}
td.n{text-align:right;font-variant-numeric:tabular-nums}
.scroll{max-height:560px;overflow:auto;border:1px solid #eef1f6;border-radius:8px}
.tier{display:inline-block;border-radius:4px;padding:1px 7px;font-size:10.8px;font-weight:700}
.tier.t10{background:#1F4E79;color:#fff}.tier.t5{background:#1852B6;color:#fff}.tier.t2{background:#4FA3E3;color:#fff}
.tier.t1{background:#A8C8EA;color:#0E2E63}.tier.t5k{background:#CFE0F5;color:#0E2E63}
.tier.t2k{background:#E3F4EA;color:#1B7A43}.tier.t1k{background:#F0F7E9;color:#3d6b1f}.tier.none{background:#EEF1F6;color:#8a94a3}
.note{background:#FFF6E5;border:1px solid #F3D9A6;border-radius:8px;padding:9px 11px;font-size:12.1px;margin-top:9px}
@media(max-width:900px){.kpis{grid-template-columns:1fr}.bior-tagwrap{display:none!important}}
</style></head><body><div class="wrap">
<h1>科研秋季开学促销 · 分区域统计</h1>
<div class="sub0">广东：%(gdw)s ｜浙江：%(zjw)s ｜金额口径：ERP 价税合计（剔除赠品与测试单）｜生成 2026-10-18</div>

<div class="kpis">
%(k1)s
%(k2)s
</div>

<div class="card"><h2>按客户（达档与赠品预算） <span>%(n)d 家</span></h2>
<div class="scroll"><table><thead><tr><th style="width:6%%">区域</th><th style="width:8%%">主跟销售</th><th style="width:22%%">客户</th>
<th style="width:18%%">课题组/项目</th><th style="width:6%%">订单</th><th style="width:11%%">采购额(元)</th>
<th style="width:9%%">达标档位</th><th style="width:8%%">赠品下限</th><th style="width:8%%">赠品上限</th></tr></thead>
<tbody>%(detail)s</tbody></table></div></div>

<div class="card"><h2>按销售员</h2>
<div class="scroll"><table><thead><tr><th style="width:8%%">区域</th><th style="width:10%%">销售员</th>
<th style="width:10%%">客户数</th><th style="width:10%%">订单数</th><th>销售额(元)</th></tr></thead>
<tbody>%(sales)s</tbody></table></div></div>

<div class="card"><h2>口径与说明</h2><div class="note">
<ul style="margin:4px 0 0 18px;padding:0">
<li>广东窗口 %(gdw)s，ERP 实际数据截至 <b>%(gdm)s</b>（10-16 无导出，末 1 天缺）；浙江窗口 %(zjw)s，数据截至 <b>%(zjm)s</b>。</li>
<li>仅统计生命科学部销售员名下订单；区域按销售员归属（非客户注册地）。</li>
<li>剔除测试销售订单与赠品行；金额为价税合计。</li>
<li>档位：1K≥1,000；2K≥2,000；5K≥5,000；1W≥10,000；2W≥20,000；5W≥50,000；10W≥100,000 元。</li>
<li>赠品价值按活动方案 5%%–10%% 折算，取档位给定上下限。</li>
</ul></div></div>
%(footer)s
</div></body></html>""" % {
    'gdw': '~'.join(d['windows']['广东']), 'zjw': '~'.join(d['windows']['浙江']),
    'gdm': d['max_date'].get('广东', ''), 'zjm': d['max_date'].get('浙江', ''),
    'k1': kpi('广东', GD, '#1852B6'), 'k2': kpi('浙江', ZJ, '#0F9D8F'),
    'detail': detail, 'sales': sales, 'n': len(d['detail']), 'footer': '__F__',
}
page = BK.inject(page, theme='dark', tag='科研秋季促销 · 分区域统计',
                 footer_extra='内部资料 · 不对外 ｜ 金额与档位均可回溯 ERP 订单')
page = page.replace('__F__', '')
open(OUT, 'w', encoding='utf-8').write(page)
print('✅', OUT, '%.0f KB' % (len(page.encode()) / 1024))
