# coding=utf-8

from datetime import datetime, timedelta, time

from talos.rpc import bind
from qa.tasks import (
    question_mapping_sync,
    answer_tag_mapping_sync,
)
from talos.tasks import (
    diary_tag_mapping_sync,
    diary_topic_tag_mapping_sync,
    tractate_tag_mapping_sync,
)
from talos.libs.datetime_utils import tzlc


@bind('mimas/tag_mapping/sync')
def tag_mapping_sync(add_relations=None, delete_relations=None, delete2old_tag_ids=None):
    """标签关系修改后，调整内容相关标签映射关系。

    对于删除的标签关系，我们仅仅新老标签同时存在的时候才进行内容上新标签进行删除。另外这里需要对以下内容进行处理：
        1、日记本、日记贴
        2、用户帖
        3、问题、回答

    @:param delete_relations 删除的标签关系 [{"tag_id": 1, "tag_v3_id": 1}, {"tag_id": 2, "tag_v3_id": 2}]
    @:param add_relations 增加的标签关系 [{"tag_id": 1, "tag_v3_id": 3}, {"tag_id": 2, "tag_v3_id": 4}]
    @:param delete2old_tag_ids 删除的标签还有哪些老标签的映射关系 {1: [1,2,3,4], 2: [78, 1354, 986]}

    delete2old_tag_ids 用于过滤掉多个老标签映射到一个新标签的情况，比如一个新标签对应多个老标签，如果有其他任何一个老标签还在
    该内容上就不应该删除该新标签。
    """

    if not delete_relations and not add_relations:
        return

    # 第二天凌晨 2:20 开始
    eta = datetime.combine(datetime.now(), time.min) + timedelta(days=1, hours=2, minutes=20)

    question_mapping_sync.apply_async(args=(add_relations, delete_relations, delete2old_tag_ids), eta=tzlc(eta))
    answer_tag_mapping_sync.apply_async(args=(add_relations, delete_relations, delete2old_tag_ids), eta=tzlc(eta))
    diary_tag_mapping_sync.apply_async(args=(add_relations, delete_relations, delete2old_tag_ids), eta=tzlc(eta))
    diary_topic_tag_mapping_sync.apply_async(args=(add_relations, delete_relations, delete2old_tag_ids), eta=tzlc(eta))
    tractate_tag_mapping_sync.apply_async(args=(add_relations, delete_relations, delete2old_tag_ids), eta=tzlc(eta))

    # question_mapping_sync(add_relations, delete_relations, delete2old_tag_ids)
    # answer_tag_mapping_sync(add_relations, delete_relations, delete2old_tag_ids)
    # diary_tag_mapping_sync(add_relations, delete_relations, delete2old_tag_ids)
    # diary_topic_tag_mapping_sync(add_relations, delete_relations, delete2old_tag_ids)
    # tractate_tag_mapping_sync(add_relations, delete_relations, delete2old_tag_ids)
