# -*- coding: utf-8 -*-
import json
import datetime
from django.conf import settings
from django.db.models import Q
from gm_types.mimas import (
    TRACTATE_PLATFORM,
    TRACTATE_REPLY_HIGHLIGHT
)
from gm_types.error import ERROR as CODES
from gm_types.gaia import USER_TYPE, DOCTOR_TYPE
from gm_dataquery.dict_mixin import to_dict

from gm_rpcd.all import RPCDFaultException
from utils.rpc import gen, get_current_user
from talos.portal import get_doctor_from_user_ids
from talos.cache.base import reply_cache as reply_msg_cache
from talos.tools.replies_tool import ReplyTool

from talos.libs.datetime_utils import get_timestamp_or_none
from qa.utils.decorator import listing
from talos.rpc import bind_context, bind
from talos.services import (
    get_user_from_context,
    UserService,
    UserConvertService,
)

from talos.services.doctor import DoctorService
from talos.services.soft_article.soft_article import SoftArticleService
from talos.tools.tractate_reply_tool import reply_update_cache
from talos.tasks.tractate import doctor_reply_push
from talos.services.soft_article.reply import SoftArticleReplyService, SoftArticle, SoftArticleReply
from talos.services.soft_article.vote import SoftArticleReplyVoteService

uri_pre = 'mimas/soft_article_reply'

class Test():
    pass


def handle_args(conditions):
    base_query = Q()
    if conditions.get("start_time"):
        times = datetime.datetime.fromtimestamp(conditions.get("start_time"))
        base_query &= Q(create_time__gte=times)
    if conditions.get("end_time"):
        times = datetime.datetime.fromtimestamp(conditions.get("end_time"))
        base_query &= Q(create_time__lte=times)
    if conditions.get("status", None) != None:
        base_query &= Q(is_reply=conditions.get("status"))
    if conditions.get('title'):
        s_article_ids = SoftArticle.objects.using(settings.SLAVE_DB_NAME)\
                                           .filter(title__contains=conditions.get('title'))\
                                           .values_list('id', flat=True)
        base_query &= Q(softarticle_id__in=list(s_article_ids))
    return base_query


