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

from __future__ import unicode_literals, absolute_import, print_function

from django.conf import settings
from django.db.models import F
from django.db import transaction

from rpc.decorators import bind
from rpc.decorators import cache_page
from relation.models import UserTagRelation

from gm_types.gaia import (
    POLYMER_DETAIL_TAB_TYPE,
    TAG_TYPE,
    TAG_V3_TYPE,
)

from agile.models import TagV3
from agile.services import (
    TagV3Control,
)
from answer.models import QuestionTag, Answer
from api.business.tag import TagControl
from api.models.tag import Tag, TagRelation
from polymer.models import (
    Polymer,
    PolymerTab,
    DeliverPolymer,
    PolymerSurgery,
    PolymerTag,
    PolymerTagV3,
)
from rpc.decorators import list_interface

POLYMER_ID_IS_DISCUSS = settings.POLYMER_ID_IS_DISCUSS


@cache_page(60 * 60)
def cache_polymer_follow_num(polymer_id=0):
    """
    获取关注当前聚合面所属的人数
    :param polymer_id:
    :return:
    """
    try:
        tag_id_list = list(Polymer.objects.get(id=polymer_id).tags.values_list("id", flat=True))
        user_attent_by_tag = UserTagRelation.objects \
            .filter(related_tag_id__in=tag_id_list) \
            .values_list("user_id", flat=True) \
            .distinct().count()
    except:
        return -1
    return user_attent_by_tag


@cache_page(60 * 60)
def cache_polymer_discuss_follow_num(polymer_id=0):
    """
    获取关注当前聚合面所属问题数与答案数
    :param polymer_id:
    :return:
    """
    try:
        tag_id_list = list(Polymer.objects.get(id=polymer_id).tags.values_list("id", flat=True))
        question_list_by_tag = list(
            QuestionTag.objects.filter(tag__in=tag_id_list).values_list("question_id", flat=True))
        answer_list_by_question = Answer.objects.filter(question__in=question_list_by_tag).values_list("id").count()
    except:
        return -1
    return answer_list_by_question + len(question_list_by_tag)


@cache_page(5 * 60)
def cache_polymer_type_disscuss():
    """
    获取含有讨论tab的所有在线（含有tag的）聚合页,并返回一张所属tag图片，如果没有图片则返回空,并按返回互动数
    """
    """
    临时更改了7705需求，http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=9766924
    以下是之前的逻辑
    polymer_type_is_discuss = PolymerTab.objects.filter(
        tab_type=POLYMER_DETAIL_TAB_TYPE.DISSCUSS,
        enable=True,
    ).values_list("polymer_id", flat=True).distinct()
    # 确定查询出的polymer存在所属的在线tag
    polymer_info = Polymer.objects.filter(is_online=True, id__in=polymer_type_is_discuss,
                                          tags__is_online=True).values("id", "name").distinct()
    polymer_id_list = [x["id"] for x in polymer_info]
    tag_info_list = Tag.objects.filter(polymer__id__in=polymer_id_list, is_online=True).values("polymer__id", "id",
                                                                                               "icon_url")

    # 将字典转为{polymer_id:pilymer_image}
    polymer_image_dict = {}
    for tag_info in tag_info_list:
        if tag_info["polymer__id"] not in polymer_image_dict:
            polymer_image_dict[tag_info["polymer__id"]] = ''
        if tag_info["icon_url"]:
            polymer_image_dict[tag_info["polymer__id"]] = tag_info["icon_url"]

    items = []
    for item in polymer_info:
        item["image"] = polymer_image_dict.get(item["id"])
        items.append(item)

    return items
    """


    # 确定查询出的polymer存在所属的在线tag
    polymer_info = Polymer.objects.filter(is_online=True, id__in=POLYMER_ID_IS_DISCUSS).values("id", "name")
    tag_info_list = Tag.objects.filter(polymer__id__in=POLYMER_ID_IS_DISCUSS, is_online=True
                                       ).values("polymer__id", "id", "icon_url")

    # 将字典转为{polymer_id:pilymer_image}
    polymer_image_dict = {}
    for tag_info in tag_info_list:

        polymer_id = tag_info["polymer__id"]

        if polymer_id and polymer_id not in polymer_image_dict:
            polymer_image_dict[polymer_id] = ''

        if tag_info["icon_url"] and not polymer_image_dict.get(polymer_id, ''):
            polymer_image_dict[polymer_id] = tag_info["icon_url"]

    items = []
    for item in polymer_info:
        item["image"] = polymer_image_dict.get(item["id"], '')
        items.append(item)

    return items


@cache_page(5 * 60)
def get_all_polymer_can_deliver():
    polymer_list = DeliverPolymer.objects.filter(is_online=True).order_by("rank")
    data = []
    for deliverpolymer in polymer_list:
        _data = deliverpolymer.polymer.tag_list
        if _data:
            data.append({
                'polymer_id': deliverpolymer.polymer_id,
                'polymer_name': deliverpolymer.polymer.name,
                'tag_ids': [x["id"] for x in _data],
            })
    return data


