#!/usr/bin/env python
# coding=utf-8

from django.conf import settings

from rpc.decorators import bind

from api.models import Province, City

from django.db.models import Q


@bind('doctor/city/all')
def all_cities():
    """
        获取所有城市
    """
    # 处理直辖市兼容处理
    directly_city_ids = ['beijing', 'tianjin', 'shanghai', 'chongqing', 'aomen', 'xianggang']
    province_list = Province.objects.filter(country_id=settings.COUNTRY_CHINA_ID)
    provinces = []
    for province in province_list:
        # 防止省里包含深圳
        if province.id == 'shenzhen':
            continue
        item = {
            'id': province.id,
            'name': province.name,
            'is_municipality_city': False,
            'cities': [],
        }
        is_municipality_city = province.id in directly_city_ids  # 该省是否是直辖市
        if is_municipality_city:
            item['is_municipality_city'] = True
        for city in province.cities.all():
            if is_municipality_city and city.id != province.id:
                continue  # 直辖市和省id必须相等，否则继续
            # 标识特别行政区、直辖市
            item['cities'].append({
                'id': city.id,
                'name': city.name,
            })
        provinces.append(item)
    return [{
        'id': settings.COUNTRY_CHINA_ID,
        'provinces': provinces,
    }]


@bind('doctor/city/get_province')
def get_province(city_id):
    """
    根据城市id获取省份
    :param city_id:
    :return:
    """
    try:
        city = City.objects.get(pk=city_id)
    except City.DoesNotExist:
        return {
            'city_id': None,
            'province_id': None
        }
    return {
        'city_id': city.id,
        'province_id': city.province.id
    }


@bind('doctor/city/search')
def search_city(srch_value=None):
    q = Q()
    if srch_value:
        q = Q(id__contains=srch_value) | Q(name__contains=srch_value)
    data = City.objects.filter(q).values_list('id', 'name')
    return [{'id':id, 'name':name} for id, name in data]


@bind('doctor/city/dict/search')
def search_city_dict(city_id_list=None):
    q = Q()
    if city_id_list:
        q = Q(id__in=city_id_list)

    data = City.objects.filter(q).values_list('id', 'name')
    id_name_dict = {}
    if data:
        for id, name in data:
            id_name_dict[id] = name
    return id_name_dict
