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"

shenzhen_stats = {"total": 0, "bound": 0}
no_address_devices = []

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:
            province = device.get("province") or ""
            city = device.get("city") or ""
            
            # 深圳统计
            if "深圳" in city or "深圳" in province:
                shenzhen_stats["total"] += 1
                if device["bind_status"] == 1:
                    shenzhen_stats["bound"] += 1
            
            # 无地址设备
            if not province or province == "UNKNOWN" or not city or city == "UNKNOWN":
                no_address_devices.append({
                    "device_id": device["device_id"],
                    "product_code": device.get("product_code", ""),
                    "brand": device.get("brand", ""),
                    "mac": device.get("mac", ""),
                    "ip": device.get("ip", ""),
                    "bind_status": device.get("bind_status", 0),
                    "location_source": device.get("location_source", "")
                })
    
    offset += limit
    if offset >= total_count:
        break

print(f"=== 深圳市 2026年6月17日绑定情况 ===")
print(f"新增设备: {shenzhen_stats['total']} 台")
print(f"已绑定: {shenzhen_stats['bound']} 台")

print(f"\n=== 无地址设备明细 (共 {len(no_address_devices)} 台) ===\n")
if no_address_devices:
    print(f"{'设备ID':<10} {'品牌':<6} {'型号':<8} {'IP地址':<18} {'绑定':<6} {'地址来源':<15}")
    print("-" * 70)
    for d in no_address_devices:
        bind_str = "是" if d["bind_status"] == 1 else "否"
        print(f"{d['device_id']:<10} {d['brand']:<6} {d['product_code']:<8} {d['ip']:<18} {bind_str:<6} {d['location_source']:<15}")