@bind(uri_pre + '/list')
def get_my_reply_list(merchant_id, conditions={}, page=1, count=10):
    """医生后台专用列表"""
    SECOND_COUNT, START_INDEX = 5, 0
    offset = count * (page - 1)
    r_query = handle_args(conditions)
    reply_all = SoftArticleReply.objects.filter(r_query, merchant_id=merchant_id, top_id=0).order_by('-id')
    replies = list(reply_all[offset:offset+count].values())

    top_reply_user_ids = [item.get('user_id') for item in replies]
    top_users = UserService.get_users_by_user_ids(top_reply_user_ids)

    second_user_ids, second_doctor_ids, repied_ids, article_ids = [], [], [], []
    for top_reply_info in replies:
        article_ids.append(top_reply_info.get('softarticle_id'))
        second_reply = SoftArticleReplyService.get_second_reply_by_top_id(top_id=top_reply_info.get('id'),
                                                                          count=SECOND_COUNT, offset=START_INDEX)
        top_reply_info['create_time'] = int(top_reply_info['create_time'].timestamp())
        top_reply_info['update_time'] = int(top_reply_info['update_time'].timestamp())
        top_reply_info['reply_count'] = int(SoftArticleReplyService.top_reply_count(top_reply_info.get('id'))) or 0

        second_user_ids.extend([reply.get('user_id') for reply in second_reply])
        second_doctor_ids.extend([reply.get('doctor_id') for reply in second_reply])
        repied_ids.extend([reply.get('replied_id') for reply in second_reply])


        # 处理一级评论的用户信息
        top_reply_info['replies'] = second_reply
        if top_reply_info.get('user_id') not in top_users:
            continue
        top_reply_info['user_name'] = top_users[top_reply_info.get('user_id')].nickname
        top_reply_info['user_portrait'] = top_users[top_reply_info.get('user_id')].portrait

    relations = SoftArticleService.get_relation_data(soft_article_ids=article_ids)
    soft_articles = SoftArticleService.get_dict_by_soft_article_ids(soft_article_ids=article_ids)

    # 处理二级评论、被评论用户信息
    replied_infos = SoftArticleReplyService.get_replies_info(reply_ids=repied_ids)
    replyed_user_ids = [value.get('user_id') for key, value in replied_infos.items()]
    second_user_ids = list(set(second_user_ids + replyed_user_ids))
    second_users = UserService.get_users_by_user_ids(second_user_ids)

    replyed_doctor_ids = [value.get('doctor_id') for key, value in replied_infos.items()]
    second_doctor_ids = list(set(second_doctor_ids + replyed_doctor_ids))
    doctor_infos = DoctorService.get_doctor_by_doctor_ids_v1(doctor_ids=second_doctor_ids)
    second_doctors = {doctor_key: doctor_values.get('meta') for doctor_key, doctor_values in doctor_infos.items()}

    # 给二级评论补充用户信息
    for top_reply_info in replies:
        top_reply_info['service_data'] = relations.get(top_reply_info.get('softarticle_id')).get('service')
        top_reply_info['diary_data'] = relations.get(top_reply_info.get('softarticle_id')).get('diary')
        top_reply_info['article_info'] = soft_articles.get(top_reply_info.get('softarticle_id'))
        for second_reply in top_reply_info['replies']:
            if second_reply.get('doctor_id') in second_doctors:
                second_reply['doctor_name'] = second_doctors[second_reply.get('doctor_id')].get('name')
                second_reply['doctor_portrait'] = second_doctors[second_reply.get('doctor_id')].get('portrait')

            if second_reply.get('user_id') in second_users:
                second_reply['user_name'] = second_users[second_reply.get('user_id')].nickname
                second_reply['user_portrait'] = second_users[second_reply.get('user_id')].portrait

            replied_info = replied_infos.get(second_reply.get('replied_id'), {})
            if replied_info.get('user_id') in second_users:
                second_reply['replied_user_id'] = second_users[replied_info.get('user_id')].id
                second_reply['replied_user_name'] = second_users[replied_info.get('user_id')].nickname
                second_reply['replied_user_portrait'] = second_users[replied_info.get('user_id')].portrait

            if replied_info.get('doctor_id') in second_doctors:
                second_reply['replied_doctor_id'] = replied_info.get('doctor_id')
                second_reply['replied_doctor_name'] = second_doctors[replied_info.get('doctor_id')].get('name')
                second_reply['replied_doctor_portrait'] = second_doctors[replied_info.get('doctor_id')].get('portrait')

    return {"total": reply_all.count(), "data": replies}


@bind(uri_pre + '/reply_create')
def reply_create(soft_article_id, top_id, reply_id=None, content=None):
    """
    医生后台帖子回复
    :return:
    """

    soft_article = SoftArticle.objects.filter(id=soft_article_id, platform=TRACTATE_PLATFORM.DOCTOR).first()
    if not soft_article:
        return {"error": 1, "msg": "帖子不存在或已下线"}

    reply = SoftArticleReplyService.create(content=content, doctor_id=soft_article.doctor_id,
                                           soft_article_id=soft_article_id, merchant_id=soft_article.merchant_id,
                                           extra={"top_id": top_id, "replied_id": reply_id,
                                                  "source_id": TRACTATE_PLATFORM.DOCTOR})

    SoftArticleReplyService.update_reply_count(top_reply_id=top_id)

    if reply_id:
        s_reply = SoftArticleReplyService.get_by_id(pk=reply_id)
        s_reply.is_reply = True
        s_reply.save()

    doctor_reply_push.delay(soft_article_id=soft_article_id, reply_id=reply.id)

    doctor_info = DoctorService.get_doctor_from_doctor_id(reply.doctor_id)

    return {
        "id": reply.id,
        "soft_article_id": reply.softarticle_id,
        "replied_id": reply.replied_id,
        "doctor_id": reply.doctor_id,
        "doctor_name": doctor_info.name,
        "doctor_portrait": doctor_info.portrait,
        "content": reply.content,
        "vote_num": 0,
        "create_time": reply.create_time.timestamp(),
        "is_vote": False,
        "replied_user_id": "",
        "replied_user_name": "",
        "replied_user_portrait": "",
    }


