# -*- coding: utf-8 -*-
"""验证：档案归属 vs 官方客户清单"""
import json, collections, os

B = "/Users/liuxinyuan/Desktop/Hermes输出-工作类/"
au = json.load(open(next(f"/Users/liuxinyuan/Desktop/Hermes输出-工作类/数据/pricing/{f}"
                         for f in os.listdir(B+"数据/pricing") if f.startswith('_auth_customers_')), encoding='utf-8'))
c36 = json.load(open(B+"数据/customer_360.json", encoding='utf-8'))['customers']
auth = {k: v['sp'] for k, v in au['customers'].items()}
byl = au['by_line']

print(f"官方清单: {len(auth)} 客户 / 双线 {au['_meta']['multi_line_customers']} / 集团 {au['_meta']['group_count']}")
print(f"档案: {len(c36)} 客户")

both = [c for c in c36 if c['name'] in auth]
same = [c for c in both if c.get('sales') == auth[c['name']]]
print(f"\n① 在官方清单内的档案客户: {len(both)}/{len(c36)}   一致={len(same)}  不一致={len(both)-len(same)}")
bad = [c for c in both if c.get('sales') != auth[c['name']]]
for c in sorted(bad, key=lambda x: -x['total'])[:15]:
    print(f"   {c['name'][:30]:32s} 档案={c.get('sales') or '(空)':8s} 官方={auth[c['name']]:8s} {c['total']/10000:>7.1f}万")

print(f"\n② 归属来源 sales_source 分布:")
for k, v in collections.Counter(c.get('sales_source') or '(空)' for c in c36).most_common():
    amt = sum(c['total'] for c in c36 if (c.get('sales_source') or '(空)') == k)
    print(f"   {k:14s} {v:>4d} 客户  {amt/10000:>9.1f}万")

print(f"\n③ 无归属客户: {len([c for c in c36 if not c.get('sales')])}")
for c in [c for c in c36 if not c.get('sales')][:10]:
    print(f"   {c['name'][:36]:38s} {c['total']/10000:>8.1f}万")

print(f"\n④ 离职人员残留: ", {k: v for k, v in collections.Counter(c.get('sales') for c in c36).items()
                          if k in ('张立娅', '龙友波', '黄明月', '黄建佳', '黄自鑫', '赵以诺', '段玉', '梁莹莹', '曾琦', '李岚风')})

per = collections.Counter(c.get('sales') or '(空)' for c in c36)
amt = collections.defaultdict(float)
for c in c36: amt[c.get('sales') or '(空)'] += c['total']
print(f"\n⑤ 档案归属分布（{len([k for k in per if k!='(空)'])} 人）:")
for k, v in per.most_common():
    print(f"   {k:18s} {v:>4d} 客户  {amt[k]/10000:>9.1f}万")

print(f"\n⑥ 业务线 sales_line 分布:", dict(collections.Counter(c.get('sales_line') or '(空)' for c in c36)))
print(f"⑦ 集团字段非空: {len([c for c in c36 if c.get('group')])}")
mism = [c for c in c36 if len(byl.get(c['name'], {})) > 1]
print(f"⑧ 档案里的双线客户: {len(mism)}")
for c in mism[:8]:
    print(f"   {c['name'][:30]:32s} 档案sales={c.get('sales')} 双线={byl[c['name']]}")
