#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys, re
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 DoctorTransfer(object):

    @classmethod
    def get_doctor_data_name_mapping_results_to_redis(cls, instance):
        try:
            doctor_name = instance.name.strip()

            if doctor_name:
                multi_fields = {
                    'hospital.city_province_name': 1,
                    'hospital.name': 1,
                    'name': 1,
                    'hospital.city_name': 1,
                    'hospital.officer_name': 1,
                    'service_closure_tags': 1
                }
                query_fields = ['^'.join((k, str(v))) for (k, v) in multi_fields.items()]
                multi_match = {
                    'query': doctor_name,
                    'type': 'cross_fields',
                    'operator': 'and',
                    '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="doctor", doc_type="doctor", 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, doctor_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['d'] = doctor_results

                logging.info(
                    "duan add,redis_key_prefix:%s,redis_val_dict:%s" % (str(redis_key_prefix), str(redis_val_dict)))
                redis_client.hset(redis_key_prefix, doctor_name, json.dumps(redis_val_dict))
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())

    @classmethod
    def get_doctor_suggest_data_list(cls, instance):
        try:
            ret_list = list()
            sub_query = re.sub('\W+', '', instance.name)
            keyword = sub_query
            cut_bool = False
            cut_word = ["下线", "停用", "已经下线", "账号停用"]
            for i in cut_word:
                if keyword.find(i) >= 0:
                    cut_bool = True

            item_dict = dict()
            suggest_list = list()
            if cut_bool == False:
                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_doctor_query_word_weight(name=instance.name,
                                                                                       doctor_id=instance.id)
                item_dict["results_num"] = QueryWordAttr.get_query_results_num(instance.name)
                item_dict["type_flag"] = get_tips_word_type(str(instance.name).lower())
                item_dict["offline_score"] = 0.0
                item_dict["tips_name_type"] = 2

                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 (dict(), list())


class DoctorTransferV1(object):

    @classmethod
    def get_doctor_data_name_mapping_results_to_redis(cls, instance):
        try:
            doctor_name = instance.name.strip()

            if doctor_name:
                multi_fields = {
                    'hospital.city_province_name': 1,
                    'hospital.name': 1,
                    'name': 1,
                    'hospital.city_name': 1,
                    'hospital.officer_name': 1,
                    'service_closure_tags': 1
                }
                query_fields = ['^'.join((k, str(v))) for (k, v) in multi_fields.items()]
                multi_match = {
                    'query': doctor_name,
                    'type': 'cross_fields',
                    'operator': 'and',
                    '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="doctor", doc_type="doctor", 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, doctor_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['d'] = doctor_results

                logging.info(
                    "duan add,redis_key_prefix:%s,redis_val_dict:%s" % (str(redis_key_prefix), str(redis_val_dict)))
                redis_client.hset(redis_key_prefix, doctor_name, json.dumps(redis_val_dict))
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())

    @classmethod
    def get_doctor_suggest_data_list(cls, instance):
        try:
            ret_list = list()
            sub_query = re.sub('\W+', '', instance.name)
            keyword = sub_query
            cut_bool = False
            cut_word = ["下线", "停用", "已经下线", "账号停用"]
            for i in cut_word:
                if keyword.find(i) >= 0:
                    cut_bool = True
            item_dict = dict()
            suggest_list = list()
            if not cut_bool:
                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_doctor_query_word_weight(name=instance.name,
                                                                                       doctor_id=instance.id)
                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"] = 2
                ret_list.append(item_dict)
                suggest_list = get_tips_suggest_list_v1(instance.name)
            return (item_dict, suggest_list)
        except:
            logging.error("catch exception,err_msg:%s" % traceback.format_exc())
            return (dict(), list())
