# # -*- coding: utf8 -*-

from talos.backbone.rpc import bind, gen, CODES, logging_exception
from talos.models.diary import Diary
from gm_types.gaia import TAG_TYPE
from talos.services import OrderService
from talos.services.goods import GoodsService
from talos.services.user import UserService

@bind("talos/diary/edit_city_tag")
def edit_diary_city_tag(diary_ids):
    """
    仅供hera后台使用
    批量修改日记本关联的地域标签
    :param diary_ids: 被修改的日记本id列表
    :return:
    """
    if diary_ids:

        try:
            diaries = Diary.objects.filter(id__in=diary_ids).iterator()
        except Diary.DoesNotExist:
            return gen(CODES.DIARY_NOT_FOUND)

        for diary in diaries:
            new_city_tag = _get_city_tag(diary)
            old_city_tag = [tag.id for tag in diary.all_tags if tag.tag_type == TAG_TYPE.CITY]
            _tag_logic_ratio(item=diary, new=new_city_tag, old=old_city_tag)

            if diary.topics.count() > 0:
                for topic in diary.topics.all():
                    topic_tag_ids = [tag.id for tag in topic.tags if tag.tag_type == TAG_TYPE.CITY]
                    _tag_logic_ratio(item=topic, new=new_city_tag, old=topic_tag_ids)


def _get_city_tag(diary):

    order = OrderService.get_order_info_by_id(diary.order_id)

    if order and order.get("city_tag_id"):
        return order.get("city_tag_id")

    service = GoodsService.get_diary_show_info_by_service_ids([diary.service_id, ])
    if service and service[diary.service_id]["city_tag_id"]:
        return service[diary.service_id]["city_tag_id"]

    user = UserService.get_user_by_user_id(diary.user_id)
    if user:
        return user.city_tag_id


def _tag_logic_ratio(item, new, old):

    try:
        if new:
            if old:
                if new in old and len(old) == 1:
                    pass
                else:
                    item.del_tags(list(set(old)))
                    item.add_tags([new, ])
            else:
                item.add_tags([new, ])
        else:
            if old:
                item.del_tags(list(set(old)))
    except Exception:
        logging_exception()
