# coding=utf-8
from django.core.management import BaseCommand

from gm_types.gaia import TAG_TYPE_ATTR

from agile.models.tag import AttrTag, TagAttrRelation


class Command(BaseCommand):

    def handle(self, *args, **options):

        attr_tags = AttrTag.objects.filter(aggregate_type=TAG_TYPE_ATTR.FIRST_BRAND)
        for attr_tag in attr_tags:
            a_t = AttrTag.objects.filter(aggregate_type=TAG_TYPE_ATTR.MODE, name=attr_tag.name).first()
            if not a_t:
                attr_tag.aggregate_type = TAG_TYPE_ATTR.MODE
                attr_tag.save()
                continue

            child_ids = list(TagAttrRelation.objects.filter(parent_id=attr_tag.id, is_online=True).values_list("child_id", flat=True))
            if not child_ids:
                continue

            exclude_child_ids = list(TagAttrRelation.objects.filter(parent_id=a_t.id, is_online=True).values_list("child_id", flat=True))
            add_child_ids = list(set(child_ids) - set(exclude_child_ids))
            relations = [
                TagAttrRelation(
                    parent_id=a_t.id,
                    child_id=child_id
                )
                for child_id in add_child_ids
            ]
            TagAttrRelation.objects.bulk_create(relations)
