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

from gm_types.doris import INTERPOSE_TYPE

from rpc.all import get_rpc_remote_invoker
from rpc.tool.log_tool import logging_exception


# {
#     'hits':{
#         'hits':[
#             {
#                 'sort':[1,2,3,4,5],
#                 '_type':'service',
#                 '_source':{},
#                 '_score':123.00,
#                 '_index':0,
#                 'highlight':{
#                     'closure_tags':[u'切开<ems>双眼皮<ems>'],
#                 },
#                 '_id':123,
#             }
#         ],
#         'total':0,
#         'max_score':None
#     },
# }
# from search.utils.es import get_es, es_index_adapt
#
#
# def _get_query(multi_match, highlight, service_ids):
#     f = [
#         {'terms': {'_id': service_ids}},
#     ]
#     return {
#         'query':
#             {
#                 'filtered': {
#                     'query': {
#                         'multi_match': multi_match
#                     },
#                     'filter': {'bool': {'must': f}
#                                }
#                 }
#             },
#         'highlight': highlight
#     }
#
#
# def retrive_from_es(q):
#     es = get_es()
#     index = es_index_adapt(
#         index_prefix=settings.ES_INDEX_PREFIX,
#         doc_type='service',
#         rw='read'
#     )
#     query = _get_query()
#     res = es.search(
#         index=index,
#         doc_type='service',
#         timeout=settings.ES_SEARCH_TIMEOUT,
#         body=q,
#     )
#     return res


def get_interpose(offset, size, keyword, filters, sort_type, interpose_type):
    tag_ids = []
    city_tag_id = None
    for k, v in filters.items():
        if k == 'area_tag_id' and isinstance(v, (long, int)):
        # if k == 'city_tag_id' and isinstance(v, (long, int)):
            city_tag_id = v
        elif k == 'tag_ids' and isinstance(v, list) and v:
            tag_ids = v
        elif k == 'bodypart_tag_id':
            # compatibility
            if isinstance(v, list) and v:
                tag_ids = v
            elif isinstance(v, (int, long)):
                tag_ids.append(v)
    if len(tag_ids) > 1:
        return None
    try:
        rpc_invoker = get_rpc_remote_invoker()
        result = rpc_invoker['doris/interpose/get'](
            interpose_type=interpose_type,
            city_tag_id=city_tag_id,
            tag_id=tag_ids[0] if tag_ids else None,
            sort_order=sort_type,
            keyword=keyword,
        ).unwrap()
        if result:
            result = result[offset:offset+size]
    except:
        logging_exception()
        return None
    return result


def search_interpose(offset, size, keyword, filters, sort_type):
    try:
        service_ids = get_interpose(offset, size, keyword, filters, sort_type, INTERPOSE_TYPE.SERVICE_SEARCH)
        if not service_ids:
            return None
        res = {
            'hits': {
                'total': len(service_ids)
            },
        }
        hits = []
        for service_id in service_ids:
            hit = {
                '_source': {},
                '_id': service_id,
            }
            hits.append(hit)
        res['hits']['hits'] = hits
        return res
    except:
        logging_exception()


def filter_interpose(offset, size, keyword, filters, sort_type):
    try:
        service_ids = get_interpose(offset, size, keyword, filters, sort_type, INTERPOSE_TYPE.SERVICE_FILTER)
        if not service_ids:
            return None
        res = {
            'service_ids': service_ids,
            'total_count': len(service_ids)
        }
        return res
    except:
        logging_exception()
