# coding:utf-8
import logging
import random

from django.conf import settings
from gm_types.gaia import SEARCH_KEYWORDS_TYPE

from api.models import City, WordRelSynonym
from api.models import SearchHotWords
from doris.models import SearchRank
from doris.utils.words_tool import words_cache
from rpc.decorators import bind
from api.tool.searchkeyword_procotol_tool import format_search_keyword

logger = logging.getLogger(__name__)


@bind('api/search_words/recommend_doris')
def get_recommend_words(tab_type, city_id):

    # 综合、美购、案例、知识使用相同的推荐词
    if tab_type in [SEARCH_KEYWORDS_TYPE.DEFAULT, SEARCH_KEYWORDS_TYPE.KNOWLEDGE, SEARCH_KEYWORDS_TYPE.SERVICE, SEARCH_KEYWORDS_TYPE.CASE]:
        tab_type = SEARCH_KEYWORDS_TYPE.DEFAULT

    try:
        province_id = City.objects.get(id=city_id).province_id
        return words_cache.get_words(tab_type, province_id)

    except City.DoesNotExist:
        return []


@bind('api/search_words/default_doris')
def get_default_words(city_id):
    if not settings.SWITCH_DORIS_DEFAULT_SEARCH_WORDS:
        return []

    try:
        province_id = City.objects.get(id=city_id).province_id
        date = SearchRank.objects.filter(province_id=province_id).latest('update_date').update_date
        words = SearchRank.objects.filter(
            province_id=province_id,
            update_date=date
        ).order_by('-search_cnt')[:15].values_list('query', flat=True)
        return list(words)

    except:
        logger.info('can not get default search words from db,city id :{} '.format(city_id))
        return []


@bind('api/search_words/duplicate')
def duplicate_recommend_words(data):
    if not data or not isinstance(data, list):
        return []
    try:
        ret = []
        for word in data:
            try:
                obj = WordRelSynonym.objects.get(word=word)
                ret.append(obj.wordrel.keyword)
            except:
                ret.append(word)
        return ret
    except:
        return []


@bind('api/search_words/master_operating')
def get_master_operating(size=10, order_by='-sorted'):
    """
    管理员自动配置的数据
    :return:
    """
    data = SearchHotWords.objects.filter(is_delete=False).order_by(order_by)[:size]
    result = list()
    for item in data:
        result.append({
            'id': item.id,
            'url': format_search_keyword(item.jump_type, item.gm_url),
            'is_special': False,
            'keyword': item.keywords,
            'alias_name': item.alias_name
        })
    return result

@bind('api/search_words/master_operating_everybody')
def master_operating_everybody(size=10, num=10, order_by='-sorted', start=0, world_random = 0):
    """
    管理员自动配置的数据  综合tab
    :return:
    """
    if world_random == 1:  #随机取数据
        if num < size:
            size = size - num
        s = SearchHotWords.objects.filter(is_delete=False).order_by(order_by)
        if len(s) < size:
            size = len(s)
        data = random.sample(s,size)
    else:  #顺序取数据
        data = SearchHotWords.objects.filter(is_delete=False).order_by(order_by)[int(start):int(start)+int(size)]
    result = list()
    for item in data:
        result.append({
            'id': item.id,
            'url': format_search_keyword(item.jump_type, item.gm_url),
            'is_special': False,
            'keyword': item.keywords,
            'alias_name': item.alias_name
        })
    return result
