import json
import urllib.request
from datetime import datetime

cutoff_date = "2026-05-18"
base_url = "http://192.168.1.7:8800/api/device/list"

total_recent = 0
bound_recent = 0
brand_stats = {"ST": {"total": 0, "bound": 0}, "KK": {"total": 0, "bound": 0}}

offset = 0
limit = 200
total_count = None

while True:
    url = f"{base_url}?limit={limit}&offset={offset}"
    try:
        with urllib.request.urlopen(url, timeout=10) as resp:
            data = json.loads(resp.read().decode())
    except Exception as e:
        print(f"Error at offset {offset}: {e}")
        break
    
    if total_count is None:
        total_count = data["total_count"]
        print(f"总设备数: {total_count}")
    
    items = data.get("items", [])
    if not items:
        break
    
    for device in items:
        ctime = device["ctime"][:10]
        if ctime >= cutoff_date:
            total_recent += 1
            brand = device["brand"]
            if brand in brand_stats:
                brand_stats[brand]["total"] += 1
            if device["bind_status"] == 1:
                bound_recent += 1
                if brand in brand_stats:
                    brand_stats[brand]["bound"] += 1
    
    offset += limit
    if offset >= total_count:
        break
    
    if offset % 2000 == 0:
        print(f"已处理: {offset}/{total_count}")

print(f"\n=== 近一个月绑定统计 (2026-05-18 至 2026-06-17) ===")
print(f"新增设备总数: {total_recent}")
print(f"新增绑定设备: {bound_recent}")
if total_recent > 0:
    print(f"绑定率: {bound_recent/total_recent*100:.1f}%")
print(f"\n=== 品牌分布 ===")
print(f"ST品牌 - 新增: {brand_stats['ST']['total']}, 绑定: {brand_stats['ST']['bound']}")
print(f"KK品牌 - 新增: {brand_stats['KK']['total']}, 绑定: {brand_stats['KK']['bound']}")
