# coding:utf-8

from django.db.models import Q

from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from gm_dataquery.dict_mixin import to_dict

from agile.models.tag import TagCategory
from agile.models.tag import TagCategoryMapTag


class TagCategoryDB(DataBuilder):

    def getval_tag_count(self, obj):
        tags_cnt = TagCategoryMapTag.objects.filter(
            tag_category_id=obj.id, is_online=True).count()

        return tags_cnt

    def getval_tag_ids(self, obj):
        tag_ids = list(TagCategoryMapTag.objects.filter(
            tag_category_id=obj.id, is_online=True).values_list("tag_id", flat=True))

        return tag_ids


@DB
class TagCategoryDQ(DataSQLQuery):
    model = TagCategory
    data_model = TagCategoryDB

    def update(self, updates, **kwargs):

        tag_ids = updates.pop('tag_ids', None)
        if tag_ids is not None:
            tag_ids = list(map(lambda i: int(i), tag_ids))

        obj = self.model.objects.get(**kwargs)

        update_fields = ["name", 'is_online']

        to_update = False
        for field in update_fields:
            value = updates.pop(field, None)
            if value is not None:
                to_update = True
                setattr(obj, field, value)

        if to_update:
            obj.save()

        # 更新tag
        if tag_ids is not None:
            tags = list(TagCategoryMapTag.objects.filter(tag_category_id=obj.id).values_list('tag_id', flat=True))

            rm_ids = set(tags) - set(tag_ids)
            if rm_ids:
                TagCategoryMapTag.objects.filter(tag_category_id=obj.id, tag_id__in=rm_ids).delete()

            _ids = set(tags) & set(tag_ids)
            if _ids:
                TagCategoryMapTag.objects.filter(tag_category_id=obj.id, tag_id__in=_ids).update(is_online=True)

            new_ids = set(tag_ids) - set(tags)
            ats = [
                TagCategoryMapTag(
                    tag_category_id=obj.id,
                    tag_id=tag_id
                )
                for tag_id in new_ids
            ]
            if ats:
                TagCategoryMapTag.objects.bulk_create(ats)

        return {'id': obj.id}

    def create(self, **kwargs):

        tag_ids = kwargs.pop('tag_ids', None)

        obj = self.model.objects.create(**kwargs)

        # 更新tag
        ats = [
            TagCategoryMapTag(
                tag_category_id=obj.id,
                tag_id=tag_id
            )
            for tag_id in tag_ids
        ]
        if ats:
            TagCategoryMapTag.objects.bulk_create(ats)

        return {'id': obj.id}
