#!/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
import base64
import random
from associate.models import agile_tag
from associate.commons.commons import get_tips_suggest_list
from django.conf import settings
from associate.commons.words_utils import QueryWordAttr


class TagTransfer(object):

    @classmethod
    def get_tag_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.strip()
            item_dict["is_online"] = instance.is_online
            random_num = random.randint(3000, 10000)
            item_dict["results_num"] = random_num
            item_dict["offline_score"] = 0.0
            item_dict["create_tag_type"] = instance.create_tag_type
            item_dict["style"] = instance.style
            item_dict["topic_recommend_sort"] = instance.topic_recommend_sort
            item_dict["agile_tag_type"] = instance.get_agile_tag_type()
            item_dict["agile_tag_id"] = instance.id
            item_dict["api_agile_tag_recommend_type"] = instance.get_api_agile_tag_recommend_type()
            ret_list.append(item_dict)
            suggest_list = get_tips_suggest_list(instance.name)

            logging.info("get ret_list:%s" % ret_list)
            logging.info("get suggest_list:%s" % ret_list)

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

    @classmethod
    def get_tractate_data_name_mapping_results_to_redis(cls, name):
        try:

            tag_name = name
            q = dict()
            if tag_name:
                multi_fields = {
                    "content": 6,
                    "tractate_tag_name": 3,
                    "tractate_tag_name_content": 4,
                    "author": 2, }

                query_fields = ['^'.join((k, str(v))) for (k, v) in multi_fields.items()]
                multi_match = {
                    'query': tag_name,
                    'type': 'cross_fields',
                    'operator': 'and',
                    'fields': query_fields,
                }
                q['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="tractate", doc_type="tractate", query_body=q,
                                                           offset=0, size=0)

                doctor_results = result_dict["total_count"]

                return doctor_results

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

    @classmethod
    def set_data_to_redis(self, instance):
        try:
            query_key = "query:associate_tip:tag_id:"

            name = agile_tag.AgileTag.objects.filter(id=instance.agile_tag_id).values_list("name", flat=True).first()

            tractate_results = TagTransfer.get_tractate_data_name_mapping_results_to_redis(name)
            logging.info("get tractate_results:%s" % tractate_results)
            key = query_key + str(instance.agile_tag_id)

            redis_client.set(key, tractate_results)

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