# coding=utf-8
from __future__ import unicode_literals, print_function, absolute_import
from libs.date import datetime_to_timestamp_millis
from libs.es import es_query, get_must_query
from django.conf import settings
from datetime import datetime
import functools

limited_size = functools.partial(min, settings.COUNT_LIMIT)
"""
def limited_size(size):
    return min(settings.COUNT_LIMIT, size)
"""


def area_tag_id_filter(prefix_list, value):
    return {
        'bool': {
            'should': [
                {'term': {prefix + field: value}}
                for prefix in prefix_list
                for field in [
                    'city_tag_id',
                    'city_province_tag_id',
                    'city_province_country_tag_id',
                ]
            ]
        }
    }


def query_by_term(es, term, offset, size):
    now = datetime.now()
    f = [
        {"term": {"is_online": True}},
        {"term": {"is_can_be_sold": True}},
        {"range": {"can_sold_time_range.start_time_long": {"lte": now}}},
        {"range": {"can_sold_time_range.end_time_long": {"gt": now}}}
    ]
    f.append(term)
    sorting = {'smart_rank': {
        'order': 'desc'
    }}
    q = get_must_query(f)
    q['sort'] = sorting
    res = es_query('service', q, offset, size, es)
    hits = res['hits']['hits']
    hit_ids = [hit['_source']['id'] for hit in hits]
    return hit_ids


def service_recall(filters={}, sors=[], offset=0, size=10):
    now = datetime.now()
    f = [
        {"term": {"is_online": True}},
        {"range": {"can_sold_time_range.start_time_long": {"lte": now}}},
        {"range": {"can_sold_time_range.end_time_long": {"gt": now}}}
    ]
