# coding=utf-8
from api.models import Doctor, User, Tag, Service
from api.business.tag import TagControl

from rpc.tool.log_tool import logging_exception
from rpc.decorators import bind

from trans2es.utils.transfer import get_area_tag_info
from search.utils.topic import filter_topic
from doctor.models import Notification, Patient


@bind('api/dbmw/get_problem_extra')
def get_problem_extra_batch(params):
    """

    :param params:
    :return:
    """
    data = []
    for param in params:
        data.append(
            get_problem_extra(param['pid'], param['uid'], param['tids'], param['sid'], param['did'])
        )
    return data


def get_problem_extra(pid, uid, tids, sid, did):
    """
    Get extra topic data.
    :param did: 帖子关联的医生
    :param sid: 帖子关联的美购
    :param tids: 帖子关联的TAG
    :param pid: topic id.
    :param uid: 帖子关联的用户.
    :return:
    """

    res = {}

    if sid:
        if not Service.objects.get(id=sid).is_online:
            res['is_sink'] = True

    if did:
        if not Doctor.objects.get(id=did).is_online:
            res['is_sink'] = True

    if uid:
        user = User.objects.get(pk=uid)
        user_info = {
            "is_doctor": Doctor.objects.filter(user_id=uid).exists(),
        }
        if hasattr(user, 'userextra') and user.userextra and user.userextra.city:
            user_info.update(get_area_tag_info(user.userextra.city))
    else:
        user_info = {}

    res['user'] = user_info
    tags = Tag.objects.filter(id__in=tids, is_online=True)
    res['tags'] = list(set([pt.name for pt in tags]))
    res['tag_ids'] = list(set([pt.id for pt in tags]))
    closure_tags = TagControl.get_ancestors(
        initial_set=tags,
        exclude_init=False,
        is_online_only=True)
    res['closure_tag_ids'] = [t.id for t in closure_tags]
    res['in_whitelist'] = False
    res['in_multitopic'] = False
    return res


@bind('api/topic/filter_topic')
def api_filter_topic(offset=0, size=10, user_city_tag_id=None, sort_type=None, filters={}):
    """
    question filter.
    :param province_id:
    :param offset:
    :param size:
    :param sort_type:
    :param filters:
    :param sort_params:
    :return:
    """
    return filter_topic(offset=offset, size=size, sort_type=sort_type, filters=filters,
                        user_city_tag_id=user_city_tag_id)

