# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function

from api.models import Tag
from api.models import TAG_TYPE
from polymer.models import PolymerAiMasterTag, PolymerAiSlaveTag, PolymerSurgery


def list_tags_by_polymer_ids(polymer_ids):
    """
    批量返回聚合页对应的一级，二级，三级标签
    :param polymer_ids:
    :return:
    """

    if not polymer_ids:
        return {}
    polymer_surgery_ids = list(PolymerSurgery.objects.filter(polymer_id__in=polymer_ids).values_list('polymer_id', flat=True))

    polymer_master_tag = PolymerAiMasterTag.objects.filter(
        polymer_id__in=polymer_ids,is_online=True).values(
            "tag_id", "polymer_id").order_by("polymer_id")
    master_tag_ids = [i['tag_id'] for i in polymer_master_tag]

    polymer_slave_tag = PolymerAiSlaveTag.objects.filter(
        polymer_id__in=polymer_ids,is_online=True).values(
            "tag_id", "polymer_id").order_by("polymer_id")
    slave_tag_ids = [i['tag_id'] for i in polymer_slave_tag]

    tag_ids = master_tag_ids + slave_tag_ids
    tags_info = Tag.objects.filter(
        pk__in=tag_ids,
        is_online=True,
        tag_type__in=[TAG_TYPE.BODY_PART, TAG_TYPE.BODY_PART_SUB_ITEM, TAG_TYPE.ITEM_WIKI]
    ).in_bulk(tag_ids)

    result = {}
    for item in polymer_ids:
        result[int(item)] = []

    for item in polymer_master_tag:
        tag_id, polymer_id = int(item['tag_id']), int(item['polymer_id'])

        if tag_id in tags_info:
            is_surgery = False
            if polymer_id in polymer_surgery_ids:
                is_surgery = True
            result[polymer_id].append({'tag_name': tags_info[tag_id].name, 'tag_id': tag_id, 'is_surgery': is_surgery})

    for item in polymer_slave_tag:
        tag_id, polymer_id = int(item['tag_id']), int(item['polymer_id'])

        if tag_id in tags_info:
            is_surgery = False
            if polymer_id in polymer_surgery_ids:
                is_surgery = True
            result[polymer_id].append({'tag_name': tags_info[tag_id].name, 'tag_id': tag_id, 'is_surgery': is_surgery})
    return result
