# -*- coding: utf-8 -*-
import io, json, math, time, urllib.request, urllib.parse

HOMES = ['崇盛里', '风来旭和府', '如玺华院', '桦枫居', '盛世钱塘',
         '吉鸿家园', '海上海', '慧仁家园', '圣苑', '水韵康桥康泽苑']


def get(name):
    q = urllib.parse.urlencode({'q': name + ' 杭州', 'limit': '3'})
    url = 'https://photon.komoot.io/api/?' + q
    op = urllib.request.build_opener(urllib.request.ProxyHandler({}))
    req = urllib.request.Request(url, headers={'User-Agent': 'paiban-test/1.0', 'Origin': 'http://localhost'})
    with op.open(req, timeout=25) as r:
        return json.loads(r.read().decode('utf-8'))


out = []
for n in HOMES:
    try:
        j = get(n)
    except Exception as e:
        out.append('%s ERR %s' % (n, e))
        time.sleep(1.2)
        continue
    fs = j.get('features') or []
    if not fs:
        out.append('%s => none' % n)
    for f in fs[:3]:
        p = f.get('properties') or {}
        c = (f.get('geometry') or {}).get('coordinates') or [0, 0]
        out.append('%s => %s | %s | %s | %s | %s | %s' % (
            n, round(c[1], 6), round(c[0], 6),
            p.get('name', ''), p.get('street', ''), p.get('district', ''), p.get('city', '')))
    time.sleep(1.2)

with io.open(r'D:\workbbbbbb\build\_ph_out.txt', 'w', encoding='utf-8') as f:
    f.write('\n'.join(out))
print('done', len(out))
