# coding=utf8
from __future__ import unicode_literals, absolute_import, print_function

import logging
import traceback
import json
from libs.cache import redis_client


class TagTab(object):
    Weight = {
        'search': 0.4,
        'trans': 0.6
    }

    SearchScore = {
        0.7: 100,
        0.1: 80,
        0.05: 60,
        0.01: 40,
        0: 20,
    }

    TransScore = {
        0.7: 100,
        0.5: 80,
        0.3: 60,
        0.1: 40,
        0: 20
    }

    def cal_score(self, search_rate, conversion_rate):
        s1 = self._cal_score(search_rate, 'SearchScore') * self.Weight['search']
        s2 = self._cal_score(conversion_rate, 'TransScore') * self.Weight['trans']
        return s1 + s2

    def _cal_score(self, item, type_):
        item *= 100.0
        scoreweight = getattr(self, type_)
        for k in sorted(scoreweight.keys(), reverse=True):
            if item >= k:
                return scoreweight[k]


class DocTab(TagTab):
    SearchScore = {
        0.04: 100,
        0.01: 80,
        0.001: 60,
        0.0002: 40,
        0: 20,
    }

    TransScore = {
        0.47: 100,
        0.2: 80,
        0.1: 60,
        0.01: 40,
        0: 20
    }


class HosTab(TagTab):
    SearchScore = {
        0.47: 100,
        0.2: 80,
        0.1: 60,
        0.01: 40,
        0: 20
    }

    TransScore = {
        1: 100,
        0.45: 90,
        0.27: 80,
        0.21: 70,
        0.15: 60,
        0.12: 50,
        0.09: 40,
        0.06: 30,
        0.04: 20,
        0: 10,
    }


class QueryWordAttr(object):
    # 获取TagConversion表最新的日期
    tag_latest_date = None
    doctor_latest_date = None
    hospital_latest_date = None

    tips_num_redis_key_prefix = "query:associate_tip:tag_id:"
    tagtab = TagTab()
    doctab = DocTab()
    hostab = HosTab()

    @classmethod
    def get_query_results_num(cls, id):
        try:
            key = cls.tips_num_redis_key_prefix + str(id)
            results_num = redis_client.get(key)
            # results_num = json.loads(str(redis_data, encoding="utf-8")) if redis_data else {}

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