#!/usr/bin/env python
# -*- coding: utf-8 -*-

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

from polymer.models import AgileTagRelationPolymer


class AgileTagRelationPolymerService(object):
    model = AgileTagRelationPolymer
    _base_query = Q(is_online=True)

    @classmethod
    def create(cls, agile_tag_id, polymer_id):
        if not all([agile_tag_id, polymer_id]):
            return

        cls.model.objects.update_or_create(
            agile_tag_id=agile_tag_id,
            polymer_id=polymer_id,
            defaults={"is_online": True},
        )

    @classmethod
    def get_polymer_id_by_agile_tag_ids(cls, agile_tag_ids):
        """
        获取新标签关联的聚合页
        :param agile_tag_ids:
        :return: {agile_tag_id: polymer_id1,}
        """
        result = {}
        filter_query = cls._base_query & Q(agile_tag_id__in=agile_tag_ids)
        relation_polymers = cls.model.objects.filter(filter_query).values("agile_tag_id", "polymer_id")

        if relation_polymers:
            result = defaultdict(int)
            for relation_polymer in relation_polymers:
                result[relation_polymer["agile_tag_id"]] = relation_polymer["polymer_id"]

        return dict(result)
