# coding=utf-8
from talos.models.topic import Problem, TopicRankingScore
from data_sync.utils import tzlc
from gm_types.gaia import TOPIC_TYPE
from utils.rpc import get_rpc_invoker


def get_problems(pks):
    """

    :param pks:
    :return:
    """
    r = get_rpc_invoker()
    problems = Problem.objects.filter(pk__in=pks)

    data = []
    params = []

    for p in problems:
        tids = [pt.tag_id for pt in p.problemtag_set.all()]
        params.append({
            "pid": p.id, "uid": p.user_id, "tids": tids,
            "sid": p.diary and p.diary.service_id,
            "did": p.diary and p.diary.doctor_id,
        })
        data.append(get_problem(p))

    extras = r['api/dbmw/get_problem_extra'](params=params).unwrap()
    assert len(extras) == len(data)

    for idx, topic in enumerate(data):
        topic['user'].update(extras[idx].pop('user', {}))
        topic.update(extras[idx])

    return data


def get_problem(instance):
    p = instance

    res = {
        'id': p.id,
        'diary_id': p.diary_id,
        'doctor_num': p.doctor_num,
        'created_time': tzlc(p.created_time),
        'content': p.answer,
        'is_public': p.is_public,
        'is_online': p.is_online,
        'is_elite': p.selected_qa,
        'is_sink': p.is_sink,
        'is_topic': p.is_topic,
        'pgc_category': p.pgc_classfy.id if p.pgc_classfy else None,
        'flag': p.flag,
        'topic_type': p.topic_type,
        'private_status': p.private_status,
        'title': p.ask,
        'title2': p.title,
        'channel_headline': p.channel_headline,
        'user': {
            'id': p.user_id,
            'last_name': p.user.nickname,
        },
        'content_level': -1 #所属日记本星级
    }

    try:
        p.video
        res['has_video'] = True
    except Problem.video.RelatedObjectDoesNotExist:
        res['has_video'] = False

    if p.topic_type in (TOPIC_TYPE.ASK, TOPIC_TYPE.TOPIC):
        res['ranking_popularity'] = TopicRankingScore.get_pop_score(topic=p)
    else:
        res['ranking_popularity'] = 0.0

    if p.doctor_num > 0:
        res['has_doctor_reply'] = True  # 是否有医生回复
    else:
        res['has_doctor_reply'] = False

    if p.images.count() > 0:
        res['has_image'] = True  # 是否有图
    else:
        res['has_image'] = False

    if p.diary:
        if (not p.diary.is_online):
            res['is_online'] = False  # 关联日记本的帖子如果日记本下线则帖子也下线
        if p.diary.is_sink:
            res['is_sink'] = True  # 关联日记本的帖子如果日记本下沉则帖子也下沉

        res['content_level'] = p.diary.content_level
    problem_replys = p.topicreply_set.all()
    res['replys_num'] = problem_replys.count()
    res['replys'] = [{
                         'id': r.id,
                         'content': r.content,
                     } for r in problem_replys]

    last_update_time = p.last_modified
    res['last_update_time'] = tzlc(last_update_time)

    try:
        if res['replys_num'] > 0:
            problem_replys_sorted = sorted(list(problem_replys), key=lambda item: item.reply_date, reverse=True)
            res['latest_reply_time'] = tzlc(problem_replys_sorted[0].reply_date)
        else:
            res['latest_reply_time'] = res['created_time']
    except:
        res['latest_reply_time'] = res['created_time']

    popularity = 0
    popularity += problem_replys.count()
    popularity += p.votes.count()
    res['popularity'] = popularity

    res['topic_score'] = [{
                              'user_id': ts.user.id,
                              'score': ts.score,
                          } for ts in p.topic_score.all()]
    res['topic_vote_count'] = p.vote_amount
    return res