#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import unicode_literals, absolute_import, print_function
import logging
import traceback
from libs.es import ESPerform


def get_suggest_tips(query, agile_tag_type):
    try:
        # ios输入法在某些情况下会携带\\u2006
        query = query.replace("\u2006", '')
        q ={}
        # if agile_tag_type != -1:
        #     q["query"] =
        q = {
            "suggest": {
                "tips-suggest": {
                    "prefix": query,
                    "completion": {
                        "field": "suggest",
                        "size": 50,
                        "contexts": {
                            "is_online": [True]
                        },
                        "fuzzy": {
                            "fuzziness": 0
                        }
                    }
                }
            }
        }

        logging.info("get qqqqqqqq:%s" % q)
        have_read_tips_set = set()
        ret_list = list()
        result_dict = ESPerform.get_search_results(ESPerform.get_cli(), sub_index_name="associate_tag", query_body=q,
                                                   offset=0, size=50, is_suggest_request=True)

        logging.info("get result_dict:%s" % result_dict)
        for tips_item in result_dict["suggest"]["tips-suggest"]:
            for hit_item in tips_item["options"]:
                if hit_item["_source"]["ori_name"] not in have_read_tips_set:
                    have_read_tips_set.add(hit_item["_source"]["ori_name"])

                    highlight_marks = u'<ems>%s</ems>' % query
                    hit_item["_source"]["highlight_name"] = hit_item["_source"]["ori_name"].replace(query,
                                                                                                    highlight_marks)

                    ori_name = hit_item["_source"]["ori_name"]
                    results_num = hit_item["_source"]["results_num"]
                    highlight_name = hit_item["_source"]["highlight_name"]

                    ret_list.append([{"ori_name": ori_name, "results_num": results_num, "highlight": highlight_name}])

        return ret_list
    except:
        logging.error("catch exception,err_msg:%s" % traceback.format_exc())
        return list()
