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

from __future__ import unicode_literals, absolute_import, print_function
import logging
import traceback
import json
import base64
from libs.es import ESPerform
from libs.cache import redis_client
from libs.tools import g_hospital_pos_dict
from libs.tools import point_distance
from gm_rpcd.all import bind
from trans2es.commons.words_utils import QueryWordAttr, get_tips_word_type


def get_suggest_tips(query, lat, lng, offset=0, size=50):
    try:
        ###先获取完全命中的query
        # qq = {
        #     "query": {
        #         "bool": {
        #             "must": [{
        #                 "term": {
        #                     "ori_name": query
        #                 }
        #             }, {
        #                 "term": {
        #                     "is_online": True
        #                 }
        #             }]
        #         }
        #     }
        # }
        # logging.info("get qqqqqqqqq:%s" % qq)
        # whole_query = ESPerform.get_search_results(ESPerform.get_cli(), sub_index_name="suggest", query_body=qq,
        #                                            offset=0, size=1, is_suggest_request=True)
        #
        # logging.info("get whole_query:%s" % whole_query)

        # hits = whole_query["hits"]["hits"]
        #
        # for item in hits:
        #     have_read_tips_set.add(item["_source"]["ori_name"])
        #     id = item["_source"]["id"]
        #     ori_name = item["_source"]["ori_name"]
        #     results_num = item["_source"]["results_num"]
        #     is_online = item["_source"]["is_online"]
        #     offline_score = item["_source"]["offline_score"]
        #     type_flag = item["_source"]["type_flag"]
        #
        #     highlight_marks = u'<ems>%s</ems>' % query
        #     item["_source"]["highlight_name"] = item["_source"]["ori_name"].replace(query, highlight_marks)
        #     highlight_name = item["_source"]["highlight_name"]
        #     if item["_source"]["type_flag"] == "hospital":
        #         if lat is not None and lng is not None and lat != 0.0 and lng != 0.0:
        #
        #             logging.info("get g_hospital_pos_dict:%s" % g_hospital_pos_dict)
        #             if item["_source"]["ori_name"] in g_hospital_pos_dict:
        #                 distance = point_distance(lng, lat,
        #                                           g_hospital_pos_dict[item["_source"]["ori_name"]][0],
        #                                           g_hospital_pos_dict[item["_source"]["ori_name"]][1])
        #                 if distance < 1000 * 50:
        #                     if distance < 1000:
        #                         if distance < 100:
        #                             item["_source"]["describe"] = "<100" + "米"
        #                         else:
        #                             item["_source"]["describe"] = "约" + str(int(distance)) + "米"
        #                     else:
        #                         item["_source"]["describe"] = "约" + str(
        #                             round(1.0 * distance / 1000, 1)) + "km"
        #                 else:
        #                     item["_source"]["describe"] = ">50km"
        #             else:
        #                 item["_source"]["describe"] = ""
        #
        #         else:
        #             item["_source"]["describe"] = ""
        #     else:
        #         if item["_source"]["type_flag"] == "doctor":
        #             item["_source"]["describe"] = ""
        #         else:
        #             item["_source"]["describe"] = "约" + str(item["_source"]["results_num"]) + "个结果" if \
        #                 item["_source"]["results_num"] else ""
        #
        #     ret_list.append({"offline_score": offline_score, "ori_name": ori_name, "results_num": results_num, "id": id,
        #                      "highlight_name": highlight_name, "type_flag": type_flag,
        #                      "is_online": is_online})

        ###获取联想到的数据
        # ios输入法在某些情况下会携带\\u2006
        query = query.replace("\u2006", '')
        q = {
            "suggest": {
                "tips-suggest": {
                    "prefix": query,
                    "completion": {
                        "field": "suggest",
                        "size": size,
                        "contexts": {
                            "is_online": [True]
                        },
                        "fuzzy": {
                            "fuzziness": 0
                        }
                    }
                }
            },
            "_source": {
                "includes": ["id", "ori_name", "offline_score", "is_online", "type_flag", "results_num"]
            }
        }
        get_doctor_hospital_data = list()
        get_tag_wiki_data = list()
        have_read_tips_set = set()
        ret_list = list()
        result_dict = ESPerform.get_search_results(ESPerform.get_cli(), sub_index_name="suggest", query_body=q,
                                                   offset=offset, size=size, 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)
                    if hit_item["_source"]["type_flag"] == "hospital":
                        if lat is not None and lng is not None and lat != 0.0 and lng != 0.0:
                            if hit_item["_source"]["ori_name"] in g_hospital_pos_dict:
                                distance = point_distance(lng, lat,
                                                          g_hospital_pos_dict[hit_item["_source"]["ori_name"]][0],
                                                          g_hospital_pos_dict[hit_item["_source"]["ori_name"]][1])
                                if distance < 1000 * 50:
                                    if distance < 1000:
                                        if distance < 100:
                                            hit_item["_source"]["describe"] = "<100" + "米"
                                        else:
                                            hit_item["_source"]["describe"] = "约" + str(int(distance)) + "米"
                                    else:
                                        hit_item["_source"]["describe"] = "约" + str(
                                            round(1.0 * distance / 1000, 1)) + "km"
                                else:
                                    hit_item["_source"]["describe"] = ">50km"
                            else:
                                hit_item["_source"]["describe"] = ""

                        else:
                            hit_item["_source"]["describe"] = ""

                        get_doctor_hospital_data.append(hit_item["_source"])
                    else:
                        if hit_item["_source"]["type_flag"] == "doctor":
                            hit_item["_source"]["describe"] = ""

                            get_doctor_hospital_data.append(hit_item["_source"])
                        else:
                            hit_item["_source"]["describe"] = "约" + str(hit_item["_source"]["results_num"]) + "个结果" if \
                                hit_item["_source"]["results_num"] else ""
                            get_tag_wiki_data.append(hit_item["_source"])

            ret_list.extend(get_tag_wiki_data)
            ret_list.extend(get_doctor_hospital_data)

        logging.info("get have_read_tips_set:%s" % have_read_tips_set)
        if len(result_dict["suggest"]["tips-suggest"]) >= 50:
            return ret_list

        else:
            query_ret_list = []
            wordresemble_ret_list = []
            value_data = []
            QUERY_KEY = "query:search_tip"
            query_base64 = base64.b64encode(query.encode('utf8')).decode('utf8')
            if redis_client.hget(QUERY_KEY, query_base64) is not None:
                logging.info("get type:%s" %type(str(redis_client.hget(QUERY_KEY, query_base64))))
                value_data = json.loads(str(redis_client.hget(QUERY_KEY, query_base64)))
            logging.info("get value_data:%s" % value_data)

            if len(value_data) > 0:
                for i in value_data:
                    key = list(i.keys())[0]
                    ori_name = str(base64.b64decode(key), "utf-8")
                    if ori_name not in have_read_tips_set:
                        have_read_tips_set.add(ori_name)
                        result_num = i.get(key, 0)
                        describe = "约" + str(result_num) + "个结果" if result_num else ""
                        logging.info("get result_num:%s" % result_num)
                        highlight_marks = u'<ems>%s</ems>' % query
                        highlight_name = ori_name.replace(query, highlight_marks)
                        if ori_name == query:
                            query_ret_list.append(
                                {"results_num": result_num, "ori_name": ori_name, "id": None, "is_online": True,
                                 "offline_score": 0,
                                 "type_flag": get_tips_word_type(ori_name), "highlight_name": highlight_name,
                                 "describe": describe})
                        else:
                            wordresemble_ret_list.append(
                                {"results_num": result_num, "ori_name": ori_name, "id": None, "is_online": True,
                                 "offline_score": 0,
                                 "type_flag": get_tips_word_type(ori_name), "highlight_name": highlight_name,
                                 "describe": describe})
                        logging.info("get query_ret_list:%s" % query_ret_list)
                        logging.info("get wordresemble_ret_list:%s" % wordresemble_ret_list)
                ret_list.extend(query_ret_list)
                ret_list.extend(wordresemble_ret_list)
            if len(ret_list) >= 50:
                return ret_list[0:50]
            else:
                return ret_list

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