# coding=utf8
import json
import datetime
from api.models import ALSearchRank, SearchHotWords
from rpc.decorators import bind
from django.db.models import Q


@bind('hera/search_words/async_data')
# 缓存1d
def get_al_search_words():
    """
    获取每天同步的数据
    :return:
    """
    latest_update = ALSearchRank.objects.latest('update_date').update_date
    if not latest_update:
        return dict()

    delete_count = ALSearchRank.objects.filter(update_date__lt=latest_update).delete()
    data = ALSearchRank.objects.\
        filter(update_date=latest_update).order_by('-search_cnt')
    if not data:
        return dict()
    result = list()
    for item in data[:50]:
        result.append({
            'id': item.id,
            'query': item.query,
            'search_cnt': item.search_cnt
        })
    return {'latest_update_date': latest_update.strftime('%Y-%m-%d') ,
            'data': result}


@bind('hera/search_words/business_data')
def get_list_data():
    """
    获取人工配置词
    :return:
    """
    result = list()
    data = SearchHotWords.objects.filter(is_delete=False).order_by('-sorted')
    for item in data:
        result.append(item.format_dict)
    return result


@bind('hera/search_words/insert')
def insert_hot_words(data):
    """
    新增配置词
    :param data:
    :return:
    """
    item = SearchHotWords()
    for k, v in data.iteritems():
        if k =='extract_config':
            setattr(item, k, json.dumps(v))
            continue
        setattr(item, k,  v)
    item.save()
    result = item.format_dict
    return result


@bind('hera/search_words/update_or_delete')
def update_hot_words(data):
    """
    更新和删除
    :param data:
    :return:
    """
    item = SearchHotWords.objects.get(pk=data.get('id'))
    for k, v in data.iteritems():
        if k =='extract_config':
            setattr(item, k, json.dumps(v))
            continue
        setattr(item, k,  v)
    item.save()
    result = item.format_dict
    return result

@bind('hera/search_words/exists_data')
def judge_keywords_is_exists(keywords, **params):
    """
    判断搜索词是否已经存在
    :param keywords:
    :param params:
    :return:
    """
    item = SearchHotWords.objects.filter((Q(keywords=keywords) | Q(alias_name=keywords)) & Q(is_delete=False))
    if item:
        return True
    return False


@bind('hera/search_words/batch_update')
def batch_update(data):
    result = SearchHotWords.batch_update(data)
    return result