@bind_context(uri_pre + '/create')
def create_reply(ctx, soft_article_id, content, top_id=None, reply_id=None):
    """
    用户发布评论
    """
    user = get_user_from_context(ctx)
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    article = SoftArticleService.healthy(soft_article_id)

    result = {
        "replied_user_id": "",
        "replied_user_portrait": "",
        "replied_user_name": ""
    }

    if not top_id and not reply_id:
        top_id = 0
    if reply_id and not top_id:
        top_id = reply_id

    if reply_id:
        replied_info = SoftArticleReplyService.get_by_id(pk=reply_id)
        if replied_info.user_id:
            replied_user_info = UserConvertService.get_user_info_by_user_id(replied_info.user_id)
            result.update({
                "replied_user_id": replied_info.user_id,
                "replied_user_portrait": replied_user_info.get("portrait", ""),
                "replied_user_name": replied_user_info.get("user_name", ""),
                "replied_user_type": USER_TYPE.NORMAL,
                "replied_user_info": replied_user_info,
            })
        if replied_info.doctor_id:
            doctor_info = UserConvertService.format_doctor_analogy_user_info_by_doctor_id(replied_info.doctor_id)
            result.update({
                "replied_user_id": doctor_info.get("user_id", 0),
                "replied_user_portrait": doctor_info.get("portrait", ""),
                "replied_user_name": doctor_info.get("user_name", ""),
                "replied_user_type": USER_TYPE.EXPERT,
                "replied_user_info": doctor_info,
            })

    reply = SoftArticleReplyService.create(content=content, user_id=user.id, merchant_id=article.merchant_id,
                                           soft_article_id=soft_article_id, extra={"top_id": top_id, "replied_id": reply_id,
                                                  "source_id": TRACTATE_PLATFORM.GM})

    # replied_user_id = replied_info.user_id if reply_id else None
    # if replied_user_id and user.id != replied_user_id:
    #     rt = ReplyTool(reply_msg_cache, replied_user_id)
    #     rt.receive_soft_article_reply(reply.id)

    doctor_reply_push.delay(soft_article_id=soft_article_id, reply_id=reply.id)

    # 更新一级评论下的评论数
    if top_id:
        result.update({"top_id": int(top_id)})
        SoftArticleReplyService.update_reply_count(top_reply_id=top_id)
    else:
        result.update({"replies": []})

    SoftArticleService.incr_article_reply(soft_article_id=soft_article_id)

    result.update({
        'id': reply.id,
        'content': reply.content,
        'user_type': USER_TYPE.NORMAL,
        'create_time': get_timestamp_or_none(reply.create_time),
        "replied_id": int(reply_id) if reply_id else '',
        "user_name": user.nickname,
        "user_id": user.id,
        "user_portrait": user.portrait,
        "is_vote": False,
        "vote_num": 0,
        "status": TRACTATE_REPLY_HIGHLIGHT.DARK,
        "reply_count": 0,
        'reply_user_info': UserConvertService.get_user_info_by_user_id(user.id)
    })
    return result


@bind(uri_pre + '/top_list')
def top_reply_list(soft_article_id, offset=0, count=10):
    """一级评论列表"""

    top_infos = SoftArticleReplyService.list_top_reply_by_soft_article_id(
        soft_article_id=soft_article_id, offset=offset, count=count)

    user_ids = [top.get("user_id") for top in top_infos]

    user_infos = UserConvertService.get_user_info_by_user_ids(user_ids=user_ids)

    for top_info in top_infos:
        _user_info = user_infos.get(top_info.get('user_id', 0), {})
        top_info.update({
            "user_name": _user_info.get("user_name", ""),
            "user_portrait": _user_info.get("user_portrait", ""),
            "reply_user_info": _user_info,
        })

    return top_infos


@bind(uri_pre + '/list_top_reply')
def get_top_list_by_soft_articles(soft_article_ids=[], offset=0, top_count=2):
    """多个软文的一级评论"""
    result, user_ids = {}, []
    for soft_article_id in soft_article_ids:
        soft_article_info = SoftArticleReplyService.list_top_reply_by_soft_article_id(
            soft_article_id=soft_article_id, offset=offset, count=top_count)
        user_ids.extend([reply.get('user_id') for reply in soft_article_info])
        result[str(soft_article_id)] = soft_article_info

    users = UserConvertService.get_user_info_by_user_ids(user_ids)

    for k, item in result.items():
        for reply in item:
            _user_info = users.get(reply.get("user_id", 0), {})
            if not _user_info:
                continue

            reply.update({
                "user_nickname": _user_info.get("user_name", ""),
                "user_portrait": _user_info.get("portrait", ""),
                "reply_user_info": _user_info,
            })

    return result


