from libs.es import tzlc, get_es, es_query, get_highlight
from libs.debug import pretty_json
from django.conf import settings

def generate_filters(filters):
    # 过滤器部分
    f = [
        {'term': {'is_online': True}},          # 只返回上线的福利
    ]
    for k, v in filters.items():
        if k == 'city_tag_id' and isinstance(v, int):
            f.append( {'term':{'city_tag_ids':v}})
        elif k == "region_city_tag_id" and isinstance(v,int):
            f.append({'term':{'region_tag_ids':v}})
        elif k == 'is_whole_country' and isinstance(v, bool):
            f.append({'term':{'is_whole_country':v}})
    return f

def generate_sorting(sort_params={}):
    sorting = [
        "_score",
    ]
    return sorting

# @desc  board召回
# @rd 郑伟
# @param  query                          搜索词
# @param  offset                         起始行数
# @param  size                           返回行数
# @param  filters                        过滤条件
# @date 20170709
def recall_board(query='',
                 offset=0,
                 size=10,
                 filters={},
                 sort_params={}):
    size = min(size, settings.COUNT_LIMIT)
    if 'city_tag_id' in filters:
        sort_params['city_tag_id'] = filters['city_tag_id']

    multi_fields = {
        'closure_tags': 6,
        'title': 2,
        'describe': 1,
    }
    fields = ['^'.join((k, str(v))) for (k, v) in multi_fields.items()]
    multi_match = {
        'query': query,
        'type': 'cross_fields',
        'operator':'and',
        'fields': fields,
    }
    f = generate_filters(filters)
    sorting = generate_sorting(sort_params)
    q = {
        "query": {
            "function_score": {
                "boost_mode": "replace",
                "functions": [
                    {
                        "filter": {
                            "match": {
                                "closure_tags": query
                            }
                        },
                        "weight": 6
                    },
                    {
                        "filter": {
                            "match": {
                                "title": query
                            }
                        },
                        "weight": 2
                    },
                    {
                        "filter": {
                            "match": {
                                "describe": query
                            }
                        },
                        "weight": 1
                    }
                ],
                "min_score": 0,
                'query':{
                    'bool':{
                        "must":[
                            {'multi_match':multi_match},
                        ]
                    }
                }
            }
        },
        'filter':  {'bool': {'must': f}},
        "sort": sorting,
    }
    pretty_json(q)
    res = es_query('board', q, offset, size)
    hits = res["hits"]["hits"]

    if "city_tag_id" in filters:
        city_tag_id = filters['city_tag_id']
        del filters['city_tag_id']
        if len(hits) == 0: #如果当前城市没有榜单, 就在大区搜索
            filters['region_city_tag_id'] = city_tag_id
            f = generate_filters(filters)
            q['filter'] = {'bool': {'must': f}}
            res = es_query('board', q, offset, size)
            hits = res["hits"]["hits"]
            del filters['region_city_tag_id']


        if len(hits) == 0:  #如果当前地区没有榜单, 就展现全国美购
            filters['is_whole_country'] = True
            f = generate_filters(filters)
            q['filter'] =  {'bool': {'must': f}}
            res = es_query('board', q, offset, size)
            hits = res["hits"]["hits"]

    hit_ids = [hit["_source"]["id"] for hit in hits]

    return hit_ids