# -*- 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

logger = logging.getLogger(__name__)

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


@bind('doris/search/query_wiki')
def query_wiki(query='', offset=0, size=10):
    try:

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

        multi_fields = {
            'name': 100,
            'description': 10,
        }
        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_not": {
                                "term": {
                                    "description": "none"
                                }
                            },
                            "must_not": {
                                "term": {
                                    "description": "none"
                                }
                            },
                            "minimum_should_match": 1
                        }
                    },
                    "functions": [
                        {
                            "filter": {
                                "term": {
                                    "wikitype": 1  # collect
                                }
                            },
                            "weight": 5
                        },
                        {
                            "filter": {
                                "term": {
                                    "wikitype": 0  # item
                                }
                            },
                            "weight": 4
                        },
                        {
                            "filter": {
                                "term": {
                                    "wikitype": 3  # product
                                }
                            },
                            "weight": 3
                        },
                        {
                            "filter": {
                                "term": {
                                    "wikitype": 2  # brand
                                }
                            },
                            "weight": 2
                        }
                    ],
                    "score_mode": "max",
                    "boost_mode": "sum"
                }
            }
        }

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

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

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

        wiki_all = []

        logging.info("q:%s" % q)

        res_hit = res["hits"]["hits"]
        for item in res_hit:
            if '_source' in item:
                id = item['_source']['id']
                wikitype = item['_source']['wikitype']

                wiki_all.append([id, wikitype])

        wiki_list = []
        flag = False
        for i in wiki_all:
            if i[1] == 1:
                flag = True
        if flag == True:
            for i in wiki_all:
                if i[1] != 0:
                    wiki_list.append(i)

        else:

            wiki_list = wiki_all

        logging.info('new wiki res:%s' % wiki_list)

        return {"wiki_all": wiki_list}

    except:

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

        return {'wiki_all': []}

@bind('doris/search/wiki_sort')
def wiki_sort(filters=None, offset=0, size=10):
    try:
        filters = filters or {}

        tag_ids = []

        for k, v in filters.items():

            if k == "tag_ids":
                tag_ids = v
        q = {}
        if len(tag_ids) > 0:
            q["query"] = {
                "bool": {
                    "must": [
                        {"term": {"is_online": True}},
                        {"terms":{"old_tag_ids":tag_ids}}
                    ]
                }
            }

        else:
            q["query"] = {
                "bool": {
                    "must": {"term": {"is_online": True}}

                }
            }

        wiki_id_dict = list()
        logging.info('test query es :%s' % str(q).encode('utf-8'))
        res = es_query('newwiki', q, offset, size)
        res_hit = res["hits"]["hits"]
        for item in res_hit:
            if '_source' in item:
                id = item['_source']['id']
                type_id = item['_source']['wikitype']
                wiki_id_dict.append({"type": type_id, "id": id})
        return {'encyclopedia':wiki_id_dict}

    except:

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

        return {'encyclopedia':[]}

