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

from rpc.decorators import bind_context, list_interface
from search.utils.user import search_user
from rpc.tool.log_tool import search_logger
from api.tool.user_tool import filter_user_nick_name, get_user_extra_by_user_id
from api.tool.image_utils import get_full_path
from api.tool.user_tool import get_user_from_context
from api.models import User
from social.models import SocialInfo


@bind_context('search/user/esquery')
@list_interface(offset_name='offset', limit_name='size', element_model=User)
def search_es_user(ctx, query='', offset=0, size=10):

    ctx.logger.app(search_esquery=dict(type='user', query=query))

    res = []

    es_res = search_user(
        query=query,
        offset=offset, size=size)
    total = es_res['hits']['total']
    hits = es_res['hits']['hits']

    for u in hits:
        id = u['_source']['id']
        try:
            user = User.objects.get(pk=id)
            person = user.person
            diary_num = person.topic_count
            diary_vote_num = person.vote_count
        except User.DoesNotExist:
            search_logger.info('user not found. user_id[%d]' % (id,))
            continue
        user_extra = get_user_extra_by_user_id(user.id)

        current_user = get_user_from_context(ctx)
        is_following = False
        if current_user:
            current_social_info = SocialInfo(uid=current_user.id)
            is_following = current_social_info.is_following_user(uid=user.id)

        source = {
            'user_id': user.id,
            'nickname': filter_user_nick_name(user) or '',
            'portrait': get_full_path(user_extra.portrait) or get_full_path('img%2Fuser_portrait.png'),
            'location': user_extra.city.name if user_extra.city else '',
            'membership_level': user_extra.membership_level,
            'topic_num': int(user.person.topic_count),
            'vote_num': int(user.person.vote_count),
            'diary_num': int(diary_num),
            'diary_vote_num': int(diary_vote_num),
            'is_following': is_following,

        }

        # 高亮字段key转换
        hlmap = {
            'last_name': 'nickname',
        }
        if 'highlight' in u:
            highlight = {}
            for k, v in hlmap.iteritems():
                if k in u['highlight']:
                    highlight[v] = u['highlight'][k]
        else:
            highlight = None

        res.append({
            'source': source,
            'highlight': highlight,
        })

    return {
        'hits': res,
        'total': total,
    }
