# -*- coding: utf-8 -*-

from collections import defaultdict
from django.db.models import Q

from gm_types.error import ERROR
from gm_types.gaia import AGILE_TAG_TYPE

from agile.models.agile_tag import AgileTagType
from rpc.tool.error_code import gen


class AgileTagTypeService(object):
    _base_query = Q(is_online=True)
    model = AgileTagType

    @classmethod
    def create(cls, agile_tag_id, agile_tag_types=[AGILE_TAG_TYPE.UNDEFINED]):
        """
        标签 与 类型关联 manytomany
        :param agile_tag_id:
        :param agile_tag_types: list
        :return:
        """
        if not all([agile_tag_id, agile_tag_types]):
            return

        agile_type_list = []
        for _type in agile_tag_types:
            agile_type = cls.model(
                agile_tag_id=agile_tag_id,
                agile_tag_type=_type
            )
            agile_type_list.append(agile_type)

        cls.model.objects.bulk_create(agile_type_list)

    @classmethod
    def get_agile_types(cls, agile_ids):
        """
        获取新标签的类型
        :param agile_ids: list
        :return:
        """
        result = {}
        if not agile_ids:
            return result

        query = cls._base_query & Q(agile_tag_id__in=set(agile_ids))
        agile_tags_type = cls.model.objects.filter(query).values('agile_tag_id', 'agile_tag_type')

        if agile_tags_type:

            result = defaultdict(list)
            for _agile_type in agile_tags_type.iterator():
                result[_agile_type["agile_tag_id"]].append(_agile_type["agile_tag_type"])

        return dict(result)

    @classmethod
    def get_agile_ids_by_agile_type(cls, agile_type='', start_num=0, offset=15):
        """
        通过类型获取标签id
        :param agile_type:  agile_type为空时获取所有热门标签
        :param start_num:
        :param offset:
        :return:
        """
        query = cls._base_query
        if agile_type:
            query = query & Q(agile_tag_type=agile_type)

        agile_ids = list(cls.model.objects.filter(query).values_list('agile_tag_id', flat=True))

        return {'ids': agile_ids}
