#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import logging
import traceback
from libs.tools import tzlc, getMd5Digest
from libs.es import ESPerform
from libs.cache import redis_client
import json
from django.conf import settings

from trans2es.commons.commons import get_tips_suggest_list, get_tips_suggest_list_v1
from trans2es.commons.words_utils import QueryWordAttr, get_tips_word_type


class ItemWikiTransfer(object):

    @classmethod
    def get_wiki_data_name_mapping_results_to_redis(cls, instance):
        try:
            wiki_name = instance.name.strip()
            QueryWordAttr.save_query_to_redis(wiki_name, from_type="wiki")
            if wiki_name:
                multi_fields = {
                    'name': 1,
                    'association_tags': 1,
                    "description": 1,
                    "use_result": 1,
                    "treatment_method": 1,
                    "effect": 1,
                    "ingredient": 1,
                    "nature_type": 1,
                    "shape": 1,
                }
                query_fields = ['^'.join((k, str(v))) for (k, v) in multi_fields.items()]

                multi_match = {
                    'query': wiki_name,
                    'type': 'cross_fields',
                    'operator': 'or',
                    'fields': query_fields,
                }

                q = {
                    "size": 0,
                    "query": {
                        "bool": {
                            "should": [
                                {"multi_match": multi_match}
                            ],
                            "must": [
                                {"term": {"is_online": True}}
                            ],
                            "minimum_should_match": 1
                        }
                    }
                }

                result_dict = ESPerform.get_search_results(ESPerform.get_cli(settings.GM_ORI_ES_INFO_LIST),
                                                           sub_index_name="newwiki", doc_type="newwiki", query_body=q,
                                                           offset=0, size=0)

                doctor_results = result_dict["total_count"]

                redis_key_prefix = "search_tips:tips_mapping_num"
                redis_data = redis_client.hget(redis_key_prefix, wiki_name)

                redis_val_dict = json.loads(str(redis_data, encoding="utf-8")) if redis_data else {}

                total_count = doctor_results
                if 't' in redis_val_dict:
                    total_count += int(redis_val_dict['t'])

                redis_val_dict['t'] = total_count
                redis_val_dict['w'] = doctor_results

                redis_client.hset(redis_key_prefix, wiki_name, json.dumps(redis_val_dict))

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

    @classmethod
    def get_itemwiki_suggest_data_list(cls, instance):
        try:
            ret_list = list()
            item_dict = dict()
            suggest_list = list()
            ret_bol = QueryWordAttr.save_query_to_redis(query=str(instance.name))
            logging.info("get_wiki_query:%s,ret_bol:%s" % (instance.name, ret_bol))
            if ret_bol:
                # item_dict["id"] = getMd5Digest(str(instance.name))
                item_dict["id"] = "itemwiki_" + str(instance.id)
                item_dict["ori_name"] = instance.name
                item_dict["is_online"] = instance.is_online
                item_dict["order_weight"] = QueryWordAttr.get_project_query_word_weight(instance.name)
                item_dict["results_num"] = QueryWordAttr.get_query_results_num(instance.name)
                item_dict["type_flag"] = get_tips_word_type(instance.name)
                item_dict["offline_score"] = 0.0
                item_dict["tips_name_type"] = 3
                ret_list.append(item_dict)
                suggest_list = get_tips_suggest_list(str(instance.name).lower())
                logging.info("get suggest_list:%s" % suggest_list)
            return (item_dict, suggest_list)
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())
            return ([], [])


class ItemWikiTransferV1(object):

    @classmethod
    def get_wiki_data_name_mapping_results_to_redis(cls, instance):
        try:
            wiki_name = instance.name.strip()
            if wiki_name:
                multi_fields = {
                    'name': 1,
                    'association_tags': 1,
                    "description": 1,
                    "use_result": 1,
                    "treatment_method": 1,
                    "effect": 1,
                    "ingredient": 1,
                    "nature_type": 1,
                    "shape": 1,
                }
                query_fields = ['^'.join((k, str(v))) for (k, v) in multi_fields.items()]

                multi_match = {
                    'query': wiki_name,
                    'type': 'cross_fields',
                    'operator': 'or',
                    'fields': query_fields,
                }

                q = {
                    "size": 0,
                    "query": {
                        "bool": {
                            "should": [
                                {"multi_match": multi_match}
                            ],
                            "must": [
                                {"term": {"is_online": True}}
                            ],
                            "minimum_should_match": 1
                        }
                    }
                }

                result_dict = ESPerform.get_search_results(ESPerform.get_cli(settings.GM_ORI_ES_INFO_LIST),
                                                           sub_index_name="newwiki", doc_type="newwiki", query_body=q,
                                                           offset=0, size=0)

                doctor_results = result_dict["total_count"]

                redis_key_prefix = "search_tips:tips_mapping_num"
                redis_data = redis_client.hget(redis_key_prefix, wiki_name)

                redis_val_dict = json.loads(str(redis_data, encoding="utf-8")) if redis_data else {}

                total_count = doctor_results
                if 't' in redis_val_dict:
                    total_count += int(redis_val_dict['t'])

                redis_val_dict['t'] = total_count
                redis_val_dict['w'] = doctor_results

                redis_client.hset(redis_key_prefix, wiki_name, json.dumps(redis_val_dict))

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

    @classmethod
    def get_itemwiki_suggest_data_list(cls, instance):
        try:
            ret_list = list()
            item_dict = dict()
            suggest_list = list()
            ret_bol = QueryWordAttr.save_query_to_redis(query=str(instance.name), type_v1=True)
            if ret_bol:
                # item_dict["id"] = getMd5Digest(str(instance.name))
                item_dict["id"] = "itemwiki_" + str(instance.id)
                item_dict["ori_name"] = instance.name
                item_dict["is_online"] = instance.is_online
                item_dict["order_weight"] = QueryWordAttr.get_project_query_word_weight(instance.name)
                item_dict["results_num"] = QueryWordAttr.get_query_results_num(instance.name)
                item_dict["type_flag"] = get_tips_word_type(instance.name)
                item_dict["offline_score"] = 0.0
                item_dict["tips_name_type"] = 3
                ret_list.append(item_dict)
                suggest_list = get_tips_suggest_list_v1(str(instance.name).lower())
            return (item_dict, suggest_list)
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())
            return ([], [])
