#!/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
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()
            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()
            item_dict["id"] = getMd5Digest(str(instance.name))
            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(instance.name)

            return (item_dict, suggest_list)
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())
            return ([], [])
