# coding=utf-8

from gm_types.gaia import QUESTION_ORDER_TYPE, USER_TYPE

from api.models import Province, Zone
from api.tasks.user_related_tasks import get_sleep_user
from api.tool.user_tool import get_auth_type_by_userid, get_user_type_ids

from rpc.decorators import bind
from rpc.decorators import list_interface

from search.utils.question import filter_question
from social import SocialInfo
from statistic import const_strings


@bind('api/question/filter')
@list_interface(offset_name='offset', limit_name='size')
def api_filter_question(offset=0, size=5, province_id=None, sort_type=QUESTION_ORDER_TYPE.DEFAULT, filters={}, sort_params=None):
    """
    question filter.
    :param province_id:
    :param offset:
    :param size:
    :param sort_type:
    :param filters:
    :param sort_params:
    :return:
    """

    if province_id:
        try:
            p = Province.objects.get(id=province_id)
            if p.tag:
                filters['area_tag_id'] = p.tag.id
        except Province.DoesNotExist:
            pass
    return filter_question(offset=offset, size=size, sort_type=sort_type, filters=filters, sort_params=sort_params)


@bind('api/user/is_following')
def is_following(cuid, uid):
    return SocialInfo(cuid).is_following_user(uid)


@bind('api/user/auth_type')
def get_user_auth_type(uid):
    """
    get user auth type
    :param uid:
    :return:
    """
    return get_auth_type_by_userid(uid)


@bind('api/users/user_type')
def get_user_auth_type(uids):
    """
    get users user type
    :param user_ids:
    :return:
    """
    users_type = get_user_type_ids(uids)

    result = {}
    for uid, user_type in users_type.items():

        if user_type['hospital_id']:
            user_type["user_type"] = USER_TYPE.OFFICER
        elif user_type['doctor_id']:
            user_type["user_type"] = USER_TYPE.EXPERT
        else:
            user_type["user_type"] = USER_TYPE.USER

        result[uid] = user_type

    return result


@bind('api/user/get_sleep_user')
def _get_sleep_user(number):
    user_extras = get_sleep_user(number)
    return [user_extra.user.id for user_extra in user_extras]


@bind('api/province/list')
def province_list(**kwargs):
    """

    :param kwargs:
    :return:
    """
    queryset = Province.objects.all()
    display_in_filter = kwargs.get('display_in_filter')
    if display_in_filter is not None:
        queryset = queryset.filter(display_in_filter=display_in_filter)
    provinces = [{'id': p.id, 'name': p.name} for p in queryset]
    provinces.insert(0, {'id': const_strings.NATIONWIDE, 'name': u'全国'})
    return provinces


@bind('api/zone/list')
def zone_list(pks):
    """
    zone list.
    :return:
    """
    return [{'id': zone.id} for zone in Zone.objects.filter(pk__in=pks)]
