# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function
from typing import Optional

from django.conf import settings
from rpc.decorators import bind, bind_context, cache_page
from rpc.tool.error_code import gen, CODES
from gm_types.poseidon import RecallType, VisualUnitRelatedServiceTemplate,CompensateRangType
from api.models.area import Province, Area, Country,City,Region
from rpc.tool.log_tool import logging_exception,info_logger


@bind("api/areas")
@bind("api/area/list")
@cache_page(24*60*60)
def get_all_areas():
    """所有地区，省、市
    """
    result = []
    provinces = Province.objects.filter(display_in_filter=True).order_by('id')
    for province in provinces:
        cities = [city.city_data() for city in province.cities.filter(display_in_filter=True).order_by('id')]
        province_info = province.province_data()
        province_info[u'cities'] = cities
        result.append(province_info)

    return result


@bind("api/area/chinalist")
@cache_page(24*60*60)
def get_china_areas():
    """
    中国地区，省、市
    """
    result = []
    provinces = Province.objects.filter(display_in_filter=True, country_id="china").order_by('id')
    for province in provinces:
        cities = [city.city_data() for city in province.cities.filter(display_in_filter=True).order_by('id')]
        province_info = province.province_data()
        province_info[u'cities'] = cities
        result.append(province_info)
    return result


@bind("api/area/consultant_chinalist")
def get_consultant_china_areas():
    """
    中国地区，省、市
    """
    result = []
    provinces = Province.objects.filter(display_in_filter=True, country_id="china").order_by('id')
    for province in provinces:
        cities = [city.city_data() for city in province.cities.filter(display_in_filter=True).order_by('id')]
        province_info = province.province_data()
        province_info[u'cities'] = cities
        result.append(province_info)
    return result


@bind("api/area/countries")
@cache_page(24*60*60)
def get_all_countries():
    """
    获取所有的国家
    """
    result = []
    countries = Country.objects.filter()
    for country in countries:
        item = {}
        item["id"] = country.tag.id
        item["name"] = country.name
        result.append(item)
    return result


@bind('api/province/info')
@cache_page(60 * 60)
def get_province_info(id):
    try:
        province = Province.objects.get(pk=id)
    except Province.DoesNotExist:
        return gen(CODES.PROVINCE_DOES_NOT_EXIST)
    return province.province_data()


@bind("api/area/register_area")
@cache_page(86400)
def get_all_register_area():
    areas = [area.data() for area in Area.objects.all()]
    return {'areas': areas}


@bind('api/area/phone_code')
def phone_area_code():
    # TODO Deprecated 所有电话号码前缀的取数据都使用方法 api/area/register_area
    area_code = settings.PHONE_AREA_CODE
    return area_code


@bind('api/province/city_ids')
def get_province_city_ids(province_id):
    try:
        province = Province.objects.get(pk=province_id)
    except Province.DoesNotExist:
        return gen(CODES.PROVINCE_DOES_NOT_EXIST)
    return list(province.city_ids())


@bind('api/province/tag')
def get_province_tag_id(province_id):
    # 获取省份的tag_id
    try:
        province = Province.objects.filter(id=str(province_id))
        if province.exists():
            return province[0].tag_id
        else:
            return 0
    except Province.DoesNotExist:
        return gen(CODES.PROVINCE_DOES_NOT_EXIST)


@bind('api/region/province/tags')
def get_region_province_tags_id(region_id):
    # 获取大区里面所有省份的tags的id
    province_tag_ids = Province.objects.filter(region_id=region_id).values_list("tag_id", flat=True)
    if province_tag_ids:
        return list(province_tag_ids)
    else:
        return []

@bind('api/area/search_province_tag_ids')
def get_province_tag_id_by_city_tag_id(city_tag_id, range_type=CompensateRangType.NATIONWIDE):
    """
        通过城市tag_id获取 所在省的 或 所在大区的 或 全国的 省份tag_id(s)
        Args:
            city_tag_id: 用户所在城市tag_id
            range_type: 范围类型, 目前只会是省/大区/全国
        Returns:
            指定范围的省份tag_id(s)
    """
    try:
        info_logger.info("rpc['api/area/search_province_tag_ids'] city_tag_id: %s" % city_tag_id)

        city = City.objects.filter(tag_id=city_tag_id).first()
        if not city:
            return []
        province_id = city.province_id

        province = Province.objects.filter(id=province_id).first()
        if not province:
            return []
        if range_type == CompensateRangType.PROVINCE:
            return [province.tag_id]

        region_id = province.region_id
        if not region_id:
            return []
        if range_type == CompensateRangType.REGION:
            return list(
                Province.objects.filter(region_id=region_id).values_list('tag_id', flat=True)
            )
        if range_type == CompensateRangType.NATIONWIDE:
            return list(
                Province.objects.all().values_list('tag_id', flat=True)
            )

        return []

    except Exception as e:
        info_logger.info("rpc['api/area/search_province_tag_ids'] Error: %s" % e)
        return []