@bind(uri_pre + '/second_list')
def get_second_list_by_top_id(top_id, offset=0, count=10, is_doctor=False):
    """一级评论的子评论"""
    if not is_doctor:
        second_list = SoftArticleReplyService.get_second_reply_by_top_id(top_id=top_id, offset=offset, count=count)
    else:
        second_list = SoftArticleReplyService.get_second_reply_by_top_id(top_id=top_id, offset=offset)

    user_ids, replied_ids, doctor_ids = set(), set(), set()
    for second_info in second_list:
        _user_id = second_info.get("user_id", 0)
        _replied_id = second_info.get("replied_id", 0)
        _doctor_id = second_info.get("doctor_id", "")

        if _user_id:
            user_ids.add(_user_id)

        if _replied_id:
            replied_ids.add(_replied_id)

        if _doctor_id:
            doctor_ids.add(_doctor_id)

    replied_infos = SoftArticleReplyService.get_replies_info(reply_ids=replied_ids)
    user_ids.update(set(reply_value.get('user_id', 0) for reply_key, reply_value in replied_infos.items()))
    doctor_ids.update(set(reply_value.get('doctor_id', "") for reply_key, reply_value in replied_infos.items()))

    user_infos = UserConvertService.get_user_info_by_user_ids(user_ids=user_ids)
    doctor_infos = UserConvertService.format_doctor_analogy_user_info_by_doctor_ids(doctor_ids)

    for second_info in second_list:
        _user_info = user_infos.get(second_info.get('user_id', 0), {})
        _doctor_info = doctor_infos.get(second_info.get('doctor_id', ""), {})

        if _user_info:
            second_info.update({
                "user_type": USER_TYPE.NORMAL,
                "user_name": _user_info.get("user_name", ""),
                "user_portrait": _user_info.get("portrait", ""),
                "reply_user_info": _user_info,
            })

        if _doctor_info:
            second_info.update({
                "doctor_id": _doctor_info.get("doctor_id", ""),
                "doctor_name": _doctor_info.get("user_name", ""),
                "doctor_portrait": _doctor_info.get("portrait", ""),
                "reply_doctor_info": _doctor_info,
            })

            if _doctor_info.get('doctor_type') == DOCTOR_TYPE.OFFICER:
                second_info['user_type'] = USER_TYPE.OFFICER
                second_info['doctor_id'] = _doctor_info.get('hospital_id', "")

        reply_data = replied_infos.get(second_info.get('replied_id'), {})
        _replied_user_info = user_infos.get(reply_data.get('user_id', 0), {})
        _replied_doctor_info = doctor_infos.get(reply_data.get('doctor_id', ""), {})

        if _replied_user_info:
            second_info.update({
                "replied_user_type": USER_TYPE.NORMAL,
                "replied_user_id": reply_data.get('user_id'),
                "replied_user_name": _replied_user_info.get("user_name", ""),
                "replied_user_portrait": _replied_user_info.get("portrait", ""),
                "replied_user_info": _replied_user_info,
            })

        if _replied_doctor_info:
            second_info.update({
                "replied_doctor_id": reply_data.get('doctor_id'),
                "replied_doctor_name": _doctor_info.get("user_name", ""),
                "replied_doctor_portrait": _doctor_info.get("portrait", ""),
                "replied_doctor_info": _replied_doctor_info,
            })

            if _doctor_info.get('doctor_type') == DOCTOR_TYPE.OFFICER:
                second_info['replied_user_type'] = USER_TYPE.OFFICER
                second_info['replied_doctor_id'] = _doctor_info.get('hospital_id', "")

    return second_list


