# -*- coding: utf-8 -*-
from django.db import IntegrityError
from django.db.models import Q
from django.conf import settings
from gm_types.error import ERROR
from gm_types.gaia import AGILE_TAG_CREATE_TYPE, AGILE_TAG_STYLE, AGILE_TAG_TYPE

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


class AgileTagService(object):
    model = AgileTag
    _base_query = Q(is_online=True)

    @classmethod
    def create(cls, name=None, description='', order=9999,
               create_tag_type=AGILE_TAG_CREATE_TYPE.CUSTOM, style=AGILE_TAG_STYLE.UNDEFINED):
        if not name:
            return gen(ERROR.AGILE_TAG_NAME_ERR)

        data = {
            'name': name,
            'description': description,
            'topic_recommend_sort': order,
            'create_tag_type': create_tag_type,
            'style': style,
        }
        try:
            agile_tag = cls.model.objects.create(**data)
        except IntegrityError:
            return gen(ERROR.AGILE_TAG_NAME_EXIST)

        return {
            'tag_id': agile_tag.id,
            'name': agile_tag.name
        }

    @classmethod
    def tag_obj_to_dict(cls, obj, simple=True):
        _style = obj.style
        _data = {
            "id": obj.id,
            "name": obj.name,
            "style": _style,
            "style_image_url": settings.AGILE_STYLE.get(_style, ''),
            "attribute": obj.attribute,   # 标签属性
        }

        if not simple:
            _data.update({
                'description': obj.description,
                'order': obj.topic_recommend_sort,
                'create_tag_type': obj.create_tag_type,
            })

        return _data

    @classmethod
    def tag_queryset_to_dict(cls, queryset=None, simple=True):
        result = []
        for item in queryset.iterator():
            result.append(cls.tag_obj_to_dict(item, simple=simple))
        return {'result': result}

    @classmethod
    def get_tag_by_ids(cls, agile_ids, simple=True):
        query = cls._base_query & Q(id__in=agile_ids)
        queryset = cls.model.objects.filter(query)

        return cls.tag_queryset_to_dict(queryset, simple=simple)

    @classmethod
    def get_hot_agile_tags_by_ids(cls, agile_ids, simple=True, start_num=0, offset=15):
        """
        获取 热门标签
        :param agile_ids:
        :param start_num:
        :param offset:
        :param simple:
        :param show_style:  展示标签 样式
        :return:
        """
        query = cls._base_query & Q(id__in=agile_ids)
        agile_tags = cls.model.objects.filter(query).order_by(
            'topic_recommend_sort', '-id')[start_num: start_num+offset]
        agile_dic = cls.tag_queryset_to_dict(agile_tags, simple=simple)

        return agile_dic
