#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
import json

from gm_rpcd.all import bind, RPCDFaultException
from communal.models import QuickSearchContentKeyword


@bind("mimas/quick_search/get_keywords")
def content_quick_search_get_keywords(content_ids, content_type):
    """
    获取内容快捷搜索关键字。这个接口只支持同一类型下的数据
    :param content_ids:
    :param content_type:
    :return:
    """
    result = {}

    keywords = QuickSearchContentKeyword.objects.filter(
        content_id__in=content_ids,
        content_type=content_type
    ).values_list("content_id", "keywords")

    for content_id, keyword in keywords:
        result.update({
            str(content_id): json.loads(keyword) or [],
        })

    return result


@bind("mimas/quick_search/update_keywords")
def content_quick_search_update_keywords(content_id, content_type, keywords):
    """
    内容快捷搜索更新关键字
    :param content_id:
    :param content_type:
    :param keywords:
    :return:
    """
    obj, _ = QuickSearchContentKeyword.objects.update_or_create(
        content_id=content_id,
        content_type=content_type,
        defaults={
            "keywords": json.dumps(keywords),
            "update_time": datetime.datetime.now(),
        }
    )

    return {
        "id": obj.id,
    }


@bind("mimas/quick_search/bulk_update_keywords")
def content_quick_search_bulk_update_keywords(bulk_update_list):
    """
    内容快捷搜索批量更新关键字
    :param bulk_update_list:
    :return:
    """
    result = []
    for item in bulk_update_list:
        obj, _ = QuickSearchContentKeyword.objects.update_or_create(
            content_id=item.get("content_id", 0),
            content_type=item.get("content_type", ""),
            defaults={
                "keywords": json.dumps(item.get("keywords", [])),
                "update_time": datetime.datetime.now(),
            }
        )

        result.append(obj.id)

    return result
