#!/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
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()
            results = instance.get_by_id_name
            logging.info("get results:%s" % results)
            name = results.get("name", None)
            item_dict["id"] = getMd5Digest(str(name))
            item_dict["ori_name"] = name
            item_dict["is_online"] = results.get("is_online", None)
            item_dict["results_num"] = QueryWordAttr.get_query_results_num(instance.agile_tag_id)
            item_dict["agile_tag_type"] = instance.agile_tag_type
            item_dict["agile_tag_id"] = instance.agile_tag_id
            item_dict["create_tag_type"] = results.get("create_tag_type", None)
            item_dict["style"] = results.get("style", None)
            item_dict["topic_recommend_sort"] = results.get("topic_recommend_sort", None)
            item_dict["offline_score"] = 0.0
            ret_list.append(item_dict)
            suggest_list = get_tips_suggest_list(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)
            if tractate_results == None:
                tractate_results = 0
            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())
