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

from django.conf import settings

from rpc.decorators import bind

from api.models import Province, City


@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
    }
