import json, subprocess, sys
from collections import defaultdict
from urllib.parse import quote

with open('/tmp/haiyi_token.txt') as f:
    token = f.read().strip()

# Fetch device list
subprocess.run(['curl', '-s', '-H', f'Authorization: Bearer {token}',
    '-o', '/tmp/haiyi_cabinets2.json',
    'https://m.hykj.cn/locker-sub-merchant/api/sub/subweighingCabinet/getCabinetInfo'], timeout=30)

with open('/tmp/haiyi_cabinets2.json') as f:
    raw = json.load(f)

gd_kw = ['广东','广州','深圳','珠海','汕头','佛山','韶关','河源','梅州','惠州','汕尾','东莞','中山','江门','阳江','湛江','茂名','肇庆','清远','潮州','揭阳','云浮','从化','英德','佛冈','南昆山','花都','三水','南丹山','新丰','丹霞','翁源','龙泰','宝晶宫','积庆里','聚龙湾','悦天下','巴伐利亚']

haiyi_gd = {}
for item in raw:
    v = item.get('value', {})
    nm = v.get('deviceName') or v.get('containerAddress') or ''
    addr = v.get('detailedAddress', '') or ''
    rn = item.get('label', '')
    combined = f"{nm} {addr}"
    if any(k in combined for k in gd_kw):
        haiyi_gd[rn] = nm

print(f"HAIYI_GD: {len(haiyi_gd)}")

# Fetch ALL June orders (need pagination)
start = quote('2026-06-01 00:00:00')
end = quote('2026-06-16 23:59:59')
all_orders = []

# Page 0
subprocess.run(['curl', '-s', '-H', f'Authorization: Bearer {token}',
    '-o', '/tmp/haiyi_orders_p0.json',
    f'https://m.hykj.cn/locker-sub-merchant/api/sub/order/weighing/product?page=0&size=200&sort=id,desc&createStartTime={start}&createEndTime={end}'],
    timeout=30)

with open('/tmp/haiyi_orders_p0.json') as f:
    p0 = json.load(f)
total = p0.get('totalElements', 0)
all_orders = p0.get('content', [])
pages = (total + 199) // 200
print(f"HAIYI_TOTAL: {total}, pages: {pages}")

for p in range(1, min(pages, 15)):
    subprocess.run(['curl', '-s', '-H', f'Authorization: Bearer {token}',
        '-o', f'/tmp/haiyi_orders_p{p}.json',
        f'https://m.hykj.cn/locker-sub-merchant/api/sub/order/weighing/product?page={p}&size=200&sort=id,desc&createStartTime={start}&createEndTime={end}'],
        timeout=30)
    with open(f'/tmp/haiyi_orders_p{p}.json') as f:
        page_data = json.load(f)
    all_orders.extend(page_data.get('content', []))

print(f"HAIYI_FETCHED: {len(all_orders)}")

# Aggregate
hd_sales = defaultdict(lambda: {'amount': 0.0, 'orders': 0, 'name': ''})
for o in all_orders:
    cab = o.get('weighingCabinet') or {}
    cab_rn = cab.get('readyNumber') or ''
    if cab_rn not in haiyi_gd:
        continue
    status = o.get('weighingOrderStatusName', '')
    if status not in ('PAID', 'DONE'):
        continue
    amt = float(o.get('transactionAmount', 0) or 0)
    hd_sales[cab_rn]['amount'] += amt
    hd_sales[cab_rn]['orders'] += 1
    hd_sales[cab_rn]['name'] = haiyi_gd[cab_rn]

sorted_hd = sorted(hd_sales.items(), key=lambda x: x[1]['amount'], reverse=True)
total_amt = sum(d['amount'] for _, d in sorted_hd)
total_ord = sum(d['orders'] for _, d in sorted_hd)

print(f"\nHAIYI_GD_SALES: ¥{total_amt:.2f} | {total_ord}笔 | {len(sorted_hd)}台")
print()
for i, (rn, sd) in enumerate(sorted_hd[:30]):
    print(f"  {i+1}. {sd['name']} | ¥{sd['amount']:.1f} | {sd['orders']}笔")

