# coding:utf-8
from django.core.management.base import BaseCommand
from gm_types.gaia import TAG_TYPE_ATTR, TAG_V3_TYPE

from agile.models import AttrTag
from agile.models.tag import TagV3MapAttrTag, AttrTagSynonym, TagV3WikiRelation, TagV3, TagSynonym, TagAttrRelation
from utils.execel import ExcelReader


class Command(BaseCommand):
    """
    标签新增子属性 python manage.py tag_new_attr_async
    """

    def handle(self, *args, **options):
        print('START')

        # 增加新映射关系
        excel = ExcelReader('/tmp/标签导入模板.xlsx')

        # 删掉 一级、二级品牌对应的历史数据
        attr_tags = AttrTag.objects.filter(aggregate_type__in=[TAG_TYPE_ATTR.BRAND, TAG_TYPE_ATTR.FIRST_BRAND])
        _ids = [tag.id for tag in attr_tags]
        TagV3MapAttrTag.objects.filter(tag_attr_id__in=_ids).delete()
        AttrTagSynonym.objects.filter(tag_attr_id__in=_ids).delete()
        TagV3WikiRelation.objects.filter(attr_tag_id__in=_ids).delete()
        attr_tags.delete()
        # print(excel._excel.get_sheet_names())
        brand = excel._excel._sheets[0]
        print('-----------开始导入品牌标签-----------')
        for row in range(2, brand.max_row+1):
            max_column = brand.max_column + 1
            row_data = []
            for i in range(1, max_column):
                cell_value = brand.cell(row=row, column=i).value or u''
                print(cell_value)
                # cell_value = cell_value.decode('utf-8')
                row_data.append(cell_value)
            tag_name = str(row_data[0])
            synonyms = row_data[1].split(',') if row_data[1] else []
            if not any([tag_name, synonyms]):
                continue
            try:
                tag = TagV3.objects.create(
                    name=tag_name,
                    tag_type=TAG_V3_TYPE.BRAND,
                )
                synonym_objects = [
                    TagSynonym(
                        name=item,
                        tag_id=tag.id,
                        tag_type=TAG_V3_TYPE.BRAND,
                    ) for item in synonyms
                ]
                TagSynonym.objects.bulk_create(synonym_objects)
            except:
                continue
        print('-----------导入品牌标签完成-----------')

        print('-----------开始导入一级耗材属性标签-----------')
        first_level = excel._excel._sheets[1]
        for row in range(2, first_level.max_row+1):
            max_column = first_level.max_column + 1
            row_data = []
            for i in range(1, max_column):
                cell_value = first_level.cell(row=row, column=i).value or u''
                # cell_value = cell_value.decode('utf-8')
                row_data.append(cell_value)
            tag_name = str(row_data[0])
            synonyms = row_data[1].split(',') if row_data[1] else []
            if not any([tag_name, synonyms]):
                continue
            try:
                tag = AttrTag.objects.create(
                    name=tag_name,
                    aggregate_type=TAG_TYPE_ATTR.FIRST_BRAND,
                )
                synonym_objects = [
                    AttrTagSynonym(
                        name=item,
                        tag_attr_id=tag.id,
                    ) for item in synonyms
                ]
                AttrTagSynonym.objects.bulk_create(synonym_objects)
            except:
                continue
            print('-----------导入一级耗材属性标签完成-----------')

        print('-----------开始导入二级耗材属性标签-----------')
        second_level = excel._excel._sheets[2]
        for row in range(2, second_level.max_row+1):
            max_column = second_level.max_column + 1
            row_data = []
            for i in range(1, max_column):
                cell_value = second_level.cell(row=row, column=i).value or u''
                # cell_value = cell_value.decode('utf-8')
                row_data.append(cell_value)
            tag_name = str(row_data[0])
            synonyms = row_data[1].split(',') if row_data[1] else []
            sub_type = row_data[2]
            brand_name = row_data[3]
            if not any([tag_name, synonyms]):
                continue
            try:
                tag = AttrTag.objects.create(
                    name=tag_name,
                    aggregate_type=TAG_TYPE_ATTR.BRAND,
                    sub_attr_type=sub_type,
                )
                synonym_objects = [
                    AttrTagSynonym(
                        name=item,
                        tag_attr_id=tag.id,
                    ) for item in synonyms
                ]
                AttrTagSynonym.objects.bulk_create(synonym_objects)
                if brand_name:
                    names = brand_name.split(',')
                    tags = TagV3.objects.filter(name__in=names, tag_type=TAG_V3_TYPE.BRAND)
                    tag_v3_ids = [t.id for t in tags]
                    if tag_v3_ids:
                        brand_objects = [
                            TagV3MapAttrTag(
                                tag_id=_id,
                                tag_attr_id=tag.id,
                            ) for _id in tag_v3_ids
                        ]
                        TagV3MapAttrTag.objects.bulk_create(brand_objects)
            except:
                continue
            print('-----------导入二级耗材属性标签完成-----------')

        print('-----------开始导入一级、二级耗材属性标签关系-----------')
        relation = excel._excel._sheets[3]
        for row in range(2, relation.max_row+1):
            max_column = relation.max_column + 1
            row_data = []
            for i in range(1, max_column):
                cell_value = relation.cell(row=row, column=i).value or u''
                # cell_value = cell_value.decode('utf-8')
                row_data.append(cell_value)
            first = row_data[1].encode().decode('utf-8')
            second = row_data[0].encode().decode('utf-8')
            # print(first)
            # print(second)
            if not all([first, second]):
                continue
            related_ids = set()
            first_brand = AttrTag.objects.filter(name=first, aggregate_type=TAG_TYPE_ATTR.FIRST_BRAND).first()
            second_brand = AttrTag.objects.filter(name=second, aggregate_type=TAG_TYPE_ATTR.BRAND).first()
            if not all([first_brand, second_brand]):
                continue
            related_ids.add((first_brand.id, second_brand.id))
            print(related_ids)

            related_objects = [
                TagAttrRelation(
                    parent_id=item[0],
                    child_id=item[1],
                ) for item in related_ids
            ]
            TagAttrRelation.objects.bulk_create(related_objects)

            print('-----------导入一级、二级耗材属性标签关系完成-----------')

        print("Done!")
