#!/usr/bin/env python
# coding=utf-8
from django.db.models import Q

from api.models import Tag
from gm_types.gaia import TAG_TYPE

from rpc.decorators import bind


@bind('doctor/tag/query')
def query_tag(query=None):
    """
        按 tag.name 进行搜索
        1. 匹配到三级tag, 返回其所有兄弟和父类;
        2. 匹配到二级tag，返回自己和所有子类
    """
    q = Q(tag_type=TAG_TYPE.BODY_PART_SUB_ITEM, is_online=True)
    # 根据二级tag去找,匹配name和孩子的name
    if query:
        name_query = Q(name__contains=query) | Q(
            all_children_relations__is_deleted=False,
            all_children_relations__child__is_online=True,
            all_children_relations__child__name__contains=query,
        )
        q &= name_query
    sub_tags = Tag.objects.filter(q).distinct()
    tags = []
    for sub_tag in sub_tags:
        children = []
        child_tags = sub_tag.online_child_tags()
        for c_tag in child_tags:
            children.append({
                'id': c_tag.id,
                'name': c_tag.name,
            })
        tags.append({
            'id': sub_tag.id,
            'name': sub_tag.name,
            'children': children,
        })
    return {
        'tags': tags,
    }


@bind('doctor/tag/list')
def tag_list():
    """
    返回所有在线2，3级tag
    :return:
    """
    tags = []
    for tag in Tag.objects.filter(tag_type__in=[TAG_TYPE.BODY_PART_SUB_ITEM, TAG_TYPE.ITEM_WIKI], is_online=True):
        data = {}
        data['id'] = tag.id
        data['name'] = tag.name
        tags.append(data)
    return tags


@bind('doctor/tag/second_list')
def second_tag_list():
    """
    返回所有在线2级tag
    :return:
    """
    tags = []
    for tag in Tag.objects.filter(tag_type__in=TAG_TYPE.BODY_PART_SUB_ITEM, is_online=True):
        data = {}
        data['id'] = tag.id
        data['name'] = tag.name
        tags.append(data)
    return tags


@bind('doctor/tag/third_list')
def second_tag_list(second_tag_id=None):
    """
    返回符合条件的3级标签
    :param second_tag_id: 二级标签ID
    :return:
    """
    tags = []
    if second_tag_id:
        tags_qs = Tag.objects.get(id=second_tag_id).children_relations.filter(
            child__tag_type=TAG_TYPE.ITEM_WIKI, child__is_online=True)
        for tag in tags_qs:
            data = {}
            data['id'] = tag.child.id
            data['name'] = tag.child.name
            tags.append(data)
    else:
        tags_qs = Tag.objects.filter(tag_type=TAG_TYPE.ITEM_WIKI, is_online=True)
        for tag in tags_qs:
            data = {}
            data['id'] = tag.id
            data['name'] = tag.name
            tags.append(data)
    return tags