# -*- 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_RECOMMEND_TYPE

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


class AgileTagRecommendTypeService(object):
    model = AgileTagRecommendType
    _base_query = Q(is_online=True)

    @classmethod
    def create(cls, agile_tag_id, agile_recommend_types):
        """
        新标签推荐类型创建
        :param agile_tag_id:
        :param agile_recommend_types: list
        :return:
        """
        if not all([agile_tag_id, agile_recommend_types]):
            return

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

        cls.model.objects.bulk_create(recommend_type_list)

        return {'id': agile_tag_id}

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

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

        if recommend_types:
            result = defaultdict(list)
            for recommend_type in recommend_types.iterator():
                result[recommend_type['agile_tag_id']].append(recommend_type["agile_tag_type"])

        return result

    @classmethod
    def get_agile_tag_ids_by_recommend_type(cls,
                                            agile_tag_ids,
                                            recommend_type=AGILE_TAG_RECOMMEND_TYPE.TRACTATE):
        """
        根据推荐类型 获取标签id
        :param agile_tag_ids:
        :param recommend_type: 推荐类型
        :return:
        """
        result = []
        if not agile_tag_ids:
            return result

        agile_ids = list(cls.model.objects.filter(
            agile_tag_type=recommend_type, agile_tag_id__in=agile_tag_ids
        ).values_list('agile_tag_id', flat=True))

        return agile_ids
