#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""用用户提供的《销售订单_2026年9月（含备货部门）》统计「分子试剂产品部」的货号与金额。

用法: python3 _stat_9月含备货部门.py <xlsx路径> [部门名]
特点：自动探测表头行（含「备货部门」的那一行），容忍前置标题/空行。
"""
import os
import sys
import pandas as pd

path = sys.argv[1]
dept = sys.argv[2] if len(sys.argv) > 2 else '分子试剂产品部'
OUT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/销售分析/%s_2026年9月_货号金额_定版.xlsx' % dept

# 自动探测表头行
raw = pd.read_excel(path, sheet_name=0, header=None)
hdr = 0
for i in range(min(12, len(raw))):
    row = [str(x) for x in raw.iloc[i].tolist()]
    if any('备货部门' in c for c in row):
        hdr = i
        break
df = pd.read_excel(path, sheet_name=0, header=hdr)
df.columns = [str(c).strip() for c in df.columns]
print('数据源: %s\n表头行: 第 %d 行 ｜ 形状 %d 行 × %d 列' % (os.path.basename(path), hdr + 1, df.shape[0], df.shape[1]))
print('列名:', ' / '.join(df.columns[:30]))

if '备货部门' not in df.columns:
    print('❌ 未找到「备货部门」列'); sys.exit(1)

sub = df[df['备货部门'].astype(str).str.strip() == dept].copy()
print('\n① 备货部门=%s：%d 行 ｜ 价税合计 %.2f' % (dept, len(sub), pd.to_numeric(sub['价税合计'], errors='coerce').sum()))
if sub.empty:
    print('   该部门在本表中无记录。全部部门取值：', dict(df['备货部门'].value_counts().head(12)))
    sys.exit(0)

# 标准口径（列存在才用）
keep = pd.Series(True, index=sub.index)
if '单据类型' in sub.columns:
    keep &= sub['单据类型'].astype(str).str.contains('标准销售订单', na=False)
if '单据状态' in sub.columns:
    keep &= sub['单据状态'].astype(str).str.contains('已审核', na=False)
if '是否赠品' in sub.columns:
    keep &= ~sub['是否赠品'].astype(str).str.strip().isin(['是', 'Y', 'True', 'true'])
if '客户' in sub.columns:
    keep &= ~sub['客户'].astype(str).str.contains('宝锐|宝泰|横琴', na=False, regex=True)
if '业务关闭' in sub.columns:
    keep &= ~sub['业务关闭'].astype(str).str.contains('作废|业务终止', na=False, regex=True)
dd = sub[keep]
print('② 过标准口径：%d 行（剔除 %d 行）｜ 价税合计 %.2f' % (len(dd), len(sub) - len(dd),
      pd.to_numeric(dd['价税合计'], errors='coerce').sum()))

hk = '货号#' if '货号#' in dd.columns else ('货号' if '货号' in dd.columns else None)
nm = '物料名称' if '物料名称' in dd.columns else None
if hk is None:
    print('❌ 未找到货号列'); print(dd.head(3).to_string(max_colwidth=16)); sys.exit(1)
keys = [hk] + ([nm] if nm else [])
by = (dd.assign(价税合计=pd.to_numeric(dd['价税合计'], errors='coerce'))
        .groupby(keys, dropna=False)
        .agg(金额=('价税合计', 'sum'), 数量=('销售数量', 'sum'), 单数=('单据编号', 'nunique'))
        .sort_values('金额', ascending=False))
print('\n③ 按货号汇总：共 %d 个货号 ｜ 合计 %.2f' % (len(by), by['金额'].sum()))
for k, r in by.iterrows():
    h = k[0] if isinstance(k, tuple) else k
    n = k[1] if isinstance(k, tuple) and len(k) > 1 else ''
    print('   %-16s %-30s %11.2f %9.2f %2d单' % (str(h)[:16], str(n)[:28], r['金额'], r['数量'], r['单数']))

os.makedirs(os.path.dirname(OUT), exist_ok=True)
with pd.ExcelWriter(OUT) as w:
    by.reset_index().to_excel(w, sheet_name='按货号汇总', index=False)
    dd.to_excel(w, sheet_name='明细', index=False)
print('\n→ %s' % OUT)
