# coding: utf-8
import datetime

from django.db import transaction
from django.db.models import Count
from collections import defaultdict

from api.models.hera.search import QueryOperation, QueryOperationWord
from rpc.decorators import bind


@transaction.atomic
@bind('hera/search/query_operation/edit')
def query_operation_edit(operation_id, operation_data, words):
    """ 搜索运营位编辑  """

    if operation_data.get("start_time"):
        operation_data["start_time"] = datetime.datetime.fromtimestamp(int(operation_data["start_time"]))
    else:
        operation_data["start_time"] = datetime.date.min

    if operation_data.get("end_time"):
        operation_data["end_time"] = datetime.datetime.fromtimestamp(int(operation_data["end_time"]))
    else:
        operation_data["end_time"] = datetime.date.max

    if operation_id:
        QueryOperation.objects.filter(id=operation_id).update(**operation_data)
        QueryOperationWord.objects.filter(operation_id=operation_id).delete()
    else:
        obj = QueryOperation.objects.create(**operation_data)
        operation_id = obj.id

    if words:
        create_words = [QueryOperationWord(operation_id=operation_id, word=word) for word in words]
        QueryOperationWord.objects.bulk_create(create_words)

    return operation_id


@bind('hera/search/query_operation/get')
def query_operation_get(operation_id):
    """ 搜索运营位 """

    obj = QueryOperation.objects.filter(id=operation_id).first()

    if not obj:
        return {}

    res = obj.detial()

    word_objs = QueryOperationWord.objects.filter(operation_id=operation_id).all()

    words = [item.word for item in word_objs]

    res["words"] = words

    return res


@bind('hera/search/query_operation/list')
def query_operation_edit(offset=0, size=10,):
    """ 搜索运营位编辑列表 """

    operation_objs = QueryOperation.objects.all()[offset: offset+size]
    word_objs = QueryOperationWord.objects.filter(operation_id__in=[operation_obj.id for operation_obj in operation_objs])

    word_info = defaultdict(list)
    for word_obj in word_objs:
        word_info[word_obj.operation_id].append(word_obj.word)

    data = []

    for operation_obj in operation_objs:
        temp = operation_obj.detial()
        temp["words"] = word_info.get(operation_obj.id, [])
        data.append(temp)

    res = {
        "data": data,
        "total_count": QueryOperation.objects.count(),
    }

    return res


@bind('hera/search/query_operation/word_judge')
def query_operation_edit(words):
    """ 搜索运营位编辑列表 """

    word_count = QueryOperationWord.objects.filter(word__in=words).values('word').annotate(Count('id'))

    return {item["word"]: item["id__count"] for item in word_count}