@bind(uri_pre + '/reply_popup')
# @listing()
def get_reply_in_popup(soft_article_id, offset=0, count=5, user_id=None, sort_condition=None):
    """评论弹窗~获取评论（一级和二级）"""
    SECOND_COUNT, START_INDEX = 2, 0
    SoftArticleService.healthy(soft_article_id)

    # 一级评论数据
    top_reply_infos = SoftArticleReplyService.list_top_reply_by_soft_article_id(
        soft_article_id=int(soft_article_id), offset=int(offset), count=int(count), sort_condition=sort_condition
    )

    top_reply_user_ids, vote_reply_ids = set(), []
    second_user_ids, repied_ids, second_doctor_ids = set(), [], set()

    # 一级评论处理用户，点赞状态，二级评论及子评论逻辑
    for item in top_reply_infos:
        _user_id = item.get("user_id", 0)
        _id = item.get("id", 0)

        if _user_id:
            top_reply_user_ids.add(_user_id)

        if _id:
            vote_reply_ids.append(_id)

        # 二级评论
        second_reply = SoftArticleReplyService.get_second_reply_by_top_id(
            top_id=_id,
            count=SECOND_COUNT,
            offset=START_INDEX,
            sort_condition=sort_condition
        )

        # 处理一级评论的子评论
        item['replies'] = second_reply
        for reply in second_reply:
            _reply_user_id = reply.get("user_id", 0)
            _replied_id = reply.get("replied_id", 0)
            _second_reply_id = reply.get("id", 0)
            _second_doctor_id = reply.get("doctor_id", "")

            if _reply_user_id:
                second_user_ids.add(_reply_user_id)
            if _replied_id:
                repied_ids.append(_replied_id)
            if _second_reply_id:
                vote_reply_ids.append(_second_reply_id)
            if _second_doctor_id:
                second_doctor_ids.add(_second_doctor_id)

    # 处理二级评论、被评论用户信息
    replied_infos = SoftArticleReplyService.get_replies_info(reply_ids=repied_ids)
    replyed_user_ids, replyed_doctor_ids = set(), set()
    for key, value in replied_infos.items():
        _replyed_user_id = value.get("user_id", 0)
        _replyed_doctor_id = value.get("doctor_id", "")

        if _replyed_user_id:
            replyed_user_ids.add(_replyed_user_id)

        if _replyed_doctor_id:
            replyed_doctor_ids.add(_replyed_doctor_id)

    # 取所有用户信息
    _all_user_ids = top_reply_user_ids | second_user_ids | replyed_user_ids
    all_user_infos = UserConvertService.get_user_info_by_user_ids(_all_user_ids)
    # 取所有医生信息
    _all_doctor_ids = second_doctor_ids | replyed_doctor_ids
    second_doctors = UserConvertService.format_doctor_analogy_user_info_by_doctor_ids(_all_doctor_ids)

    # 取所有已经被点赞的评论id
    voted_reply_ids = SoftArticleReplyVoteService.get_vote_status(
        user_id=user_id, softarticle_id=soft_article_id, reply_ids=vote_reply_ids)

    # 评论信息处理
    for top_reply_info in top_reply_infos:

        top_reply_user_info = all_user_infos.get(top_reply_info.get("user_id", 0), {})
        if not top_reply_user_info:
            continue

        top_reply_info.update({
            "user_name": top_reply_user_info.get("user_name", ""),
            "user_portrait": top_reply_user_info.get("portrait", ""),
            "is_vote": bool(top_reply_info.get("id", 0) in voted_reply_ids),
            "top_reply_user_info": top_reply_user_info,
        })

        # 二级评论信息处理
        for second_reply in top_reply_info.get('replies', []):
            second_reply_user_info = all_user_infos.get(second_reply.get('user_id', 0), {})
            second_reply_doctor_info = second_doctors.get(second_reply.get('doctor_id', ""), {})

            second_reply['is_vote'] = True if second_reply['id'] in voted_reply_ids else False

            if second_reply_user_info:
                second_reply.update({
                    "user_type": USER_TYPE.NORMAL,
                    "user_name": second_reply_user_info.get("user_name", ""),
                    "user_portrait": second_reply_user_info.get("portrait", ""),
                    "second_reply_user_info": second_reply_user_info,
                })

            if second_reply_doctor_info:
                second_reply.update({
                    "doctor_id": second_reply.get('doctor_id', ""),
                    "doctor_name": second_reply_doctor_info.get("user_name", ""),
                    "doctor_portrait": second_reply_doctor_info.get("portrait", ""),
                    "second_reply_doctor_info": second_reply_doctor_info,
                })
                if second_reply_doctor_info.get('doctor_type') == DOCTOR_TYPE.OFFICER:
                    second_reply['user_type'] = USER_TYPE.OFFICER
                    second_reply['doctor_id'] = second_reply_doctor_info.get('hospital_id', "")

            replied_info = replied_infos.get(second_reply.get('replied_id'), {})
            replied_info_user_info = all_user_infos.get(replied_info.get("user_id", 0), {})
            replied_info_doctor_info = second_doctors.get(replied_info.get("doctor_id", ""), {})

            if replied_info_user_info:
                second_reply.update({
                    "replied_user_type": USER_TYPE.NORMAL,
                    "replied_user_id": replied_info.get('user_id'),
                    "replied_user_name": replied_info_user_info.get("user_name", ""),
                    "replied_user_portrait": replied_info_user_info.get("portrait", ""),
                    "replied_user_info": replied_info_user_info,
                })

            if replied_info_doctor_info:
                second_reply.update({
                    "replied_doctor_id": replied_info.get('doctor_id'),
                    "replied_doctor_name": replied_info_doctor_info.get("user_name", ""),
                    "replied_doctor_portrait": replied_info_doctor_info.get("portrait", ""),
                    "replied_doctor_info": replied_info_doctor_info,
                })

                if replied_info_doctor_info.get('doctor_type') == DOCTOR_TYPE.OFFICER:
                    second_reply['replied_user_type'] = USER_TYPE.OFFICER
                    second_reply['replied_doctor_id'] = replied_info_doctor_info.get('hospital_id', "")

    return top_reply_infos


