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

from django.conf import settings
from django.db.models import Q

from gm_types.error import ERROR
from gm_types.gaia import (
    TAG_TYPE_ATTR,
    TAG_V3_TYPE,
)
from agile.models import (
    TagV3,
)
from agile.services import (
    TagV3Service,
    TagV3Control,
)

from agile.services.tag import get_diary_ids_for_ai_tab

from rpc.decorators import (
    bind,
    bind_context,
)
from rpc.tool.dict_mixin import to_dict
from rpc.tool.error_code import gen


MAX_LENGTH = 100


@bind("api/tag_v3/related_tags_info_by_id_on_second_appeal")
def list_related_tags_info_by_id_on_second_appeal(tag_id):
    """
    通过标签id，获取基本信息
    :param tag_ids:
    :return: {} dict
    """
    second_appeal_attrs = TagV3Service.list_second_appeal_attrs([tag_id])
    tags = TagV3Service.list_tags_by_attrs([attr.id for attrs in second_appeal_attrs.values() for attr in attrs])
    return list(tags.values())


@bind("api/tag_v3/get_tags_by_attr_tag_ids")
def get_tags_by_attr_tag_ids(attr_tag_ids):
    """
    通过属性标签获取普通标签
    :param attr_tag_ids:属性标签id列表
    :return: list
    """
    tags = TagV3Service.list_normal_tags_by_attrs(attr_tag_ids)
    return list(tags.values())


@bind("api/tag_v3/info_by_ids")
def get_tag_v3_info_by_ids(tag_ids):
    """
    通过标签id，获取基本信息
    :param tag_ids:
    :return: {} dict
    """
    return TagV3Service.get_tags_v3_by_ids(tag_ids)


@bind("api/tag_v3/attr_info_by_ids")
def get_attr_tag_infos_by_ids(attr_ids, attr_types=None):
    """
    backend 无调用
    通过属性标签ID，获取属性标签信息
    :param attr_ids:
    :param attr_types: [] 默认为空，属性类型列表
    :return:
    """
    return TagV3Service.get_attr_tag_info_by_attr_ids(attr_ids, attr_types=attr_types)


@bind("api/tag_v3/get_map_new_tag_by_old_ids")
def get_map_new_tag_by_old_ids(old_tag_ids):
    """
    通过老标签id，获取映射的新标签数据
    :param old_tag_ids:
    :return: {} dict
    """
    return TagV3Service.get_tag_v3_info_by_old_ids(old_tag_ids)


@bind("api/tag_v3/get_bodypart_tags")
def get_bodypart_tags(need_app_display=False):
    """level one tags, and sub_bodypart_items tags.
    :param need_app_display: 需要app外显属性的标签，默认是全部标签
    :return:
    """
    return TagV3Service.get_bodypart_tags(need_app_display=need_app_display)


@bind("api/tag_v3/get_closure_tags")
def get_closure_tags(tag_ids, is_online_only=True, only_need_app_display=False):
    """
    获取标签的所有父类标签，注意:这块未保留关联关系
    :param tag_ids:
    :param is_online_only:
    :param only_need_app_display:  仅需要app外显的
    :return:
    """
    tags = TagV3Service.get_objs_by_query_and_order(
        model_set=TagV3,
        query=Q(pk__in=tag_ids)
    )
    closure_tags = TagV3Control.get_ancestors(
        initial_set=tags,
        exclude_init=False,
        is_online_only=is_online_only,
        only_need_app_display=only_need_app_display
    )

    return [to_dict(t, fields=('id', 'name', 'tag_type')) for t in closure_tags]


@bind("api/tag_v3/get_ai_tab_unclean_diary_ids")
def get_ai_tab_unclean_diary_ids(last_diary_id=None, max_diary_id=None):
    """"根据strategy_id获取未来清洗的日记id。

    Return:
        {
            unclean_diary: [
                1, 2, 3, 4, 5....
            ]
        }
    """
    unclean_diary = get_diary_ids_for_ai_tab(last_diary_id, max_diary_id)
    return {"unclean_diary": list(unclean_diary)}


@bind("api/tag_v3/list_group_by_tags")
def list_group_by_tags(tag_ids):
    """"根据标签ID列表获取标签大组信息。

    Return:
        {
            tag_id: [
                {
                    "id": category.id,
                    "name": category.name,
                }
            ]
        }
    """

    tag_category_map = TagV3Service.get_category_by_tags(tag_ids)

    result = {}
    for k, v in tag_category_map.items():
        result[str(k)] = v

    return result


@bind('api/tag_v3_category')
def get_tag_v3_category(category_ids):
    """根据大组id获取大组信息"""

    tag_category_map = TagV3Service.get_category_by_ids(category_ids)

    result = {}
    for k, v in tag_category_map.items():
        result[str(k)] = v

    return result


@bind('api/tag_v3/gets_relation_tag')
def gets_relation_tag(tag_ids=None, tag_names=None, tag_type=None):
    """获取指定标签的相关标签"""
    service = TagV3Service()
    return service.gets_relation_tag(tag_ids=tag_ids, tag_names=tag_names, tag_type=tag_type)


@bind('api/tag_v3/gets_info')
def gets_info(tag_ids=None, tag_names=None, tag_type=None):
    """获取指定标签的信息"""
    service = TagV3Service()
    return service.gets_info(tag_ids=tag_ids, tag_names=tag_names, tag_type=tag_type)


@bind('api/tag_v3/gets_synonym_or_homoionym')
def gets_synonym_or_homoionym(tag_ids=None, tag_names=None, tag_type=None, get_synonym=True):
    """获取指定标签的近义词或同义词"""
    service = TagV3Service()
    return service.gets_synonym_or_homoionym(
        tag_ids=tag_ids, tag_names=tag_names, tag_type=tag_type, get_synonym=get_synonym)


@bind('api/tag_v3/gets_tag_info_by_ids')
def gets_tag_info_by_ids(tag_ids=None, tag_type=None):
    """获取指定标签信息"""
    service = TagV3Service()
    return service.gets_tag_info_by_ids(tag_ids=tag_ids, tag_type=tag_type)


@bind('api/tag_v3/gets_tag_normal')
def gets_tag_normal():
    """获取新标签---项目标签"""
    tag_list = []
    tags = TagV3.objects.filter(tag_type=TAG_V3_TYPE.NORMAL, is_online=True)
    for tag in tags:
        tag_list.append({
            'id': tag.id,
            'name': tag.name,
            'tag_type': tag.tag_type,

        })
    return {'tagv3_normal': tag_list}


@bind('api/tag_v3/by_type')
def get_tag_ids_by_type(tag_type):
    if tag_type not in TAG_V3_TYPE:
        return {}

    ids = TagV3Service.get_tag_ids_by_type(tag_type)

    return {'tag_v3_ids': ids}
