# coding:utf-8

"""将标签对应的聚合页的这些标签迁移到聚合页下面去。

包含新标签和老标签
"""

from django.conf import settings
from django.core.management import BaseCommand

from gm_types.gaia import AGILE_TAG_ATTRIBUTE

from agile.models import AgileTagMapping, AgileTag
from polymer.models import Polymer, PolymerTag, \
    PolymerAgileTag, AgileTagRelationPolymer


class Command(BaseCommand):

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

        # 聚合页标签同步
        for polymer in Polymer.objects.using(settings.SLAVE_DB_NAME).all():
            polymer_id = polymer.id

            tag_ids = [item["id"] for item in polymer.tag_list]
            print("tag_ids: ", tag_ids)
            for tag_id in tag_ids:
                PolymerTag.objects.get_or_create(tag_id=tag_id, polymer_id=polymer_id)

            agile_tag_ids = list(AgileTagRelationPolymer.objects.using(settings.SLAVE_DB_NAME).filter(polymer_id=polymer_id, is_online=True).values_list("agile_tag_id", flat=True))
            print("agile_tag_ids: ", agile_tag_ids)
            for agile_tag_id in agile_tag_ids:
                PolymerAgileTag.objects.get_or_create(agile_tag_id=agile_tag_id, polymer_id=polymer_id)

        # 新标签标签属性清洗：将有聚合页的标签设置为项目标签，非项目标签不清晰，没映射的项目标签清洗为未分类标签
        for agile_tag in AgileTag.objects.all():
            exists = AgileTagMapping.objects.using(settings.SLAVE_DB_NAME).filter(agile_tag_id=agile_tag.id).exists()
            if exists:
                if agile_tag.attribute != AGILE_TAG_ATTRIBUTE.ITEM:
                    print("{} attribute change to {} from {}".format(agile_tag.id, agile_tag.attribute, AGILE_TAG_ATTRIBUTE.ITEM))
                    agile_tag.attribute = AGILE_TAG_ATTRIBUTE.ITEM
                    agile_tag.save()
                continue

            if agile_tag.attribute == AGILE_TAG_ATTRIBUTE.ITEM:
                print("{} attribute change to {} from {}".format(agile_tag.id, agile_tag.attribute, AGILE_TAG_ATTRIBUTE.NULL))
                agile_tag.attribute = AGILE_TAG_ATTRIBUTE.NULL
                agile_tag.save()
