import json
import urllib.request
from collections import defaultdict

target_date = "2026-06-17"
base_url = "http://192.168.1.7:8800/api/device/list"

city_stats = defaultdict(lambda: {"total": 0, "bound": 0})
total_all = 0
bound_all = 0
no_address = 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"]
    
    items = data.get("items", [])
    if not items:
        break
    
    for device in items:
        ctime = device["ctime"][:10]
        if ctime == target_date:
            total_all += 1
            province = device.get("province")
            city = device.get("city")
            
            # 判断是否有地址
            if province and city and province != "UNKNOWN" and city != "UNKNOWN":
                location = f"{province}-{city}"
                city_stats[location]["total"] += 1
                if device["bind_status"] == 1:
                    city_stats[location]["bound"] += 1
                    bound_all += 1
            else:
                no_address += 1
                if device["bind_status"] == 1:
                    bound_all += 1
    
    offset += limit
    if offset >= total_count:
        break

# 按绑定数排序，取前10
sorted_cities = sorted(city_stats.items(), key=lambda x: x[1]["bound"], reverse=True)[:10]

print(f"=== 2026年6月17日全国智能床绑定统计 ===\n")
print(f"当日新增设备总数: {total_all} 台")
print(f"当日绑定总数: {bound_all} 台")
print(f"有地址设备: {total_all - no_address} 台")
print(f"无地址设备: {no_address} 台")

print(f"\n=== 有地址城市绑定排名 TOP 10 ===\n")
print(f"{'排名':<4} {'城市':<20} {'新增设备':<10} {'已绑定':<10} {'绑定率':<8}")
print("-" * 55)

for i, (city, stats) in enumerate(sorted_cities, 1):
    rate = stats["bound"] / stats["total"] * 100 if stats["total"] > 0 else 0
    print(f"{i:<4} {city:<20} {stats['total']:<10} {stats['bound']:<10} {rate:.1f}%")

# 汇总前10
if sorted_cities:
    total_new = sum(s["total"] for _, s in sorted_cities)
    total_bound = sum(s["bound"] for _, s in sorted_cities)
    print("-" * 55)
    print(f"{'TOP10合计':<4} {'':<20} {total_new:<10} {total_bound:<10} {total_bound/total_new*100:.1f}%")
