import json
import urllib.request
from collections import defaultdict

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

city_stats = defaultdict(lambda: {"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"]
    
    items = data.get("items", [])
    if not items:
        break
    
    for device in items:
        ctime = device["ctime"][:10]
        if ctime >= cutoff_date:
            province = device.get("province") or "未知省份"
            city = device.get("city") or "未知城市"
            location = f"{province}-{city}" if city != "未知城市" else province
            
            city_stats[location]["total"] += 1
            if device["bind_status"] == 1:
                city_stats[location]["bound"] += 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("=== 近一个月绑定数量前10城市 ===\n")
print(f"{'排名':<4} {'城市':<20} {'新增设备':<10} {'已绑定':<10} {'绑定率':<8}")
print("-" * 55)

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

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