# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

import datetime
from django.db.models import Q
from django.utils.html import escape
from gm_rpcd.all import bind
from gm_types.gaia import (
    PROBLEM_FLAG_CHOICES,
    TOPIC_TYPE,
)
from gm_types.mimas.qa import VIDEO_SOURCE_TYPE

from live.tasks import get_qiniu_persistent_ids

from talos.decorators import list_interface
from talos.models.topic import VotePK
from talos.models.topic import Problem, PgcClassify, ReplyHeadline
from talos.rpc import bind_context
from talos.services import get_user_from_context
from talos.services.user import UserService
from talos.statistic import (
    topic_view_increase_num,
    diary_view_increase_num,
)
from utils.common import get_data_from_rich_text


@bind('topic/ordered_pgc_ids')
def ordered_pgc_ids():
    ids = PgcClassify.objects.values_list('id', flat=True).order_by('ordering')
    return list(ids)


@bind('topic/addview')
def add_topic_view(topic_id):
    try:
        topic = Problem.objects.get(pk=topic_id)
    except Problem.DoesNotExist:
        return {'added': False}

    ids = [topic_id]
    topic_view_increase_num(ids)
    diary_view_increase_num([topic.diary_id, ])
    return {'added': True}


@bind('topic/addview_by_ids')
def add_topics_view(topic_ids):
    if not topic_ids:
        return
    topic_view_increase_num(topic_ids)
    return


@bind_context('topic/vote_pk_info')   # TODO CR vote pk 接口最后改或者不需要改
def vote_pk_info(ctx, topic_id=None, doctors_id=None, users_id=None):
    '''
    通过topic_id获取已经投票的信息
    '''
    result = {
        'vote_num': 0,
        'can_vote': True,
        'vote_info': {},
    }
    if not topic_id:
        return result
    try:
        topic = Problem.get_by_id(topic_id)
    except:
        return result
    voted_data = VotePK.objects.filter(topic=topic)

    total_vote_num = voted_data.count()

    user = get_user_from_context(ctx)

    def voted(voted_data, user):
        return False if voted_data.filter(person_id=user.person_id, vote_date=datetime.date.today()) else True

    can_vote = True if not user else voted(voted_data, user)
    # 非登录用户显示可以投票 登录用户判断是否已经投票

    voted_info = VotePK.vote_info(
        topic=topic,
        doctors_id=doctors_id,
        users_id=users_id,
        user=user
    )

    return {
        'vote_num': total_vote_num,
        'can_vote': can_vote,
        'vote_info': voted_info,
    }


@bind("topic/topics/smart/index")
# @bind("talos/topic/topics_smart_index")
def api_topic_topics_index(topic_id, topic_reply_id):
    topic = Problem.get_by_id(topic_id)
    if topic:
        if topic.flag == PROBLEM_FLAG_CHOICES.NORMAL and topic.is_online:
            replies = topic.topicreply_set.filter(commented_reply__isnull=True, is_online=True)
            replies = replies.order_by('-id')
            try:
                specific_reply = topic.topicreply_set.get(pk=topic_reply_id)
            except:
                return -1
            lower_replies = replies.filter(
                reply_date__gt=specific_reply.reply_date)

            return lower_replies.count()
    return -1


@bind('topic/community/best_ask')
@list_interface(offset_name="start_num", limit_name='count')
def get_best_ask(start_num=0, count=10, is_doctor=False, only_topic=False):
    """
    NOTE: ONLY RETURN REPLY FOR TOPIC

    DESC: 获取社区的精彩问答，按照时间倒序排列
    :param start_num:
    :param count:
    :param is_doctor: 只刷选医生的精彩回答
    :param only_topic: 医生版只刷选帖子的
    :return:
    """
    query = Q(is_online=True) & Q(reply__problem__isnull=False)
    if is_doctor:
        query = query & Q(reply__doctor_id__isnull=False)    # NOTE 对于15年前10月份以前的数据,这个查询可能有 Bug
        if only_topic:
            query = query & Q(reply__problem__isnull=False)

    reply_headlines = ReplyHeadline.objects.select_related('reply').filter(query).order_by('-create_time')
    paged_reply_headlines = reply_headlines[start_num: start_num+count]
    replies = [rh.reply for rh in paged_reply_headlines]
    if not replies:
        return []

    result = [
        {
            'topic': {
                'id': reply.problem_id,
                'problem_ask': reply.problem.ask,
                'problem_answer': reply.problem.answer,
            },
            'reply': {
                'content': escape(reply.content),
                'reply_id': reply.id,
            },
            'user': {
                'user_id': reply.user_id,
                'portrait': '',
                'membership_level': 0,
            }
        }
        for reply in replies
    ]
    user_ids = [r.user_id for r in replies]
    users = UserService.get_users_by_user_ids(user_ids)
    for r in result:
        uid = r['user']['user_id']
        if uid in users:
            portrait = users[uid].portrait
            membership_level = users[uid].membership_level
            r['user']['portrait'] = portrait
            r['user']['membership_level'] = membership_level

    return result


@bind("topic/article/add_video_water_url")
def article_rich_text_add_water_url(source_id):
    try:
        article_obj = Problem.objects.get(id=source_id)
        _topic_type = article_obj.topic_type

        if _topic_type not in (TOPIC_TYPE.COLUMN_ARTICLE, TOPIC_TYPE.USER_ARTICLE):
            return

        _, video_list = get_data_from_rich_text(article_obj.answer_richtext, u'//video[not(@name="new_video")]/@src')
        if video_list:
            get_qiniu_persistent_ids.delay(
                source_id=article_obj.id,
                video_type=VIDEO_SOURCE_TYPE.ARTICLE,
                url_list=video_list
            )

    except Problem.DoesNotExist as e:
        return