@bind(uri_pre + '/light_reply')
def get_light_reply(soft_article_id, user_id=None, target_reply_id=None):
    """获取高亮评论  针对用户"""
    SECOND_COUNT, START_INDEX = 2, 0
    more_highlight = True

    if not target_reply_id:
        return gen(CODES.PARAMS_INCOMPLETE)

    top_info = SoftArticleReplyService.get_highlight_reply(target_reply_id=target_reply_id)

    if not top_info:
        return []

    user_ids, replied_ids, vote_reply_ids, doctor_ids = set(), set(), set(), set()
    user_ids.add(top_info.get('user_id'))
    vote_reply_ids.add(top_info.get('id'))
    doctor_ids.add(top_info.get('doctor_id'))

    second_replies = SoftArticleReplyService.get_second_reply_by_top_id(
        top_id=top_info.get('id'), count=SECOND_COUNT, target_reply_id=target_reply_id
    )
    for reply in second_replies:
        _replied_id = reply.get('replied_id', 0)
        _reply_user_id = reply.get('user_id', 0)
        _reply_doctor_id = reply.get('doctor_id', "")
        _second_reply_id = reply.get("id", 0)

        if _reply_user_id:
            user_ids.add(_reply_user_id)

        if _replied_id:
            replied_ids.add(_replied_id)

        if _reply_doctor_id:
            doctor_ids.add(_reply_doctor_id)

        if _second_reply_id:
            vote_reply_ids.add(_second_reply_id)

    #获取用户是否点过赞
    voted_reply_ids = SoftArticleReplyVoteService.get_vote_status(
        user_id=user_id, softarticle_id=soft_article_id, reply_ids=vote_reply_ids)

    replied_infos = SoftArticleReplyService.get_replies_info(reply_ids=replied_ids)
    for key, value in replied_infos.items():
        user_ids.add(value.get('user_id', 0))
        doctor_ids.add(value.get('doctor_id', ""))

    all_user = UserConvertService.get_user_info_by_user_ids(user_ids)
    second_doctors = UserConvertService.format_doctor_analogy_user_info_by_doctor_ids(doctor_ids)

    for second_reply in second_replies:
        second_reply_user_info = all_user.get(second_reply.get("user_id", 0), {})
        second_reply_doctor_info = all_user.get(second_reply.get("doctor_id", ""), {})

        if not top_info['status'] and second_reply['status'] == TRACTATE_REPLY_HIGHLIGHT.LIGHT:
            more_highlight = False

        second_reply['is_vote'] = True if second_reply.get('id') in voted_reply_ids else False

        if second_reply_user_info:
            second_reply.update({
                "user_name": second_reply_user_info.get("user_name", ""),
                "user_portrait": second_reply_user_info.get("portrait", ""),
                "second_user_info": second_reply_user_info,
            })

        if second_reply_doctor_info:
            second_reply.update({
                "doctor_name": second_reply_doctor_info.get("user_name", ""),
                "doctor_portrait": second_reply_doctor_info.get("portrait", ""),
                "second_doctor_info": second_reply_doctor_info,
            })

        replied_info = replied_infos.get(second_reply.get('replied_id'), {})
        replied_info_user_info = all_user.get(replied_info.get("user_id", 0), {})
        replied_info_doctor_info = second_doctors.get(replied_info.get("doctor_id", ""), {})

        if replied_info_user_info:
            second_reply.update({
                "replied_user_id": replied_info.get('user_id'),
                "replied_user_name": replied_info_user_info.get("user_name", ""),
                "replied_user_portrait": replied_info_user_info.get("portrait", ""),
                "replied_user_info": replied_info_user_info,
            })

        if replied_info_doctor_info:
            second_reply.update({
                "replied_doctor_id": replied_info.get('doctor_id'),
                "replied_doctor_name": replied_info_doctor_info.get("user_name", ""),
                "replied_doctor_portrait": replied_info_doctor_info.get("portrait", ""),
                "replied_doctor_info": replied_info_doctor_info,
            })

    top_user_info = all_user.get(top_info.get("user_id", 0), {})
    top_info.update({
        "replies": second_replies,
        "user_id": top_user_info.get("user_id", 0),
        "user_name": top_user_info.get("user_name", ""),
        "user_portrait": top_user_info.get("portrait", ""),
        "is_vote": True if top_info.get('id') in voted_reply_ids else False,
        "top_reply_user_info": top_user_info,
    })

    if not top_info['status'] and more_highlight:
        top_info['status'] = TRACTATE_REPLY_HIGHLIGHT.MORE_LIGHT

    return [top_info]


