#!/usr/bin/env python3
"""按月生成独立Excel文件 - 里程考核绩效（含亏损筛选）"""
import os, openpyxl
from calc_engine import *
from excel_writer import *

os.chdir('/Users/kkfluous/Downloads')

# 读取
print("读取源数据...")
D = {1: read_file('租赁任务考核_2026年1月.xlsx', 1),
     2: read_file('租赁任务考核_2026年2月.xlsx', 2),
     3: read_file('租赁任务考核_2026年3月.xlsx', 3)}
for m in [1,2,3]: print(f"  {m}月: {len(D[m])}条")

# 分组+计算
G = {m: grp(D[m], m) for m in [1,2,3]}
calc_jan_carryover(G[1])
feb_data = calc_feb(G[1], G[2])
mar_data = calc_mar(G[1], G[2], G[3], feb_data)

# 发放追踪
vehicle_payments, vehicle_info = collect_vehicle_payments(G, feb_data, mar_data)
master_vehicles = read_master_vehicles()

# 亏损表
print("\n读取亏损表...")
loss_data = {}
for m in [1,2,3]:
    ld = read_loss_data(m)
    if ld:
        loss_clients = sum(1 for v in ld.values() if v == '是')
        print(f"  {m}月: {len(ld)}个客户, 其中亏损{loss_clients}个")
        loss_data[m] = ld
    else:
        print(f"  {m}月: 无亏损表")
        loss_data[m] = None

# 车牌→客户名称映射
plate_client = get_vehicle_client_map(D)

# 所有业务员
all_persons = {}
for m in G:
    for k, g in G[m].items():
        all_persons[g['销售']] = g['部门']

# 打印汇总
jan_total = sum(r['奖金'] for r in D[1] if r['是否达标']=='达标')
feb_total = sum(sum(d['额'] for d in v) for v in feb_data.values())
mar_total = sum(sum(d['额'] for d in v) for v in mar_data.values())
print(f"\n考核应发: 1月{jan_total:.2f}, 2月{feb_total:.2f}, 3月{mar_total:.2f}")
print(f"Q1考核应发合计: {jan_total + feb_total + mar_total:.2f}")

# ============================================================
# 按月生成
# ============================================================
for settle_month in [1, 2, 3]:
    print(f"\n生成 {settle_month}月核算文件...")
    wb = openpyxl.Workbook()

    # 当月数据
    if settle_month == 1:
        month_data = {'当月': [{'车牌':r['车牌号'],'销售':r['销售经理'],'部门':r['部门名称'],'额':r['奖金']}
                               for r in D[1] if r['是否达标']=='达标']}
    elif settle_month == 2:
        month_data = feb_data
    else:
        month_data = mar_data

    # Sheet 1: 考核奖励规则
    write_rules_sheet(wb)

    # Sheet 2: 里程明细
    write_detail_sheet(wb, D[settle_month], settle_month)

    # Sheet 3: 计算过程
    if settle_month == 1:
        write_calc_process_jan(wb, G[1])
    elif settle_month == 2:
        write_calc_process_feb(wb, G[1], G[2])
    else:
        write_calc_process_mar(wb, G[1], G[2], G[3], feb_data)

    # Sheet 5: 车辆考核追踪
    write_vehicle_tracking_sheet(wb, settle_month, G, master_vehicles, vehicle_payments, vehicle_info, loss_data[settle_month], plate_client)

    # Sheet 6: 奖金发放记录（叠加亏损筛选，补发查对应月盈亏）
    payment_records = build_payment_records(settle_month, month_data, loss_data, plate_client)
    write_payment_record_sheet(wb, settle_month, payment_records)

    # Sheet 7: 月汇总（从发放记录生成）
    write_summary_from_records(wb, settle_month, payment_records)

    # Sheet 6-17: 业务员
    for person in sorted(all_persons.keys()):
        write_salesperson_sheet(wb, person, all_persons[person], settle_month, D, G, month_data, vehicle_payments)

    # 删除默认空sheet
    if 'Sheet' in wb.sheetnames:
        del wb['Sheet']

    fname = f'里程任务考核_{settle_month}月核算.xlsx'
    wb.save(fname)
    print(f"  ✅ {fname} ({len(wb.sheetnames)} sheets)")
