# coding=utf8
from api.models.itemwiki import ItemWiki
from rpc.decorators import bind, bind_context
from rpc.tool.log_tool import search_logger
from search.utils.itemwiki import search_itemwiki
from rpc.decorators import list_interface
from search.utils.common import get_query_matched_tags


@bind_context("search/itemwiki/esquery")
@list_interface(offset_name='offset', limit_name='size', element_model=ItemWiki)
def search_es_itemwiki(ctx, query='', offset=0, size=5):
    """
    :param query:
    :param offset:
    :param size:
    :return:
        total   匹配结果数量
        id
        name
        slogan
        fit_people
    """

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

    results = []
    es_data = search_itemwiki(query=query, offset=offset, size=size)
    total = es_data['hits']['total']
    hits = es_data["hits"]["hits"]
    for hit in hits:
        source = {}
        id = hit['_id']

        try:
            itemwiki = ItemWiki.objects.get(pk=id)
        except ItemWiki.DoesNotExist:
            search_logger.info(u"ItemWiki {} not found".format(id))
            continue

        keys = ['id', 'item_name', 'slogan', 'fit_people', 'image']
        source = {key: getattr(itemwiki, key) for key in keys}
        source['slogan'] = itemwiki.get_slogan()
        highlight = hit.get('highlight', None)
        results.append({
            'source': source,
            'highlight': highlight,
        })

    return {
        'matched_tag_ids':[tag.id for tag in get_query_matched_tags(query)],
        'hits': results,
        'total': total
    }
