# coding=utf-8
from __future__ import unicode_literals
import json
from collections import defaultdict

from django.conf import settings
from django.db.models import Q

from api.models import Province, City
from rpc.cache import citycache
from api.tool.geo_tool import get_city_by_options

NATIVE_OVERSEA_KEY = 'native-oversea-cities'
NATIVE_OVERSEA_KEY_v2 = 'native-oversea-cities-v2'


def get_ares_cache(exclude_gat=False):
    """获取中国、国际地区原始数据。"""

    if exclude_gat:
        cache = citycache.get(NATIVE_OVERSEA_KEY_v2)
    else:
        cache = citycache.get(NATIVE_OVERSEA_KEY)

    if cache:
        cache = json.loads(cache)
    else:
        cache = native_and_oversea_area(exclude_gat)

    return cache


def native_and_oversea_area(exclude_gat=False):
    """获取中国、国际原始数据。

    :param exclude_gat: 中国是否移除港澳台地区到国际并列
    :return:
    """
    data = {
        'countries': []
    }

    native = dict(name='中国', groups=[], is_located=False)
    foreign = dict(name='海外', groups=[], is_located=False)

    if exclude_gat:
        native_provinces = frozenset(Province.objects.filter(
            country_id=settings.COUNTRY_CHINA_ID
        ).exclude(
            pk__in=settings.CHINA_EXCLUDE_PROVINCE_IDS
        ).values_list('id', flat=True).iterator())
        foreign = dict(name='国际/港澳台', groups=[], is_located=False)
    else:
        native_provinces = frozenset(Province.objects.filter(
            country_id=settings.COUNTRY_CHINA_ID
        ).values_list('id', flat=True).iterator())

    char_to_native, char_to_foreign = defaultdict(list), defaultdict(list)
    for city in City.objects.all().iterator():
        if city.id in [u'东阳', u' yiwu']:
            continue
        char = city.id[0].upper()
        if city.province_id in native_provinces:
            char_to_native[char].append(city)
        else:
            char_to_foreign[char].append(city)

    for idx, groups in enumerate([char_to_native, char_to_foreign]):
        for char in sorted(groups.keys()):
            group = {
                'initial': char,
                'title': char,
                'is_hot': False,
                'cities': [{'id': city.id, 'name': city.name, 'tag_id': city.tag_id} for city in groups[char]]
            }
            if idx ^ 1:
                native['groups'].append(group)
            else:
                foreign['groups'].append(group)

    data['countries'].append(native)
    data['countries'].append(foreign)

    return data

def is_oversea(city_ids, exclude_gat=False):
    """是否是海外城市，7.6.90后港澳台放在国际那一列。

    :param city_ids: 城市id列表
    :param exclude_gat: 中国是移除港澳台，7.6.90 后移除港澳台到国际
    :return: list
    """
    if not city_ids:
        return []

    cache_key = NATIVE_OVERSEA_KEY
    if exclude_gat:
        cache_key = NATIVE_OVERSEA_KEY_v2

    data = citycache.get(cache_key)
    if data:
        data = json.loads(data)
    else:
        data = native_and_oversea_area(exclude_gat)

    result = [False] * len(city_ids)
    city_to_mark = dict()
    for idx, country in enumerate(data['countries']):
        for group in country['groups']:
            for city in group['cities']:
                city_to_mark[city['id']] = bool(idx == 0x01)

    for idx, city in enumerate(city_ids):
        result[idx] = city_to_mark.get(city, False)

    return result


def get_city_name_by_ids(city_ids=None):

    query = Q()
    if city_ids:
        query &= Q(id__in=city_ids)

    cities = City.objects.filter(query).values("id", "name")

    res = {}
    for city in cities:
        res[city["id"]] = {
            "id": city["id"],
            "name": city["name"],
        }

    return res


def get_city_id_by_options(city_id=None, lat=None, lng=None):
    '''
    根据客户端的参数city_id, lat, lng获取城市id
    '''
    if city_id == 'worldwide':
        city_id = None
    elif not city_id:
        city_obj = get_city_by_options(lat=lat, lng=lng)
        if city_obj:
            city_id = city_obj.id
    return city_id
