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

from collections import defaultdict
from django.db import IntegrityError
from django.db.models import Q
from django.conf import settings

from gm_types.error import ERROR

from api.models import Tag
from agile.models.agile_tag import AgileTagMapping, AgileTag


class AgileTagMappingTagService(object):

    model = AgileTagMapping
    _base_query = Q(is_online=True)

    @classmethod
    def get_mapping_tags_by_agile_tag_ids(cls, agile_tag_ids, only_need_old_tag_ids=False):
        """
        获取所有映射的老标签数据

        if only_need_old_tag_ids:
            return {new_tag_id: [old_tag_id1, old_tag_id2]}
        else
            return {
                new_tag_id : [
                    {
                        "id": 1,
                        "name": "标签名"，
                        "tag_type": 标签类型,
                        "recommend_type": 推荐类型,
                    },
                ]
            }
        :param agile_tag_ids:
        :param only_need_old_tag_ids: 仅需要老标签id
        :return:
        """
        result = {}
        filter_query = cls._base_query & Q(agile_tag_id__in=agile_tag_ids)
        mapping_tags = cls.model.objects.filter(filter_query).values("agile_tag_id", "old_tag_id")

        if mapping_tags:
            result = defaultdict(list)

            if only_need_old_tag_ids:
                old_tags_info_dic = {}
            else:
                _old_tag_ids = set(map(lambda item: item["old_tag_id"], mapping_tags))
                old_tags_info = Tag.objects.filter(
                    pk__in=_old_tag_ids,
                    is_online=True
                ).values("id", "name", "tag_type", "recommend_type")

                old_tags_info_dic = {
                    tag_info["id"]: dict(tag_info) for tag_info in old_tags_info
                }

            for mapping_tag in mapping_tags:
                if only_need_old_tag_ids:
                    _info = mapping_tag["old_tag_id"]
                else:
                    _info = old_tags_info_dic.get(mapping_tag["old_tag_id"], {})

                if _info:
                    result[str(mapping_tag["agile_tag_id"])].append(_info)

        return dict(result)

    @classmethod
    def get_mapping_tags_by_old_tag_ids(cls, old_tag_ids):
        """
        通过老标签获取对应的新标签
        :param old_tag_ids:
        :return: {old_tag_id: [new_tag_id1, new_tag_id2]}
        """
        result = {}
        filter_query = cls._base_query & Q(old_tag_id__in=old_tag_ids)
        mapping_tags = cls.model.objects.filter(filter_query).values("agile_tag_id", "old_tag_id")

        if mapping_tags:
            result = defaultdict(list)
            for mapping_tag in mapping_tags:
                result[str(mapping_tag["old_tag_id"])].append(mapping_tag["agile_tag_id"])

        return dict(result)

    @classmethod
    def get_mapping_tags_tuple_by_old_tag_ids(cls, old_tag_ids):
        """
        通过老标签获取对应的新标签
        :param old_tag_ids:
        :return: [(new_tag_id1,new_tag_id1_name), (new_tag_id2,new_tag_id2_name)]}
        """
        filter_query = cls._base_query & Q(old_tag_id__in=old_tag_ids)
        agile_tag_ids = cls.model.objects.filter(filter_query).values_list('agile_tag_id', flat=True)
        if not agile_tag_ids:
            return list()
        res = AgileTag.objects.filter(id__in=agile_tag_ids).values_list('id', 'name')
        # print res[0]
        return res
