# encoding=utf-8
from __future__ import unicode_literals

from api.models.area import City, Province

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

from rpc.decorators import bind_context

__author__ = 'Zyy'

uri_pre = 'hera/city'


@bind_context(uri_pre + '/choices')
def city_choices(ctx, q='', page=1, num=30, initial=None, need_province=False):
    page = int(page)
    num = int(num)

    if initial is not None:
        if isinstance(initial, (list, tuple)):
            qry = Q(id__in=initial)
        else:
            qry = Q(id=initial)
    else:
        qry = Q(id__contains=q) | Q(name__contains=q)

    if need_province:
        pro_id_list = Province.objects.values_list('id', flat=True)
        qry &= Q(province_id__in=pro_id_list)

    query = City.objects.using(settings.SLAVE_DB_NAME).filter(qry)
    # total_count = query.count()
    total_count = 0
    start_pos = (page - 1) * num
    start_pos = start_pos if start_pos >= 0 else 0
    results = [
        {
            'id': obj.id,
            'text': u'{}:{}'.format(obj.id, obj.name),
        } for obj in query[start_pos: start_pos + num]
        ]
    return {'total_count': total_count, 'results': results, 'page': page, 'num': num}


@bind_context(uri_pre + '/select')
def city_select(ctx, include_municipality=True):
    provinces_data = []
    provinces = Province.objects.all()
    if not include_municipality:
        provinces = provinces.exclude(id__in=['beijing', 'chongqing', 'tianjin', 'shanghai'])
    for province in provinces:
        citys = City.objects.filter(province_id=province.id)
        results = [
            {
                'id': city.id,
                'text': u'{}:{}'.format(city.id, city.name),
            } for city in citys
            ]
        province_data = {
            'name': u'{}:{}'.format(province.id, province.name),
            'city': results,
        }
        provinces_data.append(province_data)
    return provinces_data


@bind_context(uri_pre + '/get_byids')
def get_city_by_ids(ctx, city_ids):
    """
    根据城市ID获取城市的姓名
    created by oldman at 2017-03-24
    :param ctx:
    :param city_ids:
    :return:
    """
    cities = City.objects.filter(id__in=city_ids)
    return [city.name for city in cities]
