# -*- coding: UTF-8 -*-
from gm_rpcd.all import bind
from libs.algorithms import variousness, region_division
from libs.debug import pretty_json
from libs.es import es_query
import functools
import logging
import traceback
import datetime
logger = logging.getLogger(__name__)

MAX_LOAD = 100
GROUP_SIZE = 10
variousness_per_10 = functools.partial(variousness, variety_size=GROUP_SIZE)

# @bind('dymas/search/query_wikitab_keyword')
def query_wiki_keyword(query, offset=0, size=10):

    now = datetime.datetime.now()
    yes_time = now - datetime.timedelta(days=1)
    yes_time_str = yes_time.strftime('%Y%m%d')
    size = min(size, MAX_LOAD)

    try:
        assert (query is not None and len(query) > 0)

        multi_fields = {
            'city_id': 100,
        }
        query_fields = ['^'.join((k, str(v))) for (k, v) in multi_fields.items()]

        multi_match = {
            'query': query,
            'type': 'cross_fields',
            'operator': 'and',
            'fields': query_fields,
        }
        q = {
            "query": {
                "function_score": {
                    "query": {
                        "bool": {
                            "should": [{"multi_match": multi_match}],
                            "must": {
                                "term": {
                                    "is_online": True
                                }
                            },
                            "must": [
                                {"exists": {
                                    "field": "name"}
                                },
                                {"wildcard": {
                                    "name": "*"}
                                },
                                {"term": {
                                    "visit_time":yes_time_str}
                                }
                            ],

                            "minimum_should_match": 1
                        },

                    }

                }
            },
            "sort": [{"visit_num": "desc"}],
            "size": size
        }

        logging.info('test query es :%s' % str(q).encode('utf-8'))

        res = es_query('wiki_keyword', q, offset, size)

        logging.info(('res wiki es :%s' % str(res)))

        wiki_hot_recommends = []

        res_hit = res["hits"]["hits"]

        for item in res_hit:
            if '_source' in item:

                wiki_name = item['_source']['name']

                if wiki_name:

                    wiki_id = item['_source']['wiki_id']

                    wiki_type = item['_source']['wiki_type']

                    wiki_hot_recommends.append([wiki_name, wiki_id, wiki_type])

        return {"wiki_hot_recommends": wiki_hot_recommends}

    except:

        logging.error("catch exception, query_sku:%s" % traceback.format_exc())

        return {'wiki_hot_recommends': []}
