# coding=utf-8

from __future__ import absolute_import, unicode_literals


from django.conf import settings
from .es import get_es, get_highlight, es_index_adapt
from api.models.types import USER_ORDER_TYPE


def search_user(query='', offset=0, size=10):
    '''
    @param query: 搜索词(用户昵称)
    @param offset: 偏移量
    @param size: 返回个数

    用户搜索
    搜索域:[
        1.用户昵称]
    默认排序:[
        相关度]
    '''

    # 搜索关键字部分
    # 搜索域
    filtered = {}
    multi_fields = {
        'last_name_not_analyzed': 10,
        'last_name_2grams': 1,
        'last_name': 1,
    }

    if query:
        fields = ['^'.join((k,str(v))) for (k,v) in multi_fields.iteritems()]

        multi_match = {
            'query': query,
            'type': 'cross_fields',
            'operator':'and',
            'fields': fields,
        }
        filtered['query'] = {
            'multi_match':multi_match,
        }

    f = {
        'term':{
            'is_active': True, # 只返回有效且未进入黑名单的用户
        }
    }
    filtered['filter'] = f

    q = {
        'query':{
            'filtered':filtered
        }
    }

    # 高亮部分
    q['highlight'] = get_highlight(multi_fields.keys())

    es = get_es()
    index = es_index_adapt(
        index_prefix=settings.ES_INDEX_PREFIX,
        doc_type='user',
        rw='read'
    )
    res = es.search(
        index = index,
        doc_type = 'user',
        timeout = settings.ES_SEARCH_TIMEOUT,
        body = q,
        from_ = offset,
        size = size)

    return res


def filter_user(offset=0, size=5, sort_type=USER_ORDER_TYPE, filters={}):

    # 过滤器部分
    f = [
        {'term':{'is_active': True}}, # 只返回有效且未进入黑名单的用户
    ]

    for k, v in filters.iteritems():
        if k=='membership_level':
            f.append({
                'term':{'membership_level':v}
            })

    q = {
        'query':{'filtered':{
            'query':{'match_all':{}},
            'filter':{'bool':{'must':f}}
        }}
    }

    # 排序规则部分
    if sort_type == USER_ORDER_TYPE.LAST_LOGIN:
        q['sort'] = [
            {'last_login':{'order':'desc'}},
        ]

    es = get_es()
    index = es_index_adapt(
        index_prefix=settings.ES_INDEX_PREFIX,
        doc_type='user',
        rw='read'
    )
    res = es.search(
        index = index,
        doc_type = 'user',
        timeout = settings.ES_SEARCH_TIMEOUT,
        body = q,
        from_ = offset,
        size = size)

    res = {
        'user_ids':[int(u['_id']) for u in res['hits']['hits']],
        'total_count':res['hits']['total'],
    }
    return res
