# -*- coding: UTF-8 -*-

from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB

from api.models.hera import SpecialPool, SpecialPoolRelationTag
from rpc.tool.dict_mixin import to_dict


class SpecialPoolDB(DataBuilder):
    def getval_project_tag_ids(self, obj):
        relations = SpecialPoolRelationTag.objects.filter(is_deleted=False, special_pool_id=obj.id).values('project_tag_id')
        project_tag_ids = [item['project_tag_id'] for item in relations]
        return project_tag_ids

    def getval_project_tag_names(self, obj):
        relations = SpecialPoolRelationTag.objects.filter(is_deleted=False, special_pool_id=obj.id).values('project_tag_id')
        project_tag_ids = [item['project_tag_id'] for item in relations]
        from agile.models import TagV3
        tags = TagV3.objects.filter(id__in=project_tag_ids)
        return [item.name for item in tags]

    def getval_is_home_page_conf(self, obj):
        if obj.order and obj.a_position_image and obj.b_position_image and obj.c_d_position_image:
            return True
        return False


@DB
class SpecialPoolDQ(DataSQLQuery):
    model = SpecialPool
    data_model = SpecialPoolDB

    def filter_created_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)
    
    def filter_project_tag_names(self, srch_key, srch_val, regex=False):
        if isinstance(srch_val, list):
            tag_ids = [int(item) for item in srch_val]
        else:
            tag_ids = [int(srch_val)]
        ids = list(SpecialPoolRelationTag.objects.filter(
            project_tag_id__in=tag_ids, is_deleted=False
        ).values_list("special_pool_id", flat=True))
        return Q(pk__in=ids)

    def create(self, **kwargs):
        project_tag_ids = kwargs.pop('project_tag_ids', [])
        project_tag_ids = [int(item) for item in project_tag_ids]
        order = kwargs.pop('order')
        if order:
            kwargs['order'] = order
        obj = to_dict(self.model.objects.create(**kwargs))
        if obj and project_tag_ids:
            relations = [SpecialPoolRelationTag(special_pool_id=obj['id'], project_tag_id=item)
                         for item in project_tag_ids]

            SpecialPoolRelationTag.objects.bulk_create(relations)
        return obj

    def update(self, updates, **kwargs):
        id_ = kwargs['id']
        project_tag_ids = updates.get('project_tag_ids', None)
        if project_tag_ids is not None:
            project_tag_ids = updates.pop('project_tag_ids', [])
            project_tag_ids = [int(item) for item in project_tag_ids]
            if not project_tag_ids:
                SpecialPoolRelationTag.objects.filter(special_pool_id=id_, is_deleted=False).update(is_deleted=True)
            else:
                query = Q(special_pool_id=id_) & ~Q(project_tag_id__in=project_tag_ids) & Q(is_deleted=False)
                SpecialPoolRelationTag.objects.filter(query).update(is_deleted=True)
                exist_relations = SpecialPoolRelationTag.objects.filter(
                    special_pool_id=id_, is_deleted=False).values('project_tag_id')
                exist_tag_ids = [item['project_tag_id'] for item in exist_relations]
                need_update_ids = [tag_id for tag_id in project_tag_ids if tag_id not in exist_tag_ids]
                update_relations = SpecialPoolRelationTag.objects.filter(
                    is_deleted=True, project_tag_id__in=need_update_ids).values('id', 'project_tag_id')
                update_deleted_false_ids = [item['id'] for item in update_relations]
                SpecialPoolRelationTag.objects.filter(id__in=update_deleted_false_ids).update(is_deleted=False)
                update_project_ids = [item['project_tag_id'] for item in update_relations]
                need_insert_ids = [item for item in need_update_ids if item not in update_project_ids]
                relations = [SpecialPoolRelationTag(special_pool_id=id_, project_tag_id=item)
                             for item in need_insert_ids]
                SpecialPoolRelationTag.objects.bulk_create(relations)
        return super(SpecialPoolDQ.sqlquery, self).update(updates, **kwargs)
