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

from api.models import Tag, defaultdict, TagRelation
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

@bind('doctor/tag/all')
def all_tag_list():
    """
    返回符合条件的所有标签
    :return:
    """
    try:
        tags = Tag.objects.filter(is_online=True, is_display=True)
        # 一级类目
        level_1 = [{"id": item.id, "name": item.name, "child": []} for item in tags if item.tag_type == TAG_TYPE.BODY_PART]
        # 二级类目
        level_2 = {item.id: {"id": item.id, "name": item.name, "is_multiple": item.is_multiple, "child": []} for item in tags if item.tag_type == TAG_TYPE.BODY_PART_SUB_ITEM}
        # 三级类目
        level_3_dic = {item.id: {"id": item.id, "name": item.name, "is_std": item.is_std} for item in tags if item.tag_type == TAG_TYPE.ITEM_WIKI}
        # 标签关系映射表
        tag_id_mapping = defaultdict(set)
        for item in TagRelation.objects.filter(is_deleted=False):
            tag_id_mapping[item.parent_id].add(item.child_id)
        res = []
        for key, item in level_2.items():
                level_3_ids = tag_id_mapping.get(key, [])
                for level_3_id in level_3_ids:
                    if level_3_id in set(level_3_dic):
                        item['child'].append({
                            "id": level_3_id,
                            "name": level_3_dic.get(level_3_id).get("name", ""),
                            "is_std": level_3_dic.get(level_3_id, {}).get("is_std", False)
                            })

        # 组装一级类目
        for one_level_1_data in level_1:
            one_level_1_id = one_level_1_data.get("id")
            # 一级类目所对应的所有子类目
            level_2_ids = tag_id_mapping.get(one_level_1_id, [])
            for one_level_2_id in level_2_ids:
                if one_level_2_id in set(level_2):
                   one_level_1_data["child"].append(level_2.get(one_level_2_id))
            res.append(one_level_1_data)

        return {"data": res, "message": "", "error": 0}

    except BaseException as e:
        return {"message": str(e), "error": 500, "data": []}