@bind_context(uri_pre + 'receive', with_context=True)
def get_replies_by_ids(ctx, replies_ids):

    user = get_user_from_context(ctx)
    if not user:
        return gen(CODES.LOGIN_REQUIRED)

    if not replies_ids:
        return {}

    replies_dict = SoftArticleReplyService.get_replies_info(reply_ids=replies_ids)

    user_ids = []
    replied_ids = []
    soft_article_ids = []
    for _, reply in replies_dict.items():
        user_ids.append(reply["user_id"])
        replied_ids.append(reply["replied_id"])
        soft_article_ids.append(reply["softarticle_id"])

    replied_dict = SoftArticleReplyService.get_replies_info(reply_ids=replied_ids)
    users_dict = UserService.get_users_by_user_ids(user_ids)
    #Todo需要修改
    soft_article_dict = SoftArticleService.get_soft_article_by_ids(soft_article_ids)

    result = {}
    for reply_id, reply in replies_dict.items():

        reply_user = users_dict.get(reply["user_id"], {})

        replied = {}
        if reply["replied_id"]:
            item = replied_dict.get(reply["replied_id"], {})
            if item:
                replied = {
                    "id": reply["replied_id"],
                    "content": reply["content"],
                }

        soft_article = {}
        soft_article_obj = soft_article_dict.get(reply["softarticle_id"])
        if soft_article_obj:
            soft_article = {
                "id": soft_article_obj.id,
                "content": soft_article_obj.content,
                "user_id": soft_article_obj.user_id
            }

        info = {
            "id": reply["id"],

            "reply_date": reply["create_time"],
            "reply_content": reply["content"],

            "soft_article": soft_article,

            "replied": replied,
            "reply_user": {
                "id": reply_user.id,
                "name": reply_user.nickname,
                "portrait": reply_user.portrait,
            },
            "author": {
                "id": user.id,
                "name": user.nickname,
                "portrait": user.portrait,
            },
        }
        result[str(reply_id)] = info

    return result