@bind('api/polymer/search_by_tag')
def get_polymer_by_tag(tags=None):
    """
    先取一级tag 没有的话根据二级tag----->一级tag来取  还没有根据三级tag---->二级tag-->一级tag来取
    """
    if not tags:
        return {}

    tags = sorted(tags, key=lambda x: x.get('tag_id'))
    tag_data = [x['id'] for x in tags if x['type'] == TAG_TYPE.BODY_PART]
    tag_id = tag_data[0] if tag_data else None
    if not tag_data:
        tag_data = [x['id'] for x in tags if x['type'] in (TAG_TYPE.BODY_PART_SUB_ITEM, TAG_TYPE.ITEM_WIKI)]
        tag_top_tag = TagRelation.get_top_tags(tag_ids=tag_data)
        if tag_top_tag.get('first'):
            tag_id = tag_top_tag.get('first')[0].id
        elif tag_top_tag.get('second'):
            tag_id = tag_top_tag.get('second')[0].id
        else:
            tag_id = tags[0]['tag_id']

    try:
        tag = Tag.objects.get(id=tag_id)
    except Tag.DoesNotExist:
        return {}

    polymer = tag.polymer.first()

    if not polymer:
            return {}

    return {
         'id': polymer.id,
         'name': polymer.name,
    }


@bind('api/polymer/search_by_tag_v2')
def get_polymer_by_tag_v2(old_tags=None, tags_v3=None):
    """
    先取一级tag 没有的话根据二级tag----->一级tag来取  还没有根据三级tag---->二级tag-->一级tag来取
    """
    result = {}

    if not any([old_tags, tags_v3]):
        return result

    v3_tags = sorted(tags_v3, key=lambda y: y.get("tag_id"))
    v1_tags = sorted(old_tags, key=lambda x: x.get('tag_id'))

    relation_polymer_id = 0

    if v3_tags:
        item_tag_ids = [tag["tag_id"] for tag in v3_tags if (tag.get("tag_type") or tag.get("type")) in
                        (TAG_V3_TYPE.NORMAL, TAG_V3_TYPE.SECOND_CLASSIFY, TAG_V3_TYPE.FIRST_CLASSIFY)]
        if item_tag_ids:
            v3_tag_objs = TagV3.objects.filter(pk__in=item_tag_ids, is_online=True, is_display=True)
            v3_first_obj_list = TagV3Control.get_ancestors(
                initial_set=v3_tag_objs,
                exclude_init=None,
                tag_type=TAG_V3_TYPE.FIRST_CLASSIFY,
                is_online_only=True
            )
            tag_v3_id = v3_first_obj_list and sorted((tag_v3.id for tag_v3 in v3_first_obj_list))[0] or 0
        else:
            tag_v3_id = v3_tags[0]["tag_id"]

        relation_polymer_id = PolymerTagV3.objects.filter(
            tag_v3_id=tag_v3_id,
            is_online=True
        ).values_list("polymer_id", flat=True).first()

    if v1_tags and not relation_polymer_id:
        item_tag_ids = [tag["tag_id"] for tag in v1_tags if (tag.get("tag_type") or tag.get("type")) in
                        (TAG_TYPE.ITEM_WIKI, TAG_TYPE.BODY_PART_SUB_ITEM, TAG_TYPE.BODY_PART)]
        if item_tag_ids:
            tag_objs = Tag.objects.filter(pk__in=item_tag_ids, is_online=True)
            first_obj_list = TagControl.get_ancestors(
                initial_set=tag_objs,
                exclude_init=None,
                tag_type=TAG_TYPE.BODY_PART,
                is_online_only=True
            )
            tag_id = first_obj_list and sorted((tag.id for tag in first_obj_list))[0] or 0
        else:
            tag_id = v1_tags[0]["tag_id"]

        relation_polymer_id = PolymerTag.objects.filter(
            tag_id=tag_id,
            is_online=True
        ).values_list("polymer_id", flat=True).first()

    polymer = None
    if relation_polymer_id:
        polymer = Polymer.objects.filter(
            pk=relation_polymer_id,
            is_online=True
        ).only("id", "name").first()

    if polymer:
        result = {
             'id': polymer.id,
             'name': polymer.name,
        }

    return result


@bind('api/polymer/deliver_polymer')
@list_interface(offset_name='offset', limit_name='count')
def all_deliver_polymer(offset=0, count=10):
    polymer_list = get_all_polymer_can_deliver()[offset: offset+count]
    return {'deliver_polymer_data':polymer_list}


@bind("api/polymer/update_deliver_polymer")
def update_deliver_polymer(polymer_ids, deliver_count):
    """
    更新投稿到小组数据
    :param polymer_ids:
    :param deliver_count:
    :return:
    """
    result = {
        "update_count": 0,
        "status": False,
    }
    if not polymer_ids or not deliver_count:
        return result

    with transaction.atomic():
        update_count = DeliverPolymer.objects.filter(polymer_id__in=polymer_ids
                                                     ).update(deliver_count=F("deliver_count")+deliver_count)
        result["status"] = True
        result["update_count"] = update_count

    return result


@bind('api/polymer/is_surgery')
def gets_polymer_is_surgery(polymer_ids):
    if not polymer_ids:
        return {}
    objs = PolymerSurgery.objects.filter(polymer_id__in=polymer_ids, is_surgery=True)
    return {str(obj.polymer_id): obj for obj in objs}


@bind('api/polymers')
def get_polymers_with_ids(polymer_ids):
    objs = Polymer.objects.filter(is_online=True, id__in=polymer_ids)
    result = list()
    for obj in objs:
        polymer = dict()
        polymer["id"] = obj.id
        polymer["name"] = obj.name
        polymer["description"] = obj.description
        polymer["tags"] = obj.tag_list
        polymer["bg_image"] = obj.bg_image
        result.append(polymer)
    return result
