#!/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

from answer.models import QuestionTag, Answer
from polymer.models import Polymer, PolymerTab, DeliverPolymer
from api.models.tag import Tag, TagRelation
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/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
