#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""修 baorui-sales/customer_attribution.json：补「刘子研」条目（大客户1岗）。

来源（可溯源）：
  A. 归属表内「大客户1」岗位 12 个集团（刘子研现为该项负责人）
  B. 归属表内 黄明月（10）+ 张立娅（10）—— 已离职，2026-09-20 交接改派给刘子研
  C. ERP 2026 1-9 月「销售员=刘子研」的实际成交客户（13 家），补充不在上述集团里的新增客户
"""
import json
import os
import shutil
from datetime import datetime

import pandas as pd

P = os.path.expanduser('~/.hermes/profiles/baorui-sales/customer_attribution.json')
ERP = os.path.expanduser('~/Desktop/hermas输入-工作台数据库/月度销售额数据/销售订单_20260101-20260930.xlsx')

A = json.load(open(P, encoding='utf-8'))
sp = A['salespeople']

# A + B：岗位与离职者名下集团
groups = []
for k in ('大客户1', '黄明月', '张立娅'):
    for c in (sp.get(k) or {}).get('customers', []):
        if c not in groups:
            groups.append(c)

# C：ERP 实际客户（剔除集团名已覆盖的）
d = pd.read_excel(ERP, sheet_name='Sheet1')
d['_sp'] = d['销售员'].astype(str).str.strip()
d['_c'] = d['客户'].astype(str).str.strip()
erp_custs = sorted({c for c in d.loc[d['_sp'] == '刘子研', '_c'] if c and c != 'nan'})

# 集团名与其成员公司的对应（用于去重：ERP 客户已含在集团里的不入列）
GROUP_KEYS = {
    '丽珠集团': ['丽珠'], '天隆集团': ['天隆'], '苏州华益美生物科技有限公司': ['华益美'],
    '佰奥莱博集团': ['佰奥莱博'], '海尔施集团': ['海尔施'], '东方基因集团': ['东方基因'],
    '复星集团': ['复星'], '杭州迪安生物技术有限公司': ['迪安'], '艾康生物技术（杭州）有限公司': ['艾康'],
    '深圳市新产业生物医学工程股份有限公司': ['新产业'], '安瑞科集团': ['安瑞科'],
    '中国人民解放军陆军军医大学第一附属医院': ['陆军军医大学'],
}
covered = [c for c in erp_custs if any(k in c for kws in GROUP_KEYS.values() for k in kws)]
new_custs = [c for c in erp_custs if c not in covered]

customers = groups + [c for c in new_custs if c not in groups]

shutil.copy2(P, P + '.bak_before_liuziyan_' + datetime.now().strftime('%Y%m%d_%H%M%S'))
sp['刘子研'] = {
    'dept': '大客户部',
    'region': '大客户1',
    'customer_count': len(customers),
    'customers': customers,
    '_来源': '大客户1岗（含 2026-09-20 离职交接：黄明月/张立娅→刘子研）+ ERP 2026 实际成交客户',
    '_生成时间': datetime.now().strftime('%Y-%m-%d %H:%M'),
    '_备注': '此前该岗位在旧花名册里挂在已离职的黄明月/张立娅与「大客户1」分组下，故新建本人条目',
}
for k in ('黄明月', '张立娅'):
    if k in sp:
        sp[k]['_备注'] = '已离职（2026-05）；名下客户已于 2026-09-20 交接给刘子研，此处保留仅作历史存档'

A['salespeople'] = sp
A['total_salespeople'] = len(sp)
A['total_customers'] = sum((v or {}).get('customer_count', 0) for v in sp.values())
A['_更新记录'] = A.get('_更新记录', []) + [{
    '时间': datetime.now().strftime('%Y-%m-%d %H:%M'),
    '动作': '新增「刘子研」条目（大客户1岗，%d 个客户）' % len(customers),
    '原因': '归属表缺该条目 → 销售助手按其 user_id 鉴权后查不到名下客户，误报无权限',
}]
json.dump(A, open(P, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
os.chmod(P, 0o600)

print('✅ 已补「刘子研」条目：%d 个客户' % len(customers))
for c in customers:
    print('   ·', c)
print()
print('  其中新增（来自 ERP、不在原岗位集团内）：', new_custs)
print('  归属表：%d 人 ｜ %d 客户（含集团口径，非去重客户数）' % (A['total_salespeople'], A['total_customers']))
